Monday 5 May 2014

C++ program to print 1 to N numbers without a loop

C++ program to print 1 to N numbers without a loop



I remember the day when i was asked about this question of printing 1 to N numbers without using a loop or a condition or something else by my senior. At that time the only thing that came to my mind is Recursion. But after knowing some concepts of Object Oriented Programming, I nodded that yes, it is indeed possible.


You remember the static data type in C++ ?
Yes, it maintains a single copy for the whole class created.
By now many of you might have got the Idea? Here's the Simple C++ code to do this.



#include <iostream>
using namespace std;
class increment
{
  static int foo;
   public:
    increment()
    {
      foo++;
      cout<<foo<<endl;
    }
};




int increment::foo=0; //Initializing static data type.




int main(void)
{
  increment buff[10]; //constructor called 10 times.
  return (0);
}


Here's the Sample output:


Check this code through Online Compiler.

No comments:

Post a Comment