C Program to Print 1 to 100 Numbers Using For Loop : |
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=100;i++)
{
printf("%d\n",i);
}
}
C Program to Print 1 to 100 Numbers Using While Loop : |
#include<stdio.h>
int main() {
int i=1;
//i is less than or equal to 100
while( i <= 100) {
//print the value of i
printf("%d\n", i);
//Increment the value of i
i++;
}
return 0;
}
Explanation of Printing 1 to 100 Numbers in C:
1) Initialises i as an integer.
2) Now i=1 and is lesser than 100 so condition satisfies and prints the value of i which is 1.
3) Now i is incremented to '2' and again it is less than 100 so condition satisfies and prints the value of i which is '2'.
4) It goes like that until i is equal to 100 and it is equal to 100 so it prints 100 than the value of i is incremented to 101 which dissatisfies the condition causing to come out of the loop.
5) As there are no statements out of the loop the program terminates.
How to 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.
C Program to Print 1 to 100 Numbers Without Using Loop : |
#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\n",num);
//recursive call
printNum(num+1);
}
}
Output:
Next Post:
Previous Post:
0 Response to Print 1 to 100 Numbers in C Programming | C Programming Examples - 6
Post a Comment