Explain it simply
Explain it simply
This lesson has no new syntax. It has four tasks that put the Basics chapter to work: variables, operators, if...else, loops, arrays and strings. Understanding a language when you read it is not the same as writing it, and the only reliable way to start writing is to write code yourself and find your own mistakes.
Think of an accountant re-checking figures. Getting an answer is not the end; the next question is "does it also hold for other inputs?" Each task here trains that habit. Write your own version first, then compare it with the reference solution, and read why the solution is written the way it is only at that point.
Problem → Why → Solution
The problem: a first draft that runs and is wrong in three places
The draft below compiles under g++ without an error and it runs. But three answers are wrong. The average is computed as sum / 5, which prints 13 instead of 13.2, because dividing two ints throws the fraction away. Age 60 prints "Adult" although 60 and above should be Senior, because the condition says <= 60. The even-number list stops at 48, because i < 50 excludes 50.
In all three, the code passes a casual test. You only discover that something is wrong by looking at a boundary value such as 60, or by checking the last element of the result yourself, not by trying an exotic input.
#include <iostream>
int main() {
int nums[5] = {4, 8, 15, 16, 23};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += nums[i];
}
std::cout << "average: " << sum / 5 << '\n'; // prints 13, the real average is 13.2
int age = 60;
if (age < 18) {
std::cout << "Minor\n";
} else if (age <= 60) { // meant: Senior starts AT 60
std::cout << "Adult\n";
} else {
std::cout << "Senior\n";
}
for (int i = 2; i < 50; i += 2) { // stops before 50
std::cout << i << ' ';
}
std::cout << '\n';
}Why doesn't the compiler complain?
The compiler follows exactly what you wrote. sum / 5 divides an int by an int, so an int result is legal, and age <= 60 is an ordinary condition. A program cannot know whether a condition matches the specification. Turning the specification's boundaries into test values and trying them is the programmer's job.
Core concept: know the trap behind each task
Each practice task is small, but each one hides a trap that experienced programmers still have to watch for. In C++ the traps are sharper, because the compiler accepts most of them without an error. The four steps below name the pattern behind each task.
1. Task 1: accumulate, then cast before dividing
Start the total at 0 and add the elements one by one. When you compute the average, convert one side of the division to double first (static_cast<double>(sum) / nums.size()); otherwise it is integer division and the fraction vanishes. Check for an empty list first as well: dividing by zero elements describes an average that does not exist, so say "no average".
2. Task 2: read an if...else chain from the top down
A chain tests from the top and runs only the first branch that is true. That is why the second branch, else if (age < 60), does not re-check age >= 18: the branch above already removed those ages. Write each limit in one place, then test both sides of every boundary: 17 and 18, 59 and 60. Testing only one side misses half of the off-by-one bugs.
3. Task 3: count without .length()
A range-based for hands you the characters of the string one at a time and you add one to a counter. Because the loop never uses the char itself, [[maybe_unused]] tells the compiler that this is deliberate. An empty string never enters the loop, so it gives 0. Remember, though, that a char is one byte, not one letter. For ASCII they are the same, but the Myanmar word "မြန်မာ" is 18 bytes in UTF-8, so this loop would answer 18.
4. Task 4: decide a loop's start, step and bound
For even numbers, starting at 1 and testing % 2 also works, but starting at 2 and stepping by 2 needs only 25 iterations. When the spec says "up to 50", decide in advance whether 50 is included; if it is, the condition must be i <= 50, because with i < 50 the last number is 48. Deliberately look at the first and last element of the result.
| Task | The trap | Values to test |
|---|---|---|
| Average | Integer division | {4, 8, 15, 16, 23} and {} |
| Age | Wrong boundary | 17, 18, 59, 60, -1 |
| Length | Bytes vs letters | "", "C++" |
| Evens | Off-by-one at the end | limit 50 and limit 1 |
The reference solution turns each task into a function that receives its data as a parameter. That lets main() call a function with many different inputs without anyone typing at a keyboard. When reading input is kept apart from the calculation, the calculation can be tested again and again, which is the same habit you met in the Student Manager project.
- Predict the output before running
- Run it and compare with the prediction
- Feed it empty and boundary input
- Only then read the reference solution
A correct answer proves only that one test passed. You can trust your code once you have tried to break it yourself.
General pattern
double total = 0.0; // accumulate
for (int item : items) total += item;
double avg = items.empty() ? 0.0 : total / items.size(); // guard the empty case
if (x < lowLimit) { /* smallest range */ } // boundary chain, smallest first
else if (x < highLimit) { /* middle range */ }
else { /* everything from highLimit up */ }
for (int i = first; i <= last; i += step) { /* inclusive bounds */ }Three patterns: an accumulating loop, a boundary chain that starts from the smallest range, and a counting loop with an inclusive bound you chose on purpose. All four tasks reuse one of these.
Reference solution: four tasks, many inputs
In the program below, each task is one function. main() calls each one with a normal value and also with an empty list, a negative age, an empty string and a small limit such as 1. The values are written into the code, so every run prints the same output. To type your own values, add lines that read from std::cin in main() and call the same functions.
#include <iostream>
#include <string>
#include <vector>
// Task 1: sum and average. An empty list has a sum (0) but no average.
void printSumAndAverage(const std::vector<int>& nums) {
int sum = 0;
for (int n : nums) {
sum += n;
}
std::cout << " sum " << sum;
if (nums.empty()) {
std::cout << ", no average (empty list)\n";
return;
}
double average = static_cast<double>(sum) / nums.size();
std::cout << ", average " << average << '\n';
}
// Task 2: classify an age. 18 is the first Adult age, 60 the first Senior age.
std::string classifyAge(int age) {
if (age < 0) {
return "Invalid";
} else if (age < 18) {
return "Minor";
} else if (age < 60) {
return "Adult";
}
return "Senior";
}
// Task 3: count characters with a loop instead of .length().
int manualLength(const std::string& text) {
int count = 0;
for ([[maybe_unused]] char c : text) {
++count;
}
return count;
}
// Task 4: even numbers from 2 to limit, one space between, no trailing space.
void printEvens(int limit) {
std::cout << " ";
int printed = 0;
for (int i = 2; i <= limit; i += 2) {
if (printed > 0) {
std::cout << ' '; // separator before every number except the first
}
std::cout << i;
++printed;
}
if (printed == 0) {
std::cout << "(none)";
}
std::cout << " [" << printed << " numbers]\n";
}
int main() {
std::cout << "Task 1\n";
printSumAndAverage({4, 8, 15, 16, 23});
printSumAndAverage({});
std::cout << "Task 2\n";
for (int age : {-1, 0, 17, 18, 59, 60, 95}) {
std::cout << " " << age << " -> " << classifyAge(age) << '\n';
}
std::cout << "Task 3\n";
for (std::string text : {"C++", "hello world", ""}) {
std::cout << " \"" << text << "\" -> " << manualLength(text) << '\n';
}
std::cout << "Task 4\n";
printEvens(50);
printEvens(1);
}Code breakdown
- Cast before dividing
double average = static_cast<double>(sum) / nums.size();sum is 66. static_cast<double> turns the first operand into 66.0, so the division is 66.0 / 5 = 13.2. Without the cast it would be 66 / 5 in int arithmetic, which is 13.
- Guard the empty case
if (nums.empty()) {An empty list has a sum of 0 but no average. Instead of dividing, the function says "no average (empty list)" and returns.
- The boundary lives here
} else if (age < 60) {Any age that reaches this line is already 18 or more. So 59 is Adult, and 60 fails this test, falls through to the else and becomes Senior. The output shows 59 and 60 side by side.
- A deliberately unused loop variable
for ([[maybe_unused]] char c : text) {The loop never uses the char itself; it only counts iterations. Without [[maybe_unused]], -Wall prints an unused-variable warning. "hello world" includes the space, so the answer is 11.
- Separator before, not after
std::cout << ' '; // separator before every number except the firstPutting a space after every number leaves a stray space at the end. Putting it before every number except the first avoids the trailing space. For limit 1 nothing is printed, so "(none)" appears.
- Both sides of every boundary
for (int age : {-1, 0, 17, 18, 59, 60, 95}) {This tries both sides of each age boundary (17/18 and 59/60), the minimum 0 and the impossible -1, which prints "Invalid".
Task 1
sum 66, average 13.2
sum 0, no average (empty list)
Task 2
-1 -> Invalid
0 -> Minor
17 -> Minor
18 -> Adult
59 -> Adult
60 -> Senior
95 -> Senior
Task 3
"C++" -> 3
"hello world" -> 11
"" -> 0
Task 4
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 [25 numbers]
(none) [0 numbers]- Is age < 0? Invalid
- Is age < 18? Minor
- Is age < 60? Adult
- Otherwise: Senior
age = 59
Adult (last Adult age)
age = 60
Senior (first Senior age)
Watch out for % with negative numbers
In Task 4, testing evens with i % 2 == 0 is correct for negative numbers too. But testing odd numbers with n % 2 == 1 is wrong for negatives. In C++, division truncates toward zero and the sign of the remainder follows the dividend, so -7 / 2 is -3 and -7 % 2 is -1. To test for odd, write n % 2 != 0.
#include <iostream>
int main() {
std::cout << -7 / 2 << ' ' << -7 % 2 << '\n';
std::cout << (-4 % 2 == 0) << ' ' << (-3 % 2 == 1) << ' ' << (-3 % 2 != 0) << '\n';
}This program prints "-3 -1" and then "1 0 1". Read the second line: -4 is even (1), -3 % 2 == 1 is false (0), and -3 % 2 != 0 is true (1). This is also why the digit functions in the challenge convert a negative number to a positive one first.
In real projects
In real projects
These four tasks have the shape of real bugs. In an entry fee, a tax bracket, a shipping threshold or a grading scale, a wrong boundary between "under 18" and "18 and over" costs real money. A dashboard showing NaN for a group that has no data yet has made the same mistake as Task 1's empty case: it divided by zero.
Pagination resembles Task 4. A last page that disappears, or an extra empty page, usually comes from a wrong loop bound. Interviewers like tasks of this kind because the code is short but still tests boundary reasoning fully. Once testing the edges is a habit, a single question in code review, "did you try 17 and 18?", can catch a bug before it ships.
Common mistakes
Common mistakes
Dividing two ints and expecting a fraction
In sum / 5 both operands are int, so 66 / 5 is 13. Storing that in a double variable still gives 13.0, because the conversion happens after the division, when the fraction is already gone. Convert one operand to double before you divide.
Choosing < or <= wrongly
If "60 and over is Senior" is written as else if (age <= 60) for Adult, then 60 becomes Adult. Think of the limit as the first value that belongs to the next group (60) and write it with <. Then test 59 and 60 on purpose.
An off-by-one error in the loop's end
i < 50 leaves out 50 and i <= 50 includes it. With array indexes it is the other way round: int nums[5] has indexes 0 to 4, so i <= 5 reads nums[5], which is outside the array (undefined behaviour). For every loop ask whether the bound is inclusive or exclusive.
Expecting cin >> text to read a whole line
std::cin >> text stops at the first space. If the user types "hello world", text holds only "hello" and the length comes out as 5. Reading "hello world" from a stream shows the difference: >> gives "hello" while std::getline gives the full "hello world". Use getline for text that may contain spaces.
Leaving a deliberate unused variable as a warning
Writing for (char c : text) count++; makes g++ -Wall -Wextra print warning: unused variable 'c' [-Wunused-variable]. If you tolerate warnings, you stop noticing the ones that matter. Add [[maybe_unused]] or restructure the loop.
Mini challenge
Work with the digits of a number
Write three functions that take an int and report its number of digits, the sum of its digits and whether it is a palindrome. Do not use strings; use only % 10 and / 10. Handle 0, negative numbers and the smallest int correctly.
- countDigits(0) must return 1, and the minus sign is not a digit
- digitSum(-121) must return 4 (a negative number still has digits to add)
- isPalindrome must return false for every negative number
- The smallest int (-2147483648) must not overflow; take its absolute value in a long long
- Print one aligned row per number with n, digits, sum and palindrome
// Work on the absolute value as a long long, so the smallest int is safe too.
long long absValue(int n); // TODO
int countDigits(int n) {
// TODO: 0 has one digit; ignore the minus sign
}
int digitSum(int n) {
// TODO: peel digits off with % 10 and / 10, add them up
}
bool isPalindrome(int n) {
// TODO: negative numbers are never palindromes
// TODO: build the reversed number digit by digit and compare it with n
}
int main() {
// TODO: test 0, 7, 1221, 1231, -121, 1000 and the smallest int
// TODO: print one aligned row per number: n, digits, digit sum, palindrome?
}Expected: One header line and seven rows. 0 and 7 have 1 digit and are palindromes; 1221 has 4 digits, sum 6, yes; 1231 has sum 7, no; -121 has 3 digits, sum 4, no; 1000 has sum 1, no; -2147483648 has 10 digits, sum 47, no.
Show hint
-n overflows for the smallest int, because the largest int is only 2147483647. Put n into a long long variable first and remove the sign there. To reverse, repeat reversed = reversed * 10 + rest % 10 while rest > 0. Start countDigits with digits = 1 so that 0 counts as one digit.
Show solution
#include <format>
#include <iostream>
#include <limits>
// Work on a long long copy so that the most negative int can be made positive.
long long absValue(int n) {
long long value = n;
return value < 0 ? -value : value;
}
int countDigits(int n) {
long long value = absValue(n);
int digits = 1; // 0 still has one digit
while (value >= 10) {
value /= 10;
++digits;
}
return digits;
}
int digitSum(int n) {
long long value = absValue(n);
int sum = 0;
while (value > 0) {
sum += static_cast<int>(value % 10);
value /= 10;
}
return sum;
}
bool isPalindrome(int n) {
if (n < 0) {
return false; // "-121" read backwards is "121-"
}
long long reversed = 0;
for (long long rest = n; rest > 0; rest /= 10) {
reversed = reversed * 10 + rest % 10;
}
return reversed == n;
}
int main() {
const int tests[] = {0, 7, 1221, 1231, -121, 1000, std::numeric_limits<int>::min()};
std::cout << std::format("{:>11} {:>6} {:>3} {}\n",
"n", "digits", "sum", "palindrome");
for (int n : tests) {
std::cout << std::format("{:>11} {:>6} {:>3} {}\n", n, countDigits(n),
digitSum(n), isPalindrome(n) ? "yes" : "no");
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Integer division drops the fraction: convert one operand to double and check for an empty list first
- Read an if...else chain top-down and test both sides of every boundary value
- Decide whether each loop bound is inclusive or exclusive and check the first and last element
- Split each task into a function and trust it only after trying empty and boundary input
The Current ISO C++ Standard (C++23) — Standard C++ Foundation