How to Use For loop in C++ ?


In C++, a for loop is a control flow statement that allows you to execute a block of code repeatedly based on a specified condition. The syntax of a for loop in C++ is as follows:

for (initialization; condition; increment/decrement) {
   // code to be executed
}

Here's what each part of the for loop does:

  • initialization: This is where you initialize the loop counter variable. It is executed only once before the loop starts.
  • condition: This is the condition that is checked before each iteration of the loop. If the condition is true, the loop continues; if it is false, the loop terminates.
  • increment/decrement: This is where you update the loop counter variable. It is executed after each iteration of the loop.
  • code to be executed: This is the block of code that is executed repeatedly as long as the condition is true.

Here's an example of a for loop that prints the numbers from 1 to 10:

for (int i = 1; i <= 10; i++) {
   cout << i << " ";
}

In this example, the loop counter variable i is initialized to 1, and the loop continues as long as i is less than or equal to 10. After each iteration of the loop, i is incremented by 1. The code inside the loop simply prints the value of i followed by a space.

Another example of a for loop is one that calculates the sum of the first 10 natural numbers:

int sum = 0;
for (int i = 1; i <= 10; i++) {
   sum += i;
}
cout << "The sum of the first 10 natural numbers is " << sum << endl;

In this example, the loop counter variable i is initialized to 1, and the loop continues as long as i is less than or equal to 10. After each iteration of the loop, i is incremented by 1. The code inside the loop adds the value of i to the variable sum. After the loop is finished, the value of sum is printed to the console.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.