Demonstration of For loop

, by Prashant Gunjal


if you have to print hii 10 times on screen then we can write a program as follow

#include<stdio.h>
void main()
{
printf("\n\thii");
printf("\n\thii");
printf("\n\thii");
printf("\n\thii");
printf("\n\thii");
printf("\n\thii");
printf("\n\thii");
printf("\n\thii");
printf("\n\thii");
printf("\n\thii");
getch();
}

above program actually display hii 10 times on screen but this not smart way to write program instead of writing 10
times printf we can use for loop any only one printf as follow

#include<stdio.h>
void main()
{
int i;
for(i=0;i<10;i++)
{
printf("\n\thii");
}
getch();
}

Output :



now you can see that code is reduced.

How to use for loop :

Syntax :
for(init;condition;nextstep)
{
statement 1;
statement 2;
statement 3;
.
.
.
statement n;
}

here we need one variable as I used 'i' in above program
1) init :
we can initialize value of variable
ex : i=0;

2) condition :
here we can write condition to check when to stop for loop
ex : i<10;   here when i becomes greater than 10 or equal to 10 then loop execution stops.
3 ) nextstep :
use to tell what should be next step after each iteration
ex : i++;    here each time value of i will increase by one

4) body :
in body we can write multiple c statements.

Don't worry you will understand it clearly after watching next programs

0 comments: