Using for loops in C
The need for loops
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.
Syntax of a for loop
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
controlVariableis the variable defined that will be used to initialize the loop counter i.e. the number of times the loop will run. -
The
conditionis 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
changingControlis the statement that will either increment, decrement or change thecontrolVariablefor the next loop run. -
The curly braces,
{}, contain the code block that is to be executed.
How does a for loop work?
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!
Applying theory to example
#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:
- Here the
controlVariableis theint a = 0declaration which defines the initializer value for the for loop. - The
conditionin this case is thea < 10statement; ifais less than 5 the loop will continue to run, otherwise it will terminate. changingControlis the expressiona++indicating that before the next run of the loop, increase the value of a by 1.- The body of the loop to be executed each time is the block of code that adds
atosumand then prints the value ofsum. - This entire process of checking the
conditionand subsequent actions is repeated once the code body executes.
Free Resources