Object Oriented Approach to Display a sequence of numbers without any For-Loop or Recursion

Suppose we have to display a sequence of numbers like from 10 to 20 i.e.

10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20

without using any for-loop and recursion.

Solution:

Advertisements

We will use two concepts here,

  • Constructor
  • Static Variable

[showads ad=inside_post]

Create a Structure with a static member variable i.e. a Counter. Then in this structure’s constructor display the Counter and increment it.

 

struct NumberGenerator
{
   static int mCounter;
   NumberGenerator()
   {
      std::cout<<mCounter<<std::endl;
      mCounter++;
   }
};

int NumberGenerator::mCounter = 10;

Now in the main function just Create 11 Objects of this Structure and hence constructor will be called 10 times.
Inside each constructor call, a static counter will be printed and its value will be incremented.

int main()
{
    NumberGenerator objArr[11];
    return 0;
}

Thus a sequence of integers will be printed.

 

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top