In this section, we will learn what the for loop statement is and how to use it in C.
What is for loop in C?
We use the `for` loop to run a block of instructions for a specific number of times. If you read about the while-loop, you should know that this type of loop runs a block of instructions until a condition is met and it doesn’t care how many times the loop is repeated!
For example, in the `while` loop we declare a condition like: “as long as an entered password does not match the actual password, repeat the process”. This might take 3 times, 10 times or even more.
But in `for` loop, we declare exactly how many times we want a process to be repeated! For example, we can say the instructions within the body of a `for` loop should execute 10 times only or 20 times only.
After that number of times, the loop will end and the instructions after the loop will run.
So the number of iteration is controllable in a `for` loop.
Note: the `for` loop has this capability to act just like a `while` loop as well. But the main purpose of working with a `for` loop is to create a loop that repeat itself for a specific number of times.
On the same page, the while loop has this capability to act just like `for` loop but this is not its main purpose.
C for Loop Syntax
Here’s the structure of the `for` loop:
for (initialization_statement ; condition_statement ; update_statement) { // the instructions within the body of 'for' loop }
`for`: In order to create a for loop, we start with the keyword, for.
`( )`: within the parentheses that comes after the `for` keyword, we define 3 statements:
- Declaring and initializing a variable (optional).
- Set a condition.
- Update the initial value created at the first step (optional).
Note: each of these steps are separated from the other via a semicolon `;`.
`initialization_statement`: We mentioned that a `for` loop can repeat the execution of a block of code a specific number of times right? Well in order to start and stop a loop, there should be a variable with a value to base the condition of the loop on it. Within the initialization_statement we can declare and initialize this variable and assign a number to it like `int i = 0` and then we use this variable in the `condition_statement` and `update_statement`.
Note: initialization_statement will only run once.
Also this variable is accessible within the body of the `for` loop, only.
`condition_statement`: condition_statement is the place where we declare the condition of the loop. The condition_statement will be checked every time the loop is repeated. The body of the `for` loop will only run if the result of the `condition_statement` is true.
`update_statement`: This is the place where we normally change the value assigned to a variable which can be the one created in the initialization_statement in order to closer the condition_statement to result false and end the loop at a certain point during the execution of the loop. So the expression we put here usually affects the condition we set in the `condition_statement`. For example, let’s say the condition of a for loop is to see if the value of a variable name `age` is less than 100 or not. Now, within the `update_statement` section, we can increase the value of this variable by one (if the current value is less than 100) every time the loop is iterated and so finally at some point in the future the value will be equal to 100 and that will cause the condition of the loop to not produce the value true and hence causing the loop to break.
Note: Assigning values to `initialization_statement`, `condition_statement` and `update_statement` is optional and we can have a `for` loop like this as well:
for (;;){//body…}
In such case, the `for` loop will run forever (because there’s no condition to meet!). But we can break such a loop via keywords like `break` and `return`.
We will run an example at the end of this section for the infinite loop.
Example: looping in C programming via for loop
#include <stdio.h> int main() { for (int var = 0;var < 5; var++){ printf("the value of the var is: %d\n",var); } return 0; }
Output:
the value of the var is: 0 the value of the var is: 1 the value of the var is: 2 the value of the var is: 3 the value of the var is: 4
How does for loop work?
Here’s the order of execution in the `for` loop:
- Everything starts with the `initialization_statement`: In this example, the `initialization_statement` is `int var = 0`. It’s a simple integer variable with the initial value set to 0.
Note: initialization_statement will only execute once.
- Execute `Condition_statement`: we have the `condition_statement` in this example which is `var<5` and at this point because the actual value assigned to this variable is less than 5, the result of the condition is true.
- Run the body of the loop: At this stage because the `condition_statement` resulted true, the body of the loop will run once.
In this example, the body is just to call the `printf` function and display a message on the screen.
- Execute `update_statement`: when the instructions within the body of the `for` loop reached to its end, the `update_statement` will be executed.
In this example, the `update_statement` is to increase the value of the `var` variable by one.
At this stage, the instructions of the 2, 3, and 4 will be repeated for as long as the `condition_statement` results false, which in that case the loop will break.
C Nested for Loop
The body of a for loop is free to be used for any purpose! This means we can put a for loop within the body of another for loop! This is known as nested for loop.
Using a nested for loop is especially important when we want to iterate through the elements of a multidimensional array, which you’ll learn about them in the C multidimensional array section.
Example: creating nested for loop in C
#include <stdio.h> int main() { for (int i=0 ; i<5; i++){ printf("\n%d",i); for (int b= 0; b<4; b++){ printf("%d",b); } } return 0; }
Output:
00123 10123 20123 30123 40123
Example: creating infinite for loop in C
#include <stdio.h> int main() { int var = 0; for (;;){ if (var> 100){ printf("the value of the var is: %d\n",var); break; } var++; } return 0; }
Output:
the value of the var is: 101
As you can see in the example above, only via `break` statement we could end the loop after looping for 100 times.
Note: Learn more about `break` in the break statement section.
You should always put the semicolon `;` between the 3 statements in the `for` loop even if you don’t set any value for these statements.
C for Loop vs While Loop
As mentioned before, the while-loop is designed to run a block of code for as long as the result of its condition is true. So its design purpose is to not be concerned about the number of times its body gets executed.
On the other hand, the for-loop is mainly designed so that we can specifically decide how many times a block of code should be executed. This was in the design purpose of the for-loop.
Note: again, we can use the for-loop and the while loop interchangeably, but remember the purpose of each one when working with them.