for loop


The for loop is an Entry-controlled loop that provides a more concise & efficient loop control structure, that’s why for loop is generally used.


Syntax of for loop

for(initialization; test-condition; increment/decrement)
{
body of the loop
}


The execution steps of for loop statement is as follow:-

  1. First of all the control variable is initialized using assignment statements such as i=0, i=1 and count=0. The variable i and count are known as control variable of the loop.

  2. The value of the control variable is checked using the test-condition. For example test condition i < 10 determines when the loop will exit. If the test-condition is true than the body of the loop is executed otherwise the loop is terminated if test-condition is false.

  3. When first time the body of the loop is executed, the control is again transferred back to the for statement to increment the value of the control variable in the for statement using assignment statement such as i++ or i=i+1 or ++i , then the new value of control variable is checked again using test-condition (i < 10) .

  4. If the test-condition is satisfied for incremented or new value of control variable then the body of the loop is executed again otherwise the loop is terminated.

Example 1:

Output:

0
1
2
3
4
5
6
7
8
9

This for loop is executed 10 times and prints the each digit form 0 to 9 in new line in ascending order.


Example 2:

Output:

9
8
7
6
5
4
3
2
1
0

This for loop is executed 10 times and prints the each digit form 9 to 0 in new line in descending order .


Example 2: Write a program to find sum of square of integers .


Output:

Enter the value of n 10
The sum of the squares is 385



Explanation:-


n=10;
sum= 1*1 + 2*2 +3*3 +_ _ _ _ _+ 10*10;
sum=385;

Here sum =sum +i*i is executed 10 times for i=1 to i<=n, where n=10. Each time the value of the i is incrementing until i=10 and adding in the variable sum.
At end of the loop sum= 1*1 + 2*2 +3*3 +_ _ _ _ _+ 10*10; the value of sum is 385.


`
Key points
  • There is no any semicolon (;) at the end of the incremented section (i++) as well as at end of the for loop statement.
  • If by mistake we use semicolon (;) at the end of the for statement, the loop is terminated & the body of the loop will not be executed.
  • If the body of the loop contains only one statement than the use of braces { } is optional .


Do You Know?