1) WHILE LOOP: -
The while loops checks whether test expression is true or not. If it is true, code(s) inside the body of while loop is executed, i.e. code(s) inside the braces { } are executed. Then again the test expression is checked whether test expression is true or not. This process continues until the while condition becomes false.
Syntax of while loop:
initialization;
while(condition)
{
.......
incrementation;
}
program:
#include <stdio.h>
int main ()
{
int i =0;
while(i < 5)
{
printf("i = %d\n",i);
i++;
}
return 0;
}
output:
i=0
i=1
i=2
i=3
i=4
Sr. No.-----Description----Short Counter
1--------------x=x+1-------------x++
2---------------x=x-1--------------x--
3----------------x=x+2------------x+=2
4----------------x=x-2-------------x-=2
5-----------------x=x*2------------x*=2
6----------------x=x/2-------------x/=2
7----------------x=x%2-------------x%=2
2) DO-WHILE LOOP: -
DO-WHILE LOOP: -
do...while loop is similar to while loop. Only difference between these two loops is that, in while loops, test expression is checked at first but, in do..while loop code is executed at first then the condition is checked. So, the code are executed at least once in do..while loop.
Syntax of Do-while loop:
initialization;
do{
.....
incrementation;
}while(condition);
3) FOR LOOP: -
The initialization statement is executed only once at the beginning of the for loop. Then the test expression is checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then the code(s) inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.
syntax:
for(initialization;condition;increment)
{
.......... body..........
}
program:
#include <stdio.h>
int main ()
{
for(int i = 0 ; i < 5 ;i++ )
{
printf("i = %d\n",i);
}
return 0;
}
output:
i=0
i=1
i=2
i=3
i=4
0 comments:
Post a Comment