In C programs if user want to execute block of code several times here loops are used.in other words loops are used to excecute block of code multiple times until specific condition met.
In C programs we have 3 types of loops
- For Loop
- while Loop
- Do-while Loop
Lets learn more by taking examples for Loops
For Loop
It execute the code until condition is false. it depends on 3 parameters
Syntax
[php]for (Initialization;condition;increment/decrement)
{
//code
}
[/php]
How For loops Works
First initialization executed once
now condition will executed until its false
if condition is true it will increment by 1
Example
[php]#include<stdio.h>
#include<conio.h>
void main() {
int i;
for( i = 20; i < 25; i++)
{
printf ("%d " , i);
}
getch();}[/php]
while Loop
While loop is executed until condition is false
Synax
[php]while(condition){
//code
}[/php]
Example
[php]#include<stdio.h>
#include<conio.h>
void main()
{
int i = 35;
do{
printf ("%d " , i );
i++;
}
while( i < =40 );
getch();
}
[/php]
Output
35
36
37
38
39
Do-while Loop
syntax
[php]do{
//code
}while(condition);
[/php]
Example
[php]
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 10;
do{
printf ("%d " , i );
i++;
}
while( i < =10 );
getch();
}
[/php]
output
10
11
No comments:
Post a Comment