Solution
To achieve the desired output, we need to add a for loop that iterates over the list of languages and prints each one. Here is the detailed solution:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
// Define a vector of strings containing the programming languages
vector<string> languages = {"Python", "Java", "JavaScript"};
// Print the initial statement
cout << "Today we'll learn about:" << endl;
// For loop to iterate over each language in the vector
for (string language : languages) {
// Print each language
cout << language << endl;
}
// Print the final statement
cout << "Let's code!" << endl;
return 0;
}
Explanation
Let's break down the solution step-by-step:
- Include necessary headers: We include the headers
<iostream>,<vector>, and<string>to use the standard input-output stream, vector, and string classes respectively. - Using the standard namespace: We use the
using namespace std;directive to avoid prefixing the standard library names withstd::. - Define the main function: The
mainfunction is the entry point of the program. - Initialize the vector: We initialize a vector of strings named
languageswith the values "Python", "Java", and "JavaScript". - Print the initial statement: We use
coutto print "Today we'll learn about:" followed by a newline. - For loop: We use a range-based for loop to iterate over each element in the
languagesvector. For each iteration, the current element is stored in the variablelanguage. - Print each language: Inside the loop, we print the current language followed by a newline.
- Print the final statement: After the loop, we print "Let's code!" followed by a newline.
- Return statement: The
mainfunction returns 0 to indicate successful execution.
Output
The output of the program will be:
Today we'll learn about:
Python
Java
JavaScript
Let's code!
Conclusion
In this lesson, we learned about the execution flow of a for loop in C++. We saw how to use brackets to define the scope of the loop and how to iterate over a vector of strings. Understanding the execution flow is crucial for writing correct and efficient programs. By practicing with different examples, you can master the use of for loops and improve your programming skills.
