C Programming Loops - display numbers using for loop, while loop and do while loop
|
1.While loop checks for the condition first. so it may not even enter into the loop, if the condition is false.
2.do while loop, execute the statements in the loop first before checks for the condition. At least one iteration takes places, even if the condition is false.
3.for loop is similar to while loop except that •initialization statement, usually the counter variable initialization •a statement that will be executed after each and every iteration in the loop, usually counter variable increment or decrement.
The following sample code that can display numbers explains all 3 different loops:
Source Code
#include <stdio.h>
int main()
{
int num = 0;
printf("Using while loop\n");
while(1)
{
num = num + 1;
printf("%d\n", num);
printf("%d\n", num);
if(num >= 5)
break;
}
printf("Using do while loop\n");
num = 0;
do
{
num = num + 1;
printf("%d\n", num);
} while(num < 5);
printf("%d\n", num);
} while(num < 5);
printf("Using for loop\n");
for(num = 1; num <= 5; num++)
{
printf("%d\n", num);
};
printf("%d\n", num);
};
return 0;
}
Output
Using while loop
1
2
3
4
5
Using do while loop
1
2
3
4
5
Using for loop
1
2
3
4
5
Press any key to continue . . .
#include
উত্তরমুছুনint main()
{
int i;
printf("Using FOR loop : \n");
for(i=1;i<=10;i++)
{
printf("%d\n",i);
}
printf("\nUsing WHILE loop : \n");
int j=1;
while(j<=10)
{
printf("%d\n",j);
j++;
}
printf("\nUsing DO WHILE loop : \n");
int k=1;
do
{
printf("%d\n",k);
k++;
}
while(k<=10);
}
///Simple if statement///
উত্তরমুছুন#include
main()
{
int n;
printf("Enter a number");
scanf("%d",&n);
if(n<1)
printf("%d is a positive number\n:",n)
}
///Simple if statement///
উত্তরমুছুন#include
main()
{
int n;
printf("Enter a number");
scanf("%d",&n);
if(n<1)
printf("%d is a positive number\n:",n)
}