These are the notes for C++ Coding Questions, episode 28, placement practice for people who finished the SyntaxPilot C++ course. In a written placement test you get a few lines of C++ and one question: what does it print? The code looks simple; the answer almost never is. Today: an average that loses its decimals (integer division), a loop that crashes on an empty vector (signed vs unsigned), an OTP whose digits add up to 204 (char arithmetic), i++ + ++i (undefined behaviour), and a token counter that forgets (static locals).
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the cost.
Every program was compiled with g++ -Wall -O2 -std=c++17 main.cpp -o main (g++ 13.3, Linux x86-64), the SyntaxPilot compiler's C++ command with warnings on, and every output below is real, including the warnings and the crash.
Real-life pictures
| In real life | In C++ |
|---|---|
| A clerk's calculator with no decimal key: 217 ÷ 3 shows 72 | int / int gives an int: the fraction is thrown away |
| Copying 72 onto a form with decimals: 72.00 | storing the result in a double is too late |
| Using a calculator with decimals from the start | make one side a double before dividing |
| A trip meter at 00000 wound back one km shows 99999 | size_t is unsigned: 0 - 1 wraps to the biggest value |
| Train seat rows A, B, C stored as 65, 66, 67 | a char is a small number, its ASCII code |
| "The row after C" = 67 + 1 = 68 = D | 'C' + 1 is the int 68; store it in a char to print D |
| A bank's token machine that resets after every customer | a normal local variable is made fresh on every call |
| A token counter that keeps its number | a static local variable |
Q1: Integer division
Problem. What does this print?
int total = 72 + 85 + 60; // 217
double average = total / 3;
cout << average;
Think out loud. average is a double, so most people answer 72.3333. Keep one rule in mind: integer division, an int divided by an int, gives an int, and the fraction is thrown away. Edge cases: where the cast goes, and negative numbers.
The obvious attempt
#include <iostream>
using namespace std;
int main() {
int maths = 72, science = 85, english = 60;
int total = maths + science + english;
double average = total / 3; // average marks
cout << "total: " << total << "\n";
cout << "average: " << average << "\n";
return 0;
}
Real output (no warning, even with -Wall):
total: 217
average: 72
Why
C++ works out the right-hand side first, using the types of its operands. total / 3 is int / int, so the result is the int 72. Only then is 72 converted to the double 72.0 and stored. The type of the variable on the left never changes how the right side is calculated. cout prints a double with no fractional part as 72.
(double)(total / 3) is too late as well: the brackets are worked out first, as ints.
The fix: make one side a double before dividing
#include <iostream>
using namespace std;
int main() {
int maths = 72, science = 85, english = 60;
int total = maths + science + english;
double late = (double)(total / 3); // cast too late
double right = static_cast<double>(total) / 3; // cast first
double also = total / 3.0; // a double literal
cout << "cast too late: " << late << "\n";
cout << "cast first: " << right << "\n";
cout << "3.0: " << also << "\n";
cout << "7 / 2 = " << 7 / 2 << ", -7 / 2 = " << -7 / 2 << "\n";
cout << "-7 % 2 = " << -7 % 2 << "\n";
return 0;
}
Real output:
cast too late: 72
cast first: 72.3333
3.0: 72.3333
7 / 2 = 3, -7 / 2 = -3
-7 % 2 = -1
static_cast<double>(total)is the C++ way to write a cast: it is easy to search for and the compiler checks it. Once one operand is adouble, the other is converted too (usual arithmetic conversions), and the division keeps the fraction.coutshows 6 significant digits by default, so 72.333333... prints as72.3333. Usefixed << setprecision(2)from<iomanip>for72.33.- Since C++11, integer division truncates toward zero:
-7 / 2is-3, not-4. And%follows from it:a == (a / b) * b + a % b, so-7 % 2is-1. The remainder takes the sign of the left operand.
Cost. Each division is O(1).
Q2: Signed vs unsigned (size() - 1)
Problem. A shop records its sales each day. Count the days that sold more than the day before.
{120, 80, 95, 130, 110} → 2 (80→95 and 95→130)
{} → 0 (a new shop)
{50} → 0 (only one day)
Think out loud. Compare day i with day i + 1; the last i is size() - 2, so loop while i < size() - 1. Edge cases: an empty vector, and a vector with one element.
The obvious attempt
#include <iostream>
#include <vector>
using namespace std;
int risingDays(const vector<int>& sales) {
int count = 0;
for (int i = 0; i < sales.size() - 1; i++) // compare day i with day i+1
if (sales[i + 1] > sales[i]) count++;
return count;
}
int main() {
vector<int> week = {120, 80, 95, 130, 110};
cout << "rising days: " << risingDays(week) << endl;
vector<int> newShop; // no sales yet
cout << "new shop: " << risingDays(newShop) << endl;
return 0;
}
Real result:
main.cpp: In function 'int risingDays(const std::vector<int>&)':
main.cpp:7:23: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
7 | for (int i = 0; i < sales.size() - 1; i++) // compare day i with day i+1
| ~~^~~~~~~~~~~~~~~~~~
rising days: 2
Segmentation fault
(The program exits with code 139: the operating system stopped it for reading memory it does not own.)
Why
size() returns size_t, an unsigned whole number type: it has no negative values. For the empty vector, size() is 0, and 0 - 1 does not give -1: unsigned arithmetic wraps round modulo 2^64, to the biggest size_t.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> newShop;
cout << "size: " << newShop.size() << "\n";
cout << "size - 1: " << newShop.size() - 1 << "\n";
return 0;
}
size: 0
size - 1: 18446744073709551615
i < 18446744073709551615 is true for every int i, so the loop reads sales[1], sales[2], ... memory the empty vector never owned, until the program crashes. That is undefined behaviour; a crash is the lucky outcome.
The warning said more: when an int meets a size_t in a comparison, the int is converted to unsigned. So -1 < v.size() is false (-1 becomes 18446744073709551615). Never ignore -Wsign-compare.
The fix: never subtract from size(); count up from 1
#include <iostream>
#include <vector>
using namespace std;
int risingDays(const vector<int>& sales) {
int count = 0;
for (size_t i = 1; i < sales.size(); i++) // compare day i with day i-1
if (sales[i] > sales[i - 1]) count++;
return count;
}
int main() {
vector<int> week = {120, 80, 95, 130, 110};
cout << "rising days: " << risingDays(week) << endl;
vector<int> newShop; // no sales yet
cout << "new shop: " << risingDays(newShop) << endl;
vector<int> oneDay = {50};
cout << "one day: " << risingDays(oneDay) << endl;
return 0;
}
Real output (no warning):
rising days: 2
new shop: 0
one day: 0
Other safe ways: if (sales.empty()) return 0; first; i + 1 < sales.size(); or C++20's std::ssize(v), which returns a signed size. Cost: O(n) time, one pass; O(1) extra space.
Q3: char arithmetic
Problem. An OTP is stored as the string "4071". Add up its digits (expected 12). And for train seats, print the row after 'C' (expected D).
Think out loud. ASCII is the table that gives every character a number: 'A' = 65, 'a' = 97, '0' = 48. A char in C++ is a small integer holding that code. Edge cases: the character '7' is not the number 7; and what does 'C' + 1 print?
The obvious attempt
#include <iostream>
#include <string>
using namespace std;
int main() {
string otp = "4071";
int sum = 0;
for (char d : otp) sum += d; // add up the digits
cout << "digit sum: " << sum << "\n";
char row = 'C';
cout << "next row: " << row + 1 << "\n";
return 0;
}
Real output:
digit sum: 204
next row: 68
Why
The characters '4' '0' '7' '1' are stored as their codes 52, 48, 55, 49, and 52 + 48 + 55 + 49 = 204. We added the codes, not the digits.
row + 1: before arithmetic, a char is promoted to int (integral promotion), so 'C' + 1 is the int 68, and cout << int prints a number.
The fix
#include <iostream>
#include <string>
using namespace std;
int main() {
string otp = "4071";
int sum = 0;
for (char d : otp) sum += d - '0'; // '7' - '0' = 7
cout << "digit sum: " << sum << "\n";
char row = 'C';
char next = row + 1; // store it as a char
cout << "next row: " << next << "\n";
cout << "as a number: " << (int)row << ", '0' is " << (int)'0' << "\n";
cout << "lowercase: " << char(row + 32) << "\n";
return 0;
}
Real output:
digit sum: 12
next row: D
as a number: 67, '0' is 48
lowercase: c
- The digit codes are consecutive (
'0'..'9'= 48..57; the C++ standard guarantees digits are consecutive), sod - '0'is the digit's value. - Store the result in a
char(or writechar(row + 1)) andcoutprints the letter. - Small letters are 32 places after capitals in ASCII, so
char(row + 32)is'c'. Prefertolower/toupperfrom<cctype>in real code.
Cost. O(length of the string).
Rapid fire 1: i++ + ++i
i++ (post-increment): use the old value, then add 1. ++i (pre-increment): add 1, then use the new value.
#include <iostream>
using namespace std;
int main() {
int i = 5;
int x = i++ + ++i; // what is x?
cout << "x = " << x << ", i = " << i << "\n";
return 0;
}
Real result with g++:
main.cpp: In function 'int main()':
main.cpp:6:14: warning: operation on 'i' may be undefined [-Wsequence-point]
6 | int x = i++ + ++i; // what is x?
| ~^~
x = 12, i = 7
clang says: warning: multiple unsequenced modifications to 'i' [-Wunsequenced].
Why. i is modified twice in one expression, and the two sides of + are unsequenced: C++ does not say which runs first. Modifying the same scalar twice without sequencing is undefined behaviour, so any result is allowed. g++ happened to print 12. The correct answer in a test is "undefined behaviour".
Fix: one change per statement.
#include <iostream>
using namespace std;
int main() {
int i = 5;
int a = i++; // a = 5, then i = 6
int b = ++i; // i = 7, then b = 7
cout << "a + b = " << a + b << ", i = " << i << "\n";
return 0;
}
a + b = 12, i = 7
Note: since C++17, cout << a << b evaluates left to right, and i = i + 1 is fine; but i++ + ++i, i = i++ + 1 style expressions and f(i++, i++) (unspecified order) are still traps.
Rapid fire 2: static locals
A bank's token machine should give tokens 1, 2, 3.
#include <iostream>
using namespace std;
int nextToken() {
int token = 0; // the bank's token counter
token++;
return token;
}
int main() {
for (int k = 0; k < 3; k++)
cout << "token " << nextToken() << "\n";
return 0;
}
token 1
token 1
token 1
Why. A normal local variable has automatic storage duration: it is created each time the function runs and destroyed when it returns, so token starts at 0 on every call.
Fix: a static local is created once, the first time control passes its declaration, and lives until the program ends.
#include <iostream>
using namespace std;
int nextToken() {
static int token = 0; // made ONCE, kept between calls
token++;
return token;
}
int main() {
for (int k = 0; k < 3; k++)
cout << "token " << nextToken() << "\n";
return 0;
}
token 1
token 2
token 3
static int token = 0; runs only once. Each call is O(1). (Since C++11, initialising a static local is thread-safe.)
Cost summary
| Question | Obvious attempt | Fix | Time | Extra space |
|---|---|---|---|---|
| Integer division | total / 3 → 72 |
static_cast<double>(total) / 3 |
O(1) | O(1) |
| Rising days | i < size() - 1 → crash on {} |
size_t i = 1; i < size() |
O(n) | O(1) |
| OTP digit sum | sum += d → 204 |
sum += d - '0' |
O(len) | O(1) |
i++ + ++i |
undefined (12 here) | two statements | O(1) | O(1) |
| Token counter | always 1 | static int token |
O(1) | O(1) |
Common mistakes (and the real results)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
double avg = total / 3; |
no error: 72 |
int / int drops the fraction |
static_cast<double>(total) / 3 |
(double)(total / 3) |
no error: 72 |
the cast comes after the division | cast an operand, not the result |
expecting -7 / 2 == -4 |
-3 |
integer division truncates toward zero | use floor on doubles if you need rounding down |
i < v.size() - 1 with int i |
warning: comparison of integer expressions of different signedness ... [-Wsign-compare], then Segmentation fault on an empty vector |
0 - 1 wraps for size_t |
start at i = 1, use size_t, or check empty() |
-1 < v.size() |
false |
the int is converted to unsigned |
compare with ssize(v) or cast carefully |
sum += d over digit chars |
204 instead of 12 |
'7' is the code 55 |
sum += d - '0' |
cout << row + 1; |
68 |
char + int is an int |
char next = row + 1; |
int x = i++ + ++i; |
warning: operation on 'i' may be undefined [-Wsequence-point] |
two unsequenced changes to i |
one change per statement |
| counter as a plain local | always 1 |
a local is made fresh each call | static int token = 0; |
Mini project: a report card printer
Uses all five ideas: a static roll-number counter, the average with a cast, a size_t loop that counts up, and char arithmetic for the "next goal" grade.
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
int nextRoll() {
static int roll = 100; // made once, remembers
return ++roll;
}
char grade(double avg) {
if (avg >= 90) return 'A';
if (avg >= 75) return 'B';
if (avg >= 60) return 'C';
return 'D';
}
int main() {
vector<string> names = {"Asha", "Ravi", "Neha"};
vector<vector<int>> marks = {{72, 85, 60}, {91, 88, 95}, {55, 61, 58}};
cout << fixed << setprecision(2);
for (size_t i = 0; i < names.size(); i++) { // size_t, counting up
int total = 0;
for (int m : marks[i]) total += m;
double avg = static_cast<double>(total) / marks[i].size();
char g = grade(avg);
char next = (g == 'A') ? 'A' : char(g - 1); // one grade better
cout << nextRoll() << " " << names[i] << ": total " << total
<< ", average " << avg << ", grade " << g
<< " (next goal: " << next << ")\n";
}
return 0;
}
Real output:
101 Asha: total 217, average 72.33, grade C (next goal: B)
102 Ravi: total 274, average 91.33, grade A (next goal: A)
103 Neha: total 174, average 58.00, grade D (next goal: C)
Note total / marks[i].size(): size() is a size_t, so even int / size_t would be integer division. The static_cast<double> makes it a double division.
Practice questions (with solutions)
1. Your turn: what does it print?
#include <iostream>
using namespace std;
int count() { static int n = 10; return n--; }
int main() {
unsigned int u = 0;
cout << count() << count() << " ";
cout << (u - 1 > 0) << " " << 9 / 2 * 2.0;
}
Solution
Real output: 109 1 8
count():nis static, made once as 10.n--returns the old value and then subtracts: first call 10, second call 9. Since C++17, the operands of<<are evaluated left to right, so it prints10then9:109.u - 1withuunsigned 0 wraps to 4294967295, which is> 0:1.9 / 2 * 2.0: left to right,9 / 2is int division = 4, then4 * 2.0=8(a double, printed as8).
2. Loop backwards over a vector safely.
Solution
for (size_t i = v.size() - 1; i >= 0; i--) never ends: a size_t is always >= 0, and 0 - 1 wraps. Test, then subtract:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {10, 20, 30};
for (size_t i = v.size(); i-- > 0; ) // i = 2, 1, 0
cout << v[i] << " ";
cout << "\n";
vector<int> e;
for (size_t i = e.size(); i-- > 0; ) cout << e[i]; // runs 0 times
cout << "empty: done\n";
return 0;
}
30 20 10
empty: done
(Or use for (auto it = v.rbegin(); it != v.rend(); ++it).)
3. Average of a vector<int> as a double, safe for an empty vector.
Solution
#include <iostream>
#include <vector>
using namespace std;
double average(const vector<int>& v) {
if (v.empty()) return 0.0; // no division by zero
long long sum = 0;
for (int x : v) sum += x;
return static_cast<double>(sum) / v.size();
}
int main() {
cout << average({72, 85, 60}) << "\n";
cout << average({1, 2}) << "\n";
cout << average({}) << "\n";
return 0;
}
72.3333
1.5
0
long long for the sum avoids overflow on big inputs.
4. Count vowels and digits in a string, and add up the digits.
Solution
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string s = "Order 42 for Priya at 7";
int vowels = 0, digits = 0, digitSum = 0;
for (char c : s) {
char low = tolower(static_cast<unsigned char>(c));
if (low == 'a' || low == 'e' || low == 'i' || low == 'o' || low == 'u') vowels++;
if (c >= '0' && c <= '9') { digits++; digitSum += c - '0'; }
}
cout << "vowels: " << vowels << ", digits: " << digits << ", digit sum: " << digitSum << "\n";
return 0;
}
vowels: 6, digits: 3, digit sum: 13
Pass tolower an unsigned char value: a negative char is undefined behaviour for the <cctype> functions.
Quick quiz
1. What does this print? (the episode quiz)
int a = 7, b = 2;
double r = a / b;
char c = 'a' + 2;
cout << r << " " << c;
(A) 3.5 c (B) 3 c (C) 3 99 (D) 3.5 99
Answer
(B) 3 c. a / b is int division: 3, stored as 3.0 and printed as 3. 'a' + 2 = 99, stored in a char: c.
2. What does this print?
cout << 5 / 2 * 2 << " " << 5 * 2 / 2 << " " << 5 / 2.0 * 2 << "\n";
unsigned int a = 3; int b = -5;
cout << (a + b > 0) << " " << a + b << "\n";
char c = '9';
cout << c + 1 << " " << char(c + 1) << " " << c - '0' + 1 << "\n";
Answer
Real output:
4 5 5
1 4294967294
58 : 10
5 / 2 * 2 = 2 * 2 = 4; 5 * 2 / 2 = 10 / 2 = 5; 5 / 2.0 * 2 = 2.5 * 2 = 5. a + b converts -5 to unsigned: 3 - 5 wraps to 4294967294, which is > 0. '9' + 1 = 58, the code of ':'; '9' - '0' + 1 = 10.
3. Is int x = i++ + ++i; 12, 11, or 13?
Answer
None is guaranteed: it is undefined behaviour (two unsequenced modifications of i). g++ printed 12 with a -Wsequence-point warning.
4. How many times does static int n = f(); call f if the function containing it is called 100 times?
Answer
Once: a static local is initialised the first time control reaches its declaration.
Interview questions
- What is integer division? Dividing two integers gives an integer; the fraction is discarded (truncated toward zero since C++11).
- How do you get a decimal average from ints? Convert one operand first:
static_cast<double>(sum) / n, orsum / 3.0. - Why is
static_castpreferred over a C-style cast? It does only safe, well-defined conversions, the compiler checks it, and it is easy to search for. - What does
-7 % 3give?-1: the remainder has the sign of the left operand. - What type does
vector::size()return?size_type, normallysize_t: an unsigned integer. - Why does
v.size() - 1crash for an empty vector? Unsigned subtraction wraps:0 - 1is the largestsize_t, so the loop runs past the end. - What happens when you compare an
intwith anunsigned? Theintis converted to unsigned (usual arithmetic conversions); negative values become huge. g++ warns with-Wsign-compare. - What is ASCII? A standard table mapping characters to numbers:
'0'= 48,'A'= 65,'a'= 97. - How do you convert a digit char to its value?
c - '0'. - What is integral promotion? Before arithmetic,
char,shortandboolare converted toint, so'A' + 1is anint. - What is undefined behaviour? Code the C++ standard gives no meaning to; the compiler may do anything, and the result can change between compilers or flags.
- Is
i++ + ++idefined? No: two unsequenced modifications of the same variable. - Pre-increment vs post-increment?
++iadds then returns the new value;i++returns the old value then adds. For iterators,++itcan be cheaper. - What is a static local variable? A local variable with static storage duration: created once, it keeps its value between calls.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Integer division | int / int gives an int; the fraction is dropped |
217 / 3 → 72 |
| Truncation toward zero | Integer division cuts off the fraction, both signs | -7 / 2 → -3 |
Modulo % |
The remainder of integer division; sign of the left operand | -7 % 2 → -1 |
double |
A floating-point type for numbers with decimals | 72.3333 |
| Cast | An explicit type conversion | (double)x |
static_cast |
The C++ cast for safe, checked conversions | static_cast<double>(total) |
| Double literal | A number written with a decimal point | 3.0 |
| Usual arithmetic conversions | Rules that bring both operands to a common type | int / double → double |
| Signed | A type that can hold negative values | int |
| Unsigned | A type with no negative values | unsigned int, size_t |
size_t |
The unsigned type for sizes and indexes | v.size() |
| Wrap-around | Unsigned arithmetic goes round modulo 2^n | 0 - 1 → 18446744073709551615 |
-Wsign-compare |
The warning for comparing signed with unsigned | i < v.size() - 1 |
| Segmentation fault | The OS stops a program that touched memory it doesn't own | the empty-vector loop |
char |
A small integer holding a character's code | 'C' = 67 |
| ASCII | The table mapping characters to numbers | '0' = 48, 'A' = 65 |
| Integral promotion | char becomes int before arithmetic |
'C' + 1 → 68 |
d - '0' |
Converts a digit character to its value | '7' - '0' → 7 |
Post-increment i++ |
Use the old value, then add 1 | a = i++; |
Pre-increment ++i |
Add 1, then use the new value | b = ++i; |
| Unsequenced | The language doesn't fix which part runs first | the two sides of + |
| Undefined behaviour | Code with no meaning in the standard: any result | i++ + ++i |
-Wsequence-point |
g++'s warning for unsequenced changes | operation on 'i' may be undefined |
| Automatic storage | A local made on each call and destroyed on return | int token = 0; |
| Static local variable | A local made once, kept between calls | static int token = 0; |
| OTP | One-time password, often stored as a string of digits | "4071" |
Summary
int / intis anint: cast one operand todoublebefore dividing (static_cast<double>(total) / 3, or/ 3.0). Integer division truncates toward zero;%keeps the left operand's sign.size()is unsigned:size() - 1on an empty container wraps to a huge number. Count up from 1 (for (size_t i = 1; i < v.size(); i++)), checkempty(), and read-Wsign-comparewarnings.- A
charis a number (its ASCII code):d - '0'gives a digit's value;'C' + 1is theint68 until you store it in achar. i++ + ++iis undefined behaviour; change a variable once per statement.- A
staticlocal is created once and remembers its value between calls.
Next episode: dynamic programming questions: climbing stairs (recursion vs memo vs table), minimum coins (coin change), and the longest common subsequence.