C Build the Logic
What is Logic?
In the previous chapter, you learned the four steps of problem solving. For many beginners, the hardest step is to plan the solution: 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: most problems are built from a few small building blocks. When you can see which blocks a problem needs, 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 often tell you which block you need:
| Block | Use it when the question is... | Code inside the loop |
|---|---|---|
| Count | "How many ...?" | if (...) count++; |
| Sum | "What is the total ...?" | sum += scores[i]; |
| Find the biggest | "Which is the highest ...?" | if (scores[i] > max) max = scores[i]; |
| Search | "Is there a ...?" | if (scores[i] == 100) found = 1; |
This example uses all four blocks on a list of test scores:
Example
#include <stdio.h>
int main() {
int scores[] = {72, 95, 61, 88, 79};
int length = sizeof(scores) / sizeof(scores[0]);
int count = 0;
int sum = 0;
int max = scores[0];
int found = 0;
for (int i = 0; i < length; i++) {
if (scores[i] >= 70) { // Count
count++;
}
sum += scores[i]; // Sum
if (scores[i] > max) { // Find the biggest
max = scores[i];
}
if (scores[i] == 100) { // Search
found = 1;
}
}
printf("Passed: %d\n", count);
printf("Total: %d\n", sum);
printf("Highest: %d\n", max);
printf("Anyone got 100? %s\n", found ? "Yes" : "No");
return 0;
}
Result:
Passed: 4
Total: 395
Highest: 95
Anyone got 100? No
Try it Yourself »
Tip: max starts with the first score, not with 0. That way it also works when all the values are negative.
Worked Problem: Grades
Let's build the logic for a real problem. A teacher wants to turn test scores into words:
- 90 or more: Excellent
- 75 or more: Good
- 50 or more: Pass
- Less than 50: Fail
It is tempting to start with the lowest limit. But then the code gives the wrong answer for 95:
Example
if (score >= 50) {
printf("%d: Pass\n", score); // 95 stops here: wrong!
} else if (score >= 75) {
printf("%d: Good\n", score);
} else if (score >= 90) {
printf("%d: Excellent\n", score);
}
95 is more than 50, so the first condition is true, and the program never checks the other rules.
The fix: when the rules overlap, check the strictest rule first. Start with 90, then 75, then 50:
Example
#include <stdio.h>
int main() {
int scores[] = {95, 80, 60, 30};
for (int i = 0; i < 4; i++) {
int score = scores[i];
if (score >= 90) {
printf("%d: Excellent\n", score);
} else if (score >= 75) {
printf("%d: Good\n", score);
} else if (score >= 50) {
printf("%d: Pass\n", score);
} else {
printf("%d: Fail\n", score);
}
}
return 0;
}
Result:
95: Excellent
80: Good
60: Pass
30: Fail
Try it Yourself »
Choose a score below, and follow its path through the conditions. The last button shows what happens with the wrong order:
Follow the path
Output
Explanation
Check the Logic With a Trace Table
A trace table lets you check your logic by hand, before you run the program. Write one row for each test value, and follow the code one condition at a time.
Here is the trace table for the grades code. A dash (-) means that the condition is never checked, because an earlier condition was already true:
| score | >= 90? | >= 75? | >= 50? | Result |
|---|---|---|---|---|
| 95 | yes | - | - | Excellent |
| 80 | no | yes | - | Good |
| 60 | no | no | yes | Pass |
| 30 | no | no | no | Fail |
All four results are correct. Notice how the test values were chosen: one for each possible result.
Tips for Building Logic
- Solve the problem by hand first, and notice what you do. "I look at each number" means a loop. "I remember the biggest one" means the "find the biggest" block.
- Write the steps in plain words before you write code.
- When the rules overlap, check the strictest rule first.
- Use a trace table to check your logic before you run it.
Many of our C Practice Problems are built from these blocks, like Sum of Numbers, Average Score and Min and Max.
Your logic may work for the values you tried. But what about unusual input? In the next chapter, you will learn how to find edge cases and logical errors.