For Loops in C++


A for loop is a special type of loop in C++ which allows us to loop over the items of a collection, such as a string or a vector.


Looping through a string:

For example, a string is a sequence of characters, so we can use a for loop to iterate over each character and do something with that character:

string name = "Andy";

for(char letter : name) {
  cout << letter << endl;
}

Let's break down this code:

  • The for keyword that indicates the start of a for loop.
  • char letter is the loop variable. It will take the value of each different item in the collection
  • The : separates the loop variable from the collection we will iterate on
  • name is the collection to loop over

The output of this code is:

A
n
d
y

As you can see, on each iteration, letter was assigned the value of the next item in the string and inside the loop, we printed that value.


Looping through a vector:

We can also use for loops with lists:

vector<string> fruits = {"banana", "orange", "pear", "kivi"};

for (string fruit : fruits) {
  cout << "I eat " + fruit << endl;
}

The output of this code is:

I eat banana
I eat orange
I eat pear
I eat kivi

Assignment
Now let's greet our friends using a for loop!


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore the concept of for loops in C++. For loops are a fundamental control structure in programming that allow us to repeat a block of code multiple times. They are particularly useful when we need to iterate over collections such as arrays, strings, or vectors. Understanding for loops is essential for writing efficient and concise code.

Understanding the Basics

Before diving into more complex examples, let's understand the basic syntax and structure of a for loop in C++. A for loop typically consists of three parts:

Here is a simple example of a for loop that prints numbers from 1 to 5:

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        cout << i << endl;
    }
    return 0;
}

In this example, i is the loop variable, i <= 5 is the condition, and i++ increments the loop variable by 1 after each iteration.

Main Concepts

Now that we understand the basics, let's explore some key concepts and techniques for using for loops effectively:

Let's see an example of a range-based for loop:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> fruits = {"banana", "orange", "pear", "kivi"};
    for (string fruit : fruits) {
        cout << "I eat " << fruit << endl;
    }
    return 0;
}

In this example, the loop variable fruit takes the value of each element in the fruits vector, and we print a message for each fruit.

Examples and Use Cases

Let's look at some more examples to understand the versatility of for loops:

Example 1: Looping through a string

#include <iostream>
using namespace std;

int main() {
    string name = "Andy";
    for (char letter : name) {
        cout << letter << endl;
    }
    return 0;
}

This example demonstrates how to iterate over each character in a string and print it.

Example 2: Summing elements in an array

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int sum = 0;
    for (int num : numbers) {
        sum += num;
    }
    cout << "Sum: " << sum << endl;
    return 0;
}

In this example, we use a for loop to sum the elements of an array.

Common Pitfalls and Best Practices

When using for loops, it's important to be aware of common pitfalls and follow best practices:

Advanced Techniques

For more advanced use cases, you can combine for loops with other control structures or use them in algorithms:

Example: Nested for loops

#include <iostream>
using namespace std;

int main() {
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

This example demonstrates how to use nested for loops to iterate over a 2D array (matrix).

Debugging and Testing

When debugging code with for loops, consider the following tips:

For testing, write test cases that cover different scenarios, including edge cases, to ensure your loop behaves as expected.

Thinking and Problem-Solving Tips

When approaching problems that involve for loops, consider these strategies:

Conclusion

In this lesson, we covered the basics of for loops in C++, explored key concepts, and looked at various examples and use cases. Mastering for loops is essential for writing efficient and maintainable code. Keep practicing and experimenting with different scenarios to deepen your understanding.

Additional Resources

For further reading and practice, consider the following resources: