The usage of for() in C++

In C++, the for loop is an iterative looping structure used to repeatedly execute a specific block of code a certain number of times. Its basic syntax is as follows:

for (初始化表达式; 循环条件; 更新表达式) {
    // 循环体
}

The initialization expression is executed once before the loop starts to initialize the counter or declare and initialize the loop variable. The loop condition is a boolean expression used to determine whether to continue executing the loop. If the condition is true, the loop body is executed; if the condition is false, the loop is exited. The update expression is executed after each loop iteration to update the counter or loop variable’s value.

Here are some examples of using for loops:

  1. Print numbers from 1 to 10.
for (int i = 1; i <= 10; i++) {
    cout << i << " ";
}
  1. Calculate the sum of the array elements.
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
    sum += arr[i];
}
  1. Traverse the string and print each character:
string str = "Hello";
for (int i = 0; i < str.length(); i++) {
    cout << str[i] << " ";
}

It is important to note that the loop condition is evaluated before each iteration, so if the condition is false from the beginning, the loop body will not be executed. Additionally, if a break statement is used within the loop body, it will immediately exit the loop.

bannerAds