For Loops
Lesson 22Author : Afrixi
Last Updated : November, 2022
For loops in C++ are used to execute a block of code repeatedly for a specific number of times. Here’s an example of a program that uses a for loop to print the numbers from 1 to 10:
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
std::cout << i << std::endl;
}
return 0;
}
In this example, the program initializes a variable i
to 1, and then enters a for loop with three expressions inside the parentheses: int i
= 1 is the initialization expression, i <= 10
is the condition expression, and i++
is the increment expression. The loop executes the code block inside the braces repeatedly for as long as the condition is true, which means it will execute 10 times in this case. The code block simply prints the value of i
to the console using std::cout
.
When i
reaches 11, the condition i <= 10
becomes false and the program exits the loop. Finally, the program returns 0 to indicate successful execution.