Lesson 2

Navigating C++ Loops: Understanding Iteration over Containers

Topic Overview and Actualization

Greetings, Explorer! Today, we will delve into the essential tools of C++ loops. Loops in programming simplify and enhance the efficiency of repetitive tasks — much like a marathon of your favorite TV series. In this lesson, we will explore the universe of looping in C++ and gain hands-on experience by applying loops to Standard Template Library (STL) containers such as vectors and strings.

Understanding Looping

Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a for loop to print greetings for a group of friends.

C
1#include <iostream> 2#include <vector> 3 4int main() { 5 std::vector<std::string> friends = {"Alice", "Bob", "Charlie", "Daniel"}; 6 for (const std::string& friend_name : friends) { 7 // For each friend_name, prints the greeting 8 std::cout << "Hello, " << friend_name << "! Nice to meet you.\n"; 9 } 10 return 0; 11}

Loops enable us to execute repetitive sequences automatically and efficiently.

For Loop in C++

The for loop is a control flow statement that allows code to be executed repeatedly. Here is how it generally works:

  1. Initialization: This is where you set up the loop variable. It's executed once when the loop begins.

  2. Condition: This Boolean expression determines if the loop will continue or stop. If it's true, the loop continues; if it's false, the loop ends and the flow jumps to the next statement after the loop.

  3. Iteration: This is where you update the loop variable. This statement executes after the loop body and right before the next condition check.

  4. Loop Body: The block of code to be executed in each loop.

The structure of a for loop is typically "for (initialization; condition; iteration) {loop body}", where the loop body gets executed for as long as the condition evaluates to true. After each loop, the iteration is executed which generally updates the value of the loop control variable.

Let's print a range of numbers using a for loop:

C
1#include <iostream> 2 3int main() { 4 for (int num = 0; num < 5; num++) { 5 // This line prints numbers from 0 to 4 6 std::cout << num << "\n"; 7 } 8 return 0; 9}

In each cycle of the loop, the variable (num) is updated before executing the code inside the block.

Range-based For Loop

The for loop is versatile and can work with any sequence-like structure in C++, such as strings, vectors, and more. The Range-based For Loop is another style of for loop in C++ which performs a loop over a range of values such as sequences or arrays, or more specifically data structures referred to as containers.

This type of loop is more simplified and safer compared to traditional loops as it eliminates the need to manually control the loop variable.

C
1#include <iostream> 2#include <vector> 3 4int main() { 5 // Vector of fruits 6 std::vector<std::string> fruits = {"apple", "banana", "cherry"}; 7 // `fruit` stands for each fruit in the `fruits` vector 8 for (const std::string& fruit : fruits) { 9 std::cout << fruit << "\n"; // prints each fruit 10 } 11 return 0; 12}

In the above example, the fruit variable stands for each element in the fruits vector. The : after fruit indicates that this is a range-based for loop. The loop body executes once for each item in the fruits vector, with fruit being a reference to the current element in each iteration.

Similarly, we may loop through strings (which are considered containers of characters), as below:

C
1#include <iostream> 2#include <string> 3 4int main() { 5 std::string word = "hello"; 6 // 'ch' is each individual character in `word` 7 for (const char& ch : word) { 8 std::cout << ch << "\n"; // prints each character from 'hello' 9 } 10 return 0; 11}

In the above example, ch stands for each character in the word string. The loop repeats for each character in the string word. For each repetition, it will print the specific character, hence printing 'hello' one character at a time.

While Loop in C++

While loops in C++ continuously execute their content until a particular condition becomes false. Here's a simple example:

C
1#include <iostream> 2 3int main() { 4 int num = 0; 5 // The loop keeps running until num is no longer less than 5 6 while (num < 5) { 7 std::cout << num << "\n"; 8 // Increase num by 1 at the end of each iteration 9 num++; 10 } 11 return 0; 12}

As you can see, before each iteration, C++ checks the condition (num < 5). If it's true, the loop continues; otherwise, the loop breaks.

Applications of Looping

Loops are integral to programming. They are extensively used in various sections of a program such as summing elements in a vector and parsing through text.

C
1#include <iostream> 2#include <vector> 3 4int main() { 5 // Vector of numbers 6 std::vector<int> numbers = {1, 2, 3, 4, 5}; 7 int total = 0; 8 // `num` is each number in `numbers` 9 for (const int& num : numbers) { 10 total += num; // Add each number in the vector 11 } 12 std::cout << total << "\n"; // prints the total sum 13 return 0; 14}
C
1#include <iostream> 2#include <string> 3 4int main() { 5 std::string text = "hello"; 6 int vowel_count = 0; 7 // `ch` is each character in `text` 8 for (const char& ch : text) { 9 // If a vowel letter is found, increment the count 10 if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { 11 vowel_count++; 12 } 13 } 14 std::cout << vowel_count << "\n"; // prints the count of vowels 15 return 0; 16}
Lesson Summary and Practice

Congratulations on mastering C++ loops! We've brushed up on for and while loops, and have seen how to loop over STL containers like vectors and strings. Now, it's time for some beneficial practice exercises to solidify your learning. The more problems you solve, the better you'll become. Let's proceed further on our journey into the depths of programming!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.