Write a program to print 1 to 100 numbers without using loop. Using loop, (for and while loop) we can easily solve this problem. Think for a moment how do you solve this problem without using a loop. We can solve this problem using recursion.
We’ll cover following programming code examples in this tutorial.
- C program to print 1 to 100 numbers without using loop.
- C++ program to print 1 to 100 numbers without using loop.
Recursion vs iteration – Difference between recursion and iteration
C Program to Print 1 to 100 Numbers without using Loop
Let’s write a C code to print 1 to 100 numbers using recursion without using loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <stdio.h> int main() { //number start from 1 int n = 1; //Method call printNum(n); return 0; } int printNum(int num) { //If number is less than or equal to 100 if(num <= 100) { printf("%d ",num); //recursive call printNum(num+1); } } |
C++ Program to Print 1 to 100 Numbers without using Loop
We have written a c code to print numbers from 1 to 100 numbers. In this example, we are going to write a c++ code to print numbers from 1 to 100 using recursion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> using namespace std; int printNum(int num) { if(num <= 100) { //print number cout << num << " "; //recursive call printNum(num+1); } } int main() { //number start from 1 int n = 1; //Method call printNum(n); return 0; } |