📅  最后修改于: 2023-12-03 15:13:54.217000             🧑  作者: Mango
In C++, a for loop is a programming construct used to repeat a block of code a certain number of times. It provides a convenient way to iterate over a range of values or elements in an array. The for loop consists of an initialization statement, a condition, an iteration statement, and a body.
The syntax of a for loop in C++ is as follows:
for (initialization; condition; iteration)
{
// Code to be executed repeatedly
}
initialization
: It is an optional statement used to initialize the loop variable.condition
: It is an expression evaluated before each iteration. If the condition is true, the loop continues; otherwise, it terminates.iteration
: It is an expression executed at the end of each iteration to update the loop variable.body
: It is a block of code that is executed repeatedly as long as the condition is true.Here is an example of a for loop that iterates from 1 to 5 and prints the values:
#include <iostream>
int main()
{
for (int i = 1; i <= 5; i++)
{
std::cout << i << std::endl;
}
return 0;
}
Output:
1
2
3
4
5
In this example, the loop variable i
is initialized to 1, and the loop continues as long as i
is less than or equal to 5. After each iteration, i
is incremented by 1. The body of the loop simply prints the value of i
on a new line.
For more information and advanced usage of for loop in C++, refer to the official documentation or online resources.