Previous | Home | Next |
Iteration Statements OR Loops
These are used to run a particular block statements repeatedly or in other words form a loop. for, while and do-while statements come under this category.
# for Statement (Loop)
Loops generated by for statement is are also called entry controlled or close ended because the condition for iteration of loop is check at the starting of the loop and loop will not execute even once if the condition will not satisfy even once.
Syntax
for (initialization; condition, increment) statement; //OR for(initialize counter;test counter;increment counter) { //do this; //and this; //and this; }
Initialization: In this we initialize the loop control value to a starting value.
Condition: In this evaluate the condition for the iteration of the loop and loop repeat only when this is true.
Increment: In this we determine how the value of loop control value changes with each iteration of the loop. It can be increment, decrement or any mathematical expression.
Example/* Calculation of simple interest for 3 sets of p, n and r */ main ( ) { int p, n, count ; float r, si ; for ( count = 1 ; count <= 3 ; count = count + 1 ) { printf ( "Enter values of p, n, and r " ) ; scanf ( "%d %d %f", &p, &n, &r ) ; si = p * n * r / 100 ; printf ( "Simple Interest = Rs.%f\n", si ) ; } }
The execution process for the above program is given as follows:
- When the for statement is executed for the first time, the value of count is set to an initial value 1.
- Now the condition count <= 3 is tested. Since count is 1 the condition is satisfied and the body of the loop is executed for the first time.
- Upon reaching the closing brace of for, control is sent back to the for statement, where the value of count gets incremented by 1.
- Again the test is performed to check whether the new value of count exceeds 3.
- If the value of count is still within the range 1 to 3, the statements within the braces of for are executed again.
- The body of the for loop continues to get executed till count doesn’t exceed the final value 3.
- When count reaches the value 4 the control exits from the loop and is transferred to the statement (if any) immediately after the body of for.
# Multiple initialization in for loop
Multiple statements can also be used in the incrementation expression of for loop; i.e., you can increment (or decrement) two or more variables at the same time. However, only one expression is allowed in the test expression. This expression may contain several conditions linked together using logical operators. Use of multiple statements in the initialisation expression also demonstrates why semicolons are used to separate the three expressions in the for loop. If commas had been used, they could not also have been used to separate multiple statements in the initialisation expression, without confusing the compiler.
// one statement separated by a comma for ( i = 1, j = 2 ; j <= 10 ; j++ )
Previous | Home | Next |