Open In App

Print 1 to 100 in C++ Without Loops and Recursion

We can print 1 to 100 without using loops and recursion using three approaches discussed below:

1) Template Metaprogramming: Templates in C++ allow non-datatypes also as parameters. Non-datatype means a value, not a datatype. 



Example:




// CPP Program to print 1 to 100
// without loops and recursion
#include <iostream>
using namespace std;
 
template <int N> class PrintOneToN {
public:
    static void print()
    {
        PrintOneToN<N - 1>::print();
       
        // Note that this is not recursion
        cout << N << endl;
    }
};
 
template <> class PrintOneToN<1> {
public:
    static void print() { cout << 1 << endl; }
};
 
// Driver Code
int main()
{
    const int N = 100;
    PrintOneToN<N>::print();
    return 0;
}

Output



1
2
3
..
..
98
99
100

The program prints all numbers from 1 to n without using a loop and recursion. 

Explanation: 

2) Following is another approach using classes and static variables,  




// CPP Program to print 1 to 100 without loops and recursion
#include <iostream>
using namespace std;
 
class A {
public:
    static int a;
    A() { cout << a++ << endl; }
};
 
int A::a = 1;
 
// Driver Code
int main()
{
    int N = 100;
    A obj[N];
    return 0;
}

Output

1
2
3
..
..
98
99
100

The output of this program is the same as the above program. 

Explanation: 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. Therefore, we get all values from 1 to 100 printed on the screen.

3) Using goto keyword: The goto statement is a jump statement and can be used to jump from anywhere to anywhere within a function.

Example:




// CPP Program to print 1 to 100
// without loops and recursion
#include <iostream>
 
// Driver Code
int main()
{
    short sum = 0;
 
update:
    sum++;
    std::cout << sum << std::endl;
 
    if (sum == 100)
        return 0;
    goto update;
}

Output

1
2
3
..
..
98
99
100

The output of this program is the same as the above program. 

Explanation: In the above program, goto keyword is jump again to the label named update. The value of  ‘sum’ is printed and incremented with every call. The program stops executing once the variable sum is equal to 100. In this way, we get all values from 1 to 100 printed on the console. 

Time complexity : O(1) 
Auxiliary Space : O(1)


Article Tags :