C++ Build the Logic
What is Logic?
In the previous chapter, you learned the four steps of problem solving. For many beginners, step 2 is the hardest: you understand the problem, but you do not know what code to write.
The plan is called the logic of the program: the steps and decisions that turn the input into the output.
The good news: many problems are built from the same few building blocks. When you can spot them, the code is much easier to write.
The Building Blocks
A building block is a small piece of code that does one common job. You can use it again and again, in many different programs.
Each block below uses a loop to look at the values one at a time. With each value, it does one small job: count it, add it, compare it, or look for it. The words in the question tell you which block you need:
| Block | The problem asks... | Code inside the loop |
|---|---|---|
| Count | "How many ...?" | if (p > 80) { count++; } |
| Sum | "What is the total ...?" | sum += p; |
| Max or Min | "What is the highest ...?" | if (p > max) { max = p; } |
| Search | "Is there a ...?" | if (p == 100) { found = true; } |
This example uses all four blocks on the points of five players in a game:
Example
#include <iostream>
using namespace std;
int main() {
int points[5] = {72, 95, 61, 88, 79};
int count = 0;
int sum = 0;
int max = points[0];
bool found = false;
for (int p : points) {
if (p > 80) { // Count
count++;
}
sum += p; // Sum
if (p > max) { // Max
max = p;
}
if (p == 100) { // Search
found = true;
}
}
cout << "More than 80 points: " << count << "\n";
cout << "Total points: " << sum << "\n";
cout << "Best score: " << max << "\n";
cout << "Anyone with 100? " << (found ? "Yes" : "No") << "\n";
return 0;
}
Result:
More than 80 points: 2
Total points: 395
Best score: 95
Anyone with 100? No
Try it Yourself »
Which Block Do You Need?
Spotting the right block gets easier with practice. Try it now: for each question about the game, choose the block you need:
Question
Code
Explanation
Tips for Building Logic
- Look for the question words: "how many" (Count), "total" (Sum), "highest" or "lowest" (Max or Min), and "is there" (Search).
- Choose the start value first:
count = 0,sum = 0,max = points[0]orfound = false. - Many problems use more than one block. An average, for example, is a sum divided by the number of values.
Many of our C++ Practice Problems are built from these blocks, like Sum of Numbers, Average Score and Min and Max.