📜  c++ forloop - C++ (1)

📅  最后修改于: 2023-12-03 15:13:54.217000             🧑  作者: Mango

C++ For Loop - C++

Introduction

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.

Syntax

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.
Example

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.

Key Points
  • The for loop is often used when the number of iterations is known or can be determined.
  • The loop variable should be declared and initialized within the initialization statement.
  • The condition is evaluated before each iteration to determine if the loop should continue or terminate.
  • The iteration statement is executed at the end of each iteration to update the loop variable.
  • The body of the loop is executed repeatedly until the condition becomes false.

For more information and advanced usage of for loop in C++, refer to the official documentation or online resources.