Following is a C++ program that prints 1 to 100 without loop and without recursion.
1 2 3 .. .. 98 99 100
The program prints all numbers from 1 to n without using a loop and recursion. The concept used in this program is Template Metaprogramming.
Let us see how this works. Templates in C++ allow non-datatypes also as parameter. Non-datatype means a value, not a datatype. For example, in the above program, N is passed as a value which is not a datatype. A new instance of a generic class is created for every parameter and these classes are created at compile time. In the above program, when compiler sees the statement “PrintOneToN<
Following is another approach to print 1 to 100 without loop and recursion.
The output of this program is same as above program. In the above program, class A has a static variable ‘a’, which is incremented with every instance of A. The default constructor of class A prints the value of ‘a’. When we create an array of objects of type A, the default constructor is called for all objects one by one. Value of ‘a’ is printed and incremented with every call. Therefore, we get all values from 1 to 100 printed on the screen.
Thanks to Lakshmanan for suggesting this approach.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- How to print a number 100 times without using loop and recursion in C?
- Print a character n times without using loop, recursion or goto in C++
- Print a number 100 times without using loop, recursion and macro expansion in C?
- Write a C program to print "GfG" repeatedly without using loop, recursion and any control structure?
- Print a pattern without using any loop
- How will you print numbers from 1 to 100 without using loop? | Set-2
- How will you print numbers from 1 to 100 without using loop?
- Print pattern using only one loop | Set 1 (Using setw)
- C++ Program to print an Array using Recursion
- How to print N times without using loops or recursion ?
- Print alternate nodes of a linked list using recursion
- Programs to print Triangle and Diamond patterns using recursion
- Print substring of a given string without using any string function and loop in C
- C/C++ For loop with Examples
- C/C++ do while loop with Examples