-
-
Notifications
You must be signed in to change notification settings - Fork 1
For Loop
The for loop in C++ is a control flow statement that allows us to repeat a block of code a set number of times. It is used to iterate over a range of values.
The for loop has the following syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Let's take a look at each of these components in more detail:
-
Initialization: This is the initial value of the loop variable. It is usually a variable declared before the loop starts.
-
Condition: This is the condition that must be met in order for the loop to continue executing. The loop will terminate when this condition is false.
-
Increment/Decrement: This is the amount by which the loop variable is incremented or decremented each time the loop executes.
Let's take a look at a simple example. In this example, we will use a for loop to print the numbers from 0 to 10:
#include <iostream>
int main() {
for (int i = 0; i <= 10; i++) {
std::cout << i << " ";
}
return 0;
}
In this example, the loop variable i
is initialized to 0 and then incremented by 1 each time the loop executes. The loop will terminate when i
is greater than 10. The output of this program will be:
0 1 2 3 4 5 6 7 8 9 10
The for loop is a powerful and versatile control flow statement in C++. It can be used to iterate over a range of values and perform a set of operations for each iteration.