TITLE: c++ interview question with "no loop" solution (Newsgroups: comp.lang.c++.moderated, 19 Mar 2000) KRASKA: [snip] >> The candidate must write a function which prints from 1 to >> 100 and back to 1 without making use of for, while, goto, >> or any looping constructs what-so-ever. GLASSBOROW: Francis Glassborow > If that last condition is true then I cannot imagine (OK I am > sometimes a bit short of imagination) what you expect as a > solution to that problem. Are you really expecting the > programmer to use some form of recursion? KUEHL: Dietmar Kuehl Here is a non-recursive version which does not use any looping construct: #include #include #include #include static int const count = 100; int up() { static int rc = 1; return rc++; } int down() { static int rc = count; return rc--; } int main() { std::generate_n(std::ostream_iterator(std::cout, "\n"), count, up); std::generate_n(std::ostream_iterator(std::cout, "\n"), count, down); } ------------------------------------------------------------------- TRIBBLE: David R Tribble [mailto:david@tribble.com], Aug 1 2000 [snip] Of course, something this redundant could probably be done using some recursive template magic (pardon me if I don't get the exact syntax correct): template inline void printUp() { cout << N << endl; // print N printUp(); // print N+1 } template<> inline void printUp<100>() { // stop at 100 } template inline void printDown() { cout << N << endl; // print N printDown(); // print N-1 } template<> inline void printDown<0>() { // stop at 0 } int main() { printUp<1>(); // print 1 to 99 printDown<100>(); // print 100 to 1 return 0; } This could probably be optimized. (But who would want to?) --------------------------------------------------------------- [ This is another solution to the C++ "aptitude" question below: The candidate must write a function which prints from 1 to 100 and back to 1 without making use of for, while, goto, or any looping constructs what-so-ever. - Allan ] EDWARDS: Carl Edwards [cedwards@vitesse.com], 1 Aug 2000 Great question, I had an interview candidate answer something similar to this: #include class A { public: A() { cout << count++ << endl; } ~A() { cout << --count << endl; } static unsigned count; }; unsigned A::count; int main(int argc, char** argv) { A::count = 1; A a[100]; return(0); } _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com