The Largest Value
The third pattern finds the largest value. Imagine going through a pile of exam papers to find the best one. You pick up the first paper. Then you look at the others one by one, and whenever one is better than the paper in your hand, you take that one instead. At the end, you are holding the best paper. In code, the paper in your hand is a variable:
std::vector<int> scores = {72, 45, 90, 38, 64};
int highest = scores[0];
for (int score : scores) {
if (score > highest) {
highest = score;
}
}
std::cout << "Highest score: " << highest << std::endl;Highest score: 90The variable highest starts with the first element. Then the loop compares each score with it: 72 is not greater than 72, 45 isn't either, but 90 is, so highest becomes 90. Neither 38 nor 64 is greater than 90, so 90 stays until the end.
Why not start with 0? Because 0 might not be one of the values. If all the values were negative, for example the winter temperatures {-5, -2, -8}, the starting 0 would remain the largest, and the program would print 0, a temperature that isn't in the vector at all. The first element is always a safe start, as long as the vector isn't empty.
You find the smallest value the same way, only with < instead of >.
Sometimes you compare one thing but want to keep another. To find the longest name, compare the sizes of the names, but store the name itself:
std::vector<std::string> names = {"Eva", "Christopher", "Adam"};
std::string longest = names[0];
for (std::string name : names) {
if (name.size() > longest.size()) {
longest = name;
}
}
std::cout << "Longest name: " << longest << std::endl;Longest name: ChristopherInstructions
The vector prices holds the prices of headphones in an online shop. Create a variable highest of type int with the first price, prices[0].
Go through prices with a loop, and whenever a price is greater than highest, store it in highest. After the loop, print the result as Most expensive: 2499.
Find the price of the cheapest headphones the same way: with a variable lowest that starts with the first price, and with < instead of >. Print the result as Cheapest: 179.
Start programming for free
8/13