1. Goals
Calculate a small bill with arithmetic operators.
Build conditions with comparisons and
boolvalues.Select a branch with
if/elseorswitch, while avoiding division by zero.
2. Prerequisites
You can create main.cpp, compile and run it, and declare an int variable.
You have used std::cout to print values; \n is a newline character.
The example represents Vietnamese dong amounts as integers and needs no keyboard input.
3. Explanation
Calculate and compare
+, -, *, and / mean addition, subtraction, multiplication, and division.
With two integer operands, 7 / 3 produces 2; the fractional part is discarded.
% gives the remainder: 7 % 3 produces 1. Never use a zero divisor with / or %.
Multiplication and division group before addition and subtraction: 2 + 3 * 4
equals 14. Use parentheses to change grouping or make the intended calculation
clear: (2 + 3) * 4 equals 20. Operator precedence determines how an expression
is grouped; it is not a general rule for the execution order of every operation.
==, !=, <, <=, >, and >= compare values and produce a bool:
true means the condition holds and false means it does not. age = 18 changes
the age; age == 18 asks whether it equals 18. To test a range, write
age >= 12 && age < 18, rather than the mathematical notation 12 <= age < 18.
&& requires both conditions to hold; || requires at least one to hold;
! reverses true and false. For example, !isStudent means not a student.
For the basic values used here, && skips its right operand when the left is false,
and || skips its right operand when the left is true. This is short-circuit evaluation.
That is why the example checks ticketCount > 0 before evaluating the division.
The && rule is described in the C++ working draft.
Select a branch
An if / else if / else chain runs the first branch whose condition holds;
else handles the remaining cases. Use {} to group the statements in a branch.
The example gives children under 12 a 50% discount first. Otherwise,
students or people aged 65 and over receive 20%. The discounts do not stack.
switch is useful for comparing an integer value against a few specific choices.
case 1: and case 2: are choice labels; default: handles other values.
break; exits the switch. Without it, execution can continue into statements
under a later label, even when that label does not match.
Use if for an age range and switch for a payment method code.
4. Runnable example
Save this complete program as main.cpp. Prices and quantities are small, fixed
values so that you can concentrate on selecting branches. Payment codes 1 and 2
are recognized; default makes an unexpected code visible.
#include <iostream>
int main() {
int ticketCount = 3;
int ticketPrice = 120000;
int age = 16;
bool isStudent = true;
int paymentMethod = 2;
int subtotal = ticketCount * ticketPrice;
int discountPercent = 0;
if (age < 12) {
discountPercent = 50;
} else if (isStudent || age >= 65) {
discountPercent = 20;
} else {
discountPercent = 0;
}
int total = subtotal - (subtotal * discountPercent / 100);
std::cout << "Subtotal: " << subtotal << '\n';
std::cout << "Discount: " << discountPercent << "%\n";
std::cout << "Total: " << total << '\n';
if (ticketCount > 0 && total / ticketCount <= 100000) {
std::cout << "Within budget per ticket\n";
}
switch (paymentMethod) {
case 1:
std::cout << "Payment: cash\n";
break;
case 2:
std::cout << "Payment: card\n";
break;
default:
std::cout << "Payment: unknown\n";
break;
}
return 0;
}Compile with g++ -std=c++17 -Wall -Wextra -pedantic main.cpp -o lesson.
Run ./lesson on Linux/macOS or .\lesson.exe in Windows PowerShell.
Output:
Subtotal: 360000
Discount: 20%
Total: 288000
Within budget per ticket
Payment: cardEach discounted ticket costs 288000 / 3 = 96000, within the 100000 budget.
These particular values produce a whole-dong discount. Other values can lose
a fractional part during integer division; real billing needs an explicit rounding policy.
5. Common mistakes
Writing
if (age = 18): assignment changes the variable. Use==to compare.Writing
if (age < 12);: the semicolon ends an empty body, so the following block may run unconditionally.Reversing the guard to
total / ticketCount <= 100000 && ticketCount > 0: the division is evaluated first, so the later check cannot protect it.Using two independent
ifstatements for the discounts: the later one may overwrite the earlier discount.Choosing huge values whose product exceeds the range of
int. In this lesson, try ticket counts from 0 to 10 with the given price; input-based programs need bounds checks.
6. Practice
Change the age to 10 and keep
isStudent = true. Confirm a 50% discount and a total of180000. Explain why another 20% is not deducted.Set the age to 30 and student status to false. Predict the total of
360000and why the budget message disappears. Then try age 65.Change the ticket count to 0 and the payment code to 9. Check that the total is zero, no division by zero occurs, and the program prints
Payment: unknown.
7. Self-check
What are the results of
10 / 4and10 % 4? Answer:2and2, respectively: the integer quotient and the remainder.Which branch runs for a 10-year-old student in the example? Answer: Only
age < 12, giving 50% off; the followingelse ifis not evaluated.Why is the budget condition safe when
ticketCount = 0? Answer: The left operand of&&is false, so its right operand, containing the division, is not evaluated.
Sample code
Source file
cpp98_foundation/03_operators_conditions/main.cpp
#include <iostream>
int main() {
int ticketCount = 3;
int ticketPrice = 120000;
int age = 16;
bool isStudent = true;
int paymentMethod = 2;
int subtotal = ticketCount * ticketPrice;
int discountPercent = 0;
if (age < 12) {
discountPercent = 50;
} else if (isStudent || age >= 65) {
discountPercent = 20;
} else {
discountPercent = 0;
}
int total = subtotal - (subtotal * discountPercent / 100);
std::cout << "Subtotal: " << subtotal << '\n';
std::cout << "Discount: " << discountPercent << "%\n";
std::cout << "Total: " << total << '\n';
if (ticketCount > 0 && total / ticketCount <= 100000) {
std::cout << "Within budget per ticket\n";
}
switch (paymentMethod) {
case 1:
std::cout << "Payment: cash\n";
break;
case 2:
std::cout << "Payment: card\n";
break;
default:
std::cout << "Payment: unknown\n";
break;
}
return 0;
}