For Loop
If you want to execute the code a certain number of times use the for
loop.
Syntax:
for (statement#1; statement#2; statement#3) {
// The code block
}
It looks a bit difficult but letβs understand what is actually going on:
- The statement#1 is an initial statement. It is executed at the beginning of for loop and doesnβt repeat later.
- The statement#2 is the condition. The code block in the loop is executed if the condition is true (for example
x < 4
). - The statement#3 is executed every time after the code block execution (in most cases itβs this statement increment/decremant the control variable of the loop).
The loop body stops execution if the condition (statement#2) is false.
Letβs look at the example:
123for (int x = 1; x < 5; x++) { cout << x << endl; }
This code prints numbers from 1 to 4. Firstly the code sets in the variable x
the value 1
before the loop starts. Then we mention that the program should execute the block while the x is less than 5 (x<5
) and increment it by 1
every time after the code block execution.
You can also change statements in any convenient way. For example, we want to print all even numbers descending from 10 to 0:
for (int x = 10; x >= 0; x-=2) {
cout << x << endl;
}
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Ask me questions about this topic
Summarize this chapter
Show real-world examples
Awesome!
Completion rate improved to 3.7
For Loop
Swipe to show menu
If you want to execute the code a certain number of times use the for
loop.
Syntax:
for (statement#1; statement#2; statement#3) {
// The code block
}
It looks a bit difficult but letβs understand what is actually going on:
- The statement#1 is an initial statement. It is executed at the beginning of for loop and doesnβt repeat later.
- The statement#2 is the condition. The code block in the loop is executed if the condition is true (for example
x < 4
). - The statement#3 is executed every time after the code block execution (in most cases itβs this statement increment/decremant the control variable of the loop).
The loop body stops execution if the condition (statement#2) is false.
Letβs look at the example:
123for (int x = 1; x < 5; x++) { cout << x << endl; }
This code prints numbers from 1 to 4. Firstly the code sets in the variable x
the value 1
before the loop starts. Then we mention that the program should execute the block while the x is less than 5 (x<5
) and increment it by 1
every time after the code block execution.
You can also change statements in any convenient way. For example, we want to print all even numbers descending from 10 to 0:
for (int x = 10; x >= 0; x-=2) {
cout << x << endl;
}
Thanks for your feedback!