for and foreach loop in C++

Suneet Agrawal
2 min readNov 16, 2024

--

When it comes to repetitive tasks in programming, loops are a powerful and versatile tool that can simplify your code and make it more efficient. In C++, two commonly used loops are the for loop and the for each loop. In this comprehensive guide, we’ll explore both types of loops in C++ and provide you with various examples to help you master their usage.

This post was originally posted at https://agrawalsuneet.github.io/blogs/for-and-foreach-loop-in-c++/ and later reposted on Medium.

Anatomy of a for Loop

Before we dive into examples, let’s review the basic structure of a for loop in C++:

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

Here’s what each part does:

  • Initialization: This part is executed only once at the beginning of the loop. It typically initializes a loop control variable (e.g., int i = 0).
  • Condition: The loop continues as long as the condition is true. When the condition becomes false, the loop terminates. If the condition is false from the start, the loop may not execute at all.
  • Increment/Decrement: This part is executed at the end of each iteration and is usually used to modify the loop control variable (e.g., i++ or i–).
  • Code to be executed: The block of code enclosed in curly braces {} is the body of the loop. It’s executed repeatedly until the condition becomes false.

Printing Numbers with a for Loop

#include <iostream>

int main() {
for (int i = 1; i <= 5; i++) {
std::cout << i << " ";
}

return 0;
}

Output:

1 2 3 4 5

In this example, we use a for loop to print numbers from 1 to 5. The loop control 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.

Sum of Numbers with a for Loop

we calculate the sum of numbers from 1 to 5 using a for loop. The sum variable accumulates the values of i in each iteration.

Please continue reading at https://agrawalsuneet.github.io/blogs/for-and-foreach-loop-in-c++/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

No responses yet