Flow Chart of For loop in C
This is a flowchart that represents the process of executing the for loop in the C programming language.
Generally, as we know there are three main components of for loop:
1. The initialization statement,
2. The termination condition, and
3. The update statement: This statement this helps in altering the value for further execution.
Here, you can see that the first step is to declare the variable and initialize its value with the help of assignment operator.
In the next step, we will have to use a test expression that will certainly help in dismissing the for loop or from preventing it to run toward infinity as per the requirement. If the termination condition or test expression is true then the control will go to the main body of the loop.
The last component of for loop is the increment or decrement statement that will be executed after the execution of the body.
This execution will terminate here. And, the loop will go to execute for next time and check whether the value returned by the termination condition is true or false. Loop will continue to execute until the condition becomes false. As the value is found to be false then the control will come out of the loop and the loop will completely dismissed.
Example of For Loop:
Here is program in c that will print numbers from 11 to 20 with the help of for loop:
#include <stdio.h>
int main()
{
int a; /* declaring a variable ‘a’ */
for (a = 11; a <= 20; ++a)
/* initializing its value as 11; a must be less than 20; modifying statement */
{
printf ("%d ", a);
/* printing final value of variable ‘a’
}
return 0;
}
Explanation:
Initially we declared a variable ‘a’. Then, we have for loop syntax that contains 3 main components which are as follows:
- a=11 (Initialization statement)
- a<=20 (termination condition)
- ++a (increment or decrement statement)
In this, the value of ‘a’ will begin with 11, and the termination condition will check that the value of ‘a’ is smaller than 20 or not. After this, there is modifying statement that helps in altering the value of ‘a’ so that further evaluations can be done. This can be pre-increment, post-increment, pre-decrement, or post-decrement. When the value of ‘a’ goes higher than 20 then the termination condition will terminate the for loop.
Two More Examples of For Loop
Example 1:
#include <stdio.h>
int main()
{
int a;
/* declaring a variable ‘a’ */
for (a = 199; a >= 148; --a)
/* initializing its value as 199; a must be more than 148; modifying statement */
{
printf ("%d ", a);
/* printing final value of variable ‘a’ */
}
return 0;
}
Example 2:
#include <stdio.h>
int main()
{
int a, b, c = 0;
/* declaring a variable ‘a’ ‘b’ ‘c’ */
printf("Enter a positive integer: ");
scanf("%d", &a);
for(b = 1; b <= a; ++b)
/* initializing its value as 1; a must be less than a; modifying statement */
{
c += b;
}
printf("c = %d", c);
/* printing final value of variable ‘c’ */
return 0;
}