Friday, December 12, 2008

for loop

LOOPS:
These loops are used to execute a statement number of times until the given condition is satisfied.
There are three types of loops.
1. For loop.
2. While loop.
3. Do..while loop.
1.For loop-
This loop is used very frequently in accepting the values in the array. By using the loop we can execute a statement number of times as per the requirement. The limitation and incrementing or decrementing can also be given in the syntax of the loop. The initialization of variable can be given.
e.g for(x=0;x<10;x++) or for(x=0;x>10;x--)
void main()
{
Int x[5],y;
Printf(“Enter five numbers”);
For(y=0;y<5;y++)
{
Scanf(“%d”,&x[y]);
}
Getch();
}
Here in this program five integers can be stored in the array. To accept the numbers ‘for’ loop is used. First y is initialized to zero. So first value accepted will be stored in x[0], then y will be incremented and the limit is checked weather y is less than 5 or not. Then next value is accepted in x[1]. This is continued upto x[4]. Then when the value of y exceeds the limit the loop exits ending the program. In the starting itself the condition is checked. The declaration of variable used in the loop should be in the beginning of the program. The loop can be used in any manner.
Other forms of for loop-
For(;x<5;)- Only condition is given. Declaration can be in the beginning and incrementing in the loop itself.
For(x=0;x++)- Condition in the loop.
For(;x<5;x++)- definition at the beginning.
For(;;)-definition at beginning, condition and increment or decrement in the body of loop.
Note that the semicolons in the loop are necessary. No semicolon should be given after the ‘for’ loop otherwise the loop will terminate with only once executing the statement inside it.

No comments:

Watch tv!