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
forkeyword that indicates the start of aforloop. char letteris 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 nameis 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.
Free plan: 30 tutor messages. PRO is unlimited.
