Printing 1 to 100 number in C using 4 different methods:
Method 1: Using a for loop
#include <stdio.h> int main() { for (int i = 1; i <= 100; i++) { printf("%d ", i); } return 0; }
Method 2: Using a while loop
#include <stdio.h> int main() { int i = 1; while (i <= 100) { printf("%d ", i); i++; } return 0; }
Method 3: Using a do-while loop
#include <stdio.h> int main() { int i = 1; do { printf("%d ", i); i++; } while (i <= 100); return 0; }
Method 4: Using recursion
#include <stdio.h> void printNumbers(int n) { if (n <= 100) { printf("%d ", n); printNumbers(n + 1); } } int main() { printNumbers(1); return 0; }
The first 3 methods are pretty basic. However, method 4 uses recursion to print the numbers from 1 to 100. Recursion is a technique in which a function calls itself to solve a smaller instance of the same problem.
In this method, we have a function called printNumbers
that takes an integer parameter n
. It checks if n
is less than or equal to 100. If it is, it prints the value of n
and then calls itself with n+1
as the argument.
The recursion continues until n
exceeds 100, at which point the function calls stop and the program terminates.
Here’s a step-by-step explanation of how the recursion works:
- The
printNumbers
function is called with an initial value ofn
as 1. - The function checks if
n
is less than or equal to 100. Since 1 is less than 100, it proceeds to the next step. - It prints the value of
n
(which is 1) usingprintf
. - The
printNumbers
function calls itself withn+1
as the argument. This creates a new instance of the function withn
set to 2. - The new instance of the function repeats the process from step 2 with
n
as 2. It prints 2 and calls itself withn
as 3. - This recursion continues until
n
reaches 100. Each function instance prints its value and calls the next instance with an incremented value ofn
. - Once the value of
n
becomes greater than 100, the recursion stops, and the program terminates.
Note These methods will all produce the same output, printing the numbers from 1 to 100 separated by spaces. Choose the one that suits your needs best.