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
The execution steps of for loop statement is as follow:-
- 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.
- 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.
- 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) .
- 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.
This for loop is executed 10 times and prints the each digit form 0 to 9 in new line in ascending order.
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 .
sum= 1*1 + 2*2 +3*3 +_ _ _ _ _+ 10*10;
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.