TITLE: c++ interview question with "no loop" solution

(Newsgroups: comp.lang.c++.moderated, 19 Mar 2000)

KRASKA: <jkraska1@san.rr.com>

[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 <francisG@robinton.demon.co.uk>

> 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 <dietmar.kuehl@claas-solutions.de>

Here is a non-recursive version which does not use any looping
construct:

  #include <algorithm>
  #include <vector>
  #include <iterator>
  #include <iostream>

  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<int>(std::cout, "\n"),
                    count, up);
    std::generate_n(std::ostream_iterator<int>(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 <int N>
    inline void printUp()
    {
        cout << N << endl;   // print N
        printUp<N+1>();      // print N+1
    }

    template<>
    inline void printUp<100>()
    {
        // stop at 100
    }

    template <int N>
    inline void printDown()
    {
        cout << N << endl;    // print N
        printDown<N-1>();     // 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 <iostream>

  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








