for Statement
for is an entry control loop statement which executes the statements to a
specified number of times. The for loop provides a more
concise loop control structure. The general form of the for loop is:
Syntax:
for (initialization; test condition; increment)
{
body of the loop;
}
{
body of the loop;
}
statement-x;
Steps: -
1. Initialization of the loop control variable
is done first.
2. The value of the loop-control
variable is tested. If the condition is true, thebody of the loop
will be executed otherwise the loop will be terminated.
3. When the body of the loop
is executed, loop-control variable is incremented or updated wth
new value using assignment operator.
4. New value of the control variable is again tested to see whether it
satisfies the test condition.
5. If the condition is satisfied (TRUE) means the body of the loop is
again executed and this
process continues until the condition becomes FALSE.
Sample Program for printing numbers from 1 to 100
void main()
{
int i;
for(i=1;i<=100;i++)
printf(“\t%d”,i);
}
Note:- Here i is known as loop-control variable.
void main()
{
int i;
for(i=1;i<=100;i++)
printf(“\t%d”,i);
}
Note:- Here i is known as loop-control variable.
Features:-
1. More than one variable can be
initialized at a time using comma operator.
for(n=1,m=50;n<=m;n++,m--)
{
printf(“%d”,m/n);
}
2. The
Test condition can have compound relations and the testing need not be limited
to loop-
control variable.
sum=0;
for(i=1;i<10&&sum<100;i++)
{
sum=sum+i;
printf(“%d”,sum);
}
3. We can
use assignment statements in initialization and increment sections.
p=10;
q=6;
for(x=(p+q)/2;x>=0;x=x/2)
{
printf(“%d”,x);
}
4. One or
more sections can be omitted, but the semi-colons separating the sections
must
remain.
i=1;
for(;i<=100;i++)
{
printf(“%d”,i);
i++;
}
** we can omit test condition if required,
But this produces infinite loop.
5.
Nesting of loops are allowed.
for(i=2;i<=10;i++)
{
for(j=1;j<=10;j++)
{
printf(“\t
%d*%d=%d”,i,j,i*j);
}
printf(”\n”);
}
* This program prints the Multiplication
table.
No comments:
Post a Comment