While solving certain programming problems, some blocks of code need to be executed repeatedly. The repetition of the same code until a particular condition is met justifies the need of for loops as a whole.
The for loop is a special kind of loop that only repeats the block of code it contains for a specific number of times. The number of repetitions is defined by a conditional statement within the loop. Let’s look at the syntax for declaring a loop to better understand how this works.
for(controlVariable; condition; changingControl){//body of for loop}
Now let’s look at each section of the for loop:
The controlVariable
is the variable defined that will be used to initialize the loop counter i.e. the number of times the loop will run.
The condition
is the statement on the basis of which the loop will be evaluated. Given that the statement returns false, the loop will no longer run.
The changingControl
is the statement that will either increment, decrement or change the controlVariable
for the next loop run.
The curly braces, {}
, contain the code block that is to be executed.
The illustration below shows the life cycle of the for loop and how it evaluates statements to run itself
Now that we know why we need a for loop and how it works, lets look at an example to re-inforce what we have learnt!
#include <stdio.h>int main() {// your code goes hereint sum =0;for(int a=0;a<10;a++){sum= sum+a;printf("%d\n",sum);}}
In the code above, let’s see which part is what:
controlVariable
is the int a = 0
declaration which defines the initializer value for the for loop.condition
in this case is the a < 10
statement; if a
is less than 5 the loop will continue to run, otherwise it will terminate.changingControl
is the expression a++
indicating that before the next run of the loop, increase the value of a by 1.a
to sum
and then prints the value of sum
.condition
and subsequent actions is repeated once the code body executes.