Course Introduction to Programming
Command: for
In this lesson, we will learn about the for repetition structure. We will go through the following topics:
- Exemple of a task;
- For structure;
- Coding.
Task
Make a program that reads an integer number N and prints the message "Neps" N times.
To solve this task we have two options: we can use the while structure, learned in the previous class, or we can use the for structure.
For structure
The for structure is similar to the while. Since both are repetition structures they repeat a piece of code while a certain condition is true. However, we can include a command before the first check is executed and a command that will be executed at the end of each repetition when using the command for.
Syntax
for(initialization; condition; increment){
//Code
}
Below is an image to better explain the functioning of the for.

Figure 1
When the code reaches the for, the initialization is executed, then while the condition is true, the code is executed and then the increment happens. When the condition is false the for ends.
Coding
If we solve the task using the while structure, the final code would be as follows.
#include<stdio.h>
int main(){
int n;
int i;
scanf("%d", &n);
i = 1; // initialization
while(i<=n){ //condition
printf("Neps\n");
i = i+1; // increment
}
}
If
Then, as a result of the program, "Neps" will be printed only once. If
In the while structure, we can only write the condition to check when the structure will stop. However, in the for structure, we can use two other parameters, the initialization parameter, which is executed at the beginning of the structure, and the increment parameter, which is executed at the end of each repetition.
Thus, when coding a for, we can initialize the variable we use to count the repetitions within the structure, do the verification, and increment the variable in a very compact way.
A possible solution with the For structure is as follows:
#include<stdio.h>
int main(){
int n;
int i;
scanf("%d", &n);
for(i = 1; i<=n; i = i+1){
printf("Neps\n");
}
}
When the code reaches the for structure, the initialization is executed and the value of the variable
The result of the algorithm is the same as the previous one, but it is way more concise.
It is common to use shorter ways of incrementing the variables, such as i++ or i--, which, respectively, increases the variable by 1, or decreases the variable by 1.
Now you know how to code and use the for structure to solve problems that require repetition structures.