These are the notes for C++ episode 5. Until now every program ran every line, top to bottom, no matter what. Here your program learns to decide: run some code only when something is true, and other code when it isn't. You will learn if, else, the three silent bugs that fool almost every beginner (= instead of ==, a semicolon after if (...), missing braces), else if ladders and why their order matters, combining conditions with && and ||, nested if, catching bad input with if (cin.fail()), the ternary operator ?:, and switch with case, break and default, including fall-through and why switch can't take a string. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run with the input shown, using printf '<input>' | ./main.
Piped input is not echoed. When input comes from a pipe (or the SyntaxPilot input box), what you "typed" does not appear in the output. In a real terminal you would see it next to the cursor.
The problem: the free-chai offer
Raju runs a chai stall near the college. New offer: if your bill is over ₹200, the chai is free. Aman adds the offer to Raju's billing program like this:
#include <iostream>
#include <string>
using namespace std;
int main() {
int bill;
cin >> bill;
cout << "Bill: " << bill << endl;
cout << "Free chai!" << endl;
return 0;
}
Input 120. Output:
Bill: 120
Free chai!
Wrong: a ₹120 bill gets free chai, and so does every other bill. Why? Every program so far runs every line, top to bottom. There is no way to say "only sometimes". The program needs to make a decision.
The fix: if
Raju asks himself one question: is the bill over ₹200? The answer is yes or no.
| At the chai stall | In C++ |
|---|---|
| "Is the bill over ₹200?" (yes / no) | the condition (bill > 200), which is true or false |
| Yes: hand over a free chai, only then | if (bill > 200) { ... }: the block runs only if the condition is true |
| Either way: "Thank you!" | the next line after the if: always runs |
#include <iostream>
#include <string>
using namespace std;
int main() {
int bill;
cin >> bill;
if (bill > 200) {
cout << "Free chai!" << endl;
}
cout << "Thank you, visit again" << endl;
return 0;
}
| Input | Output |
|---|---|
250 |
Free chai! then Thank you, visit again |
120 |
Thank you, visit again |
With 120 the condition 120 > 200 is false, so the program jumps straight over the block. Same code, two different paths: your program made its first decision.
- A condition is any expression that gives
trueorfalse: a comparison (bill > 200,age == 18), aboolvariable, or several joined with&&/||. - A block is the code between
{and}. Everything inside belongs to theif. - In C++, any number that isn't 0 also counts as
true, and 0 counts asfalse. Remember that: it causes bug 1 below.
The other path: else
The ₹120 customer gets nothing: no chai and no message. She wants to know how much more to spend. Now there are two paths, exactly one of which runs. The second path is called else.
#include <iostream>
#include <string>
using namespace std;
int main() {
int bill;
cin >> bill;
if (bill > 200) {
cout << "Free chai!" << endl;
} else {
cout << "Add Rs " << 201 - bill << " more" << endl;
}
return 0;
}
| Input | Output | Which block ran |
|---|---|---|
120 |
Add Rs 81 more |
else |
250 |
Free chai! |
if |
200 |
Add Rs 1 more |
else: 200 is not greater than 200 |
Test the edge value, the number exactly on the line. "Over 200" is bill > 200; "200 or more" would be bill >= 200.
The shape:
if (condition) {
// runs when condition is true
} else {
// runs when condition is false
}
- Exactly one of the two blocks runs, every time.
elseis optional, and it never has its own condition.
Three silent bugs (no error, wrong answer)
Bug 1: = instead of ==
| At the stall | In C++ |
|---|---|
| Write ₹500 on the bill: the bill changes | bill = 500: assignment, puts 500 into bill |
| Ask "is the bill ₹500?": the bill stays the same | bill == 500: comparison, gives true or false |
#include <iostream>
#include <string>
using namespace std;
int main() {
int bill;
cin >> bill;
if (bill = 500) {
cout << "Free chai!" << endl;
}
cout << "Bill: " << bill << endl;
return 0;
}
Input 120. Output:
Free chai!
Bill: 500
The single = wrote 500 into bill, and the value of the assignment (500) is not 0, so it counts as true. The customer's bill was silently changed. No error with the stage's command; with warnings on (-Wall), g++ says warning: suggest parentheses around assignment used as truth value [-Wparentheses].
Bug 2: a semicolon after if (...)
if (bill > 200);
{
cout << "Free chai!" << endl;
}
Input 120 prints Free chai!. The ; is an empty statement: it is the whole body of the if. The block below is just an ordinary block that always runs. With -Wall -Wextra: warning: suggest braces around empty body in an 'if' statement [-Wempty-body].
Bug 3: no braces, two lines
if (bill > 200)
cout << "Free chai!" << endl;
cout << "Free samosa too!" << endl;
| Input | Output |
|---|---|
120 |
Free samosa too! |
250 |
Free chai! then Free samosa too! |
Without braces, if controls only the next statement. The indentation lies: C++ ignores spaces. With -Wall: warning: this 'if' clause does not guard... [-Wmisleading-indentation]. Always use braces.
Many paths: else if
The metro fare depends on age: under 5 free, under 18 ₹10 (youth), under 60 ₹30, 60 and over ₹15 (senior). The obvious attempt is four separate ifs:
int age;
cin >> age;
if (age < 5) cout << "Ticket: free" << endl;
if (age < 18) cout << "Ticket: Rs 10 (youth)" << endl;
if (age < 60) cout << "Ticket: Rs 30" << endl;
if (age >= 60) cout << "Ticket: Rs 15 (senior)" << endl;
Input 3. Output: three tickets.
Ticket: free
Ticket: Rs 10 (youth)
Ticket: Rs 30
3 is under 5, but also under 18 and under 60. Each if is checked on its own. We need "stop at the first rule that matches": an else if ladder.
#include <iostream>
#include <string>
using namespace std;
int main() {
int age;
cin >> age;
if (age < 5) {
cout << "Ticket: free" << endl;
} else if (age < 18) {
cout << "Ticket: Rs 10 (youth)" << endl;
} else if (age < 60) {
cout << "Ticket: Rs 30" << endl;
} else {
cout << "Ticket: Rs 15 (senior)" << endl;
}
return 0;
}
| Input | Output |
|---|---|
3 |
Ticket: free |
12 |
Ticket: Rs 10 (youth) |
35 |
Ticket: Rs 30 |
70 |
Ticket: Rs 15 (senior) |
C++ checks the conditions from the top, runs the first block whose condition is true, and skips all the rest. The final else catches everything else.
Order matters: the mango sorter
A mango-sorting tray has holes from small to big. Each mango drops through the first hole it fits and never reaches the others; mangoes too big for every hole land in the basket at the end (else). Put the biggest hole first and every mango drops into it:
if (age < 60) {
cout << "Ticket: Rs 30" << endl;
} else if (age < 18) {
cout << "Ticket: Rs 10 (youth)" << endl;
} else if (age < 5) {
cout << "Ticket: free" << endl;
} else {
cout << "Ticket: Rs 15 (senior)" << endl;
}
Input 3 prints Ticket: Rs 30 (and so does 12). The youth and free branches can never run. Put the narrowest condition first.
Combining conditions: &&, || and nested if
Weekend offer: 10% off on Saturday (day 6) or Sunday (day 7), but only if the bill is over ₹100.
#include <iostream>
#include <string>
using namespace std;
int main() {
int day, bill;
cin >> day >> bill;
if ((day == 6 || day == 7) && bill > 100) {
cout << "Weekend offer: 10% off" << endl;
} else {
cout << "No offer today" << endl;
}
return 0;
}
| Input | Output | Why |
|---|---|---|
6 250 |
Weekend offer: 10% off |
both parts true |
7 80 |
No offer today |
the bill part is false; && needs both |
3 250 |
No offer today |
the day part is false |
The brackets around the || part matter: && is evaluated before || (like × before +), so without them day == 6 || day == 7 && bill > 100 would give the offer to every Saturday bill.
A nested if is an if inside another if's block: a second question asked only after the first says yes. The metro's student fare is only for adults:
int age;
bool student;
cin >> age >> student;
if (age >= 18) {
if (student) {
cout << "Rs 20 (student)" << endl;
} else {
cout << "Rs 30" << endl;
}
} else {
cout << "Rs 10 (youth)" << endl;
}
| Input | Output |
|---|---|
20 1 |
Rs 20 (student) |
20 0 |
Rs 30 |
15 1 |
Rs 10 (youth) (the inner question is never asked) |
(cin >> student reads 1 as true and 0 as false.) Keep nesting shallow: more than two levels gets hard to read; an else if ladder or && is often clearer.
Catching bad input: if (cin.fail())
In episode 4 a friend typed abc for the bill: cin put 0 in the box and raised its fail flag. Now you can check the flag:
#include <iostream>
#include <string>
using namespace std;
int main() {
int bill;
cin >> bill;
if (cin.fail()) {
cout << "Please type a number." << endl;
return 1;
}
cout << "Each of 4 pays: " << bill / 4.0 << endl;
return 0;
}
| Input | Output | Exit code |
|---|---|---|
abc |
Please type a number. |
1 |
480 |
Each of 4 pays: 120 |
0 |
return 1; inside main ends the program immediately. The number is the exit code: 0 means "finished fine", anything else means "something went wrong" (scripts and other programs can read it). Checking input before using it is called input validation.
One-line choice: the ternary operator ?:
When the decision just picks one of two values, use condition ? valueIfTrue : valueIfFalse:
int bill;
cin >> bill;
string msg = (bill > 200) ? "Free chai!" : "No chai";
cout << msg << endl;
Input 250 prints Free chai!; input 90 prints No chai. Read it as "is the bill over 200? if yes this, else that". It's called ternary because it takes three parts. Use it only for picking a value; for anything bigger, use if / else.
Menus: switch
The canteen menu: 1 dosa, 2 idli, 3 vada, 4 chai. With else if that's choice == 1, choice == 2, choice == 3... the same question again and again. Like a lift, where you press 3 and it goes straight to floor 3, switch jumps straight to the matching option:
#include <iostream>
#include <string>
using namespace std;
int main() {
int choice;
cin >> choice;
switch (choice) {
case 1: cout << "Masala dosa: Rs 60" << endl; break;
case 2: cout << "Idli: Rs 40" << endl; break;
case 3: cout << "Vada: Rs 30" << endl; break;
case 4: cout << "Chai: Rs 15" << endl; break;
default: cout << "Not on the menu" << endl;
}
return 0;
}
| Input | Output |
|---|---|
2 |
Idli: Rs 40 |
9 |
Not on the menu |
switch (value)compares one value against fixed options.case 2:is one option (a label). The value aftercasemust be a constant: a number or a character literal.break;jumps out of the switch.default:runs when no case matches, like a finalelse. It's optional.
Forgetting break: fall-through
Delete every break and order an idli (input 2):
Idli: Rs 40
Vada: Rs 30
Chai: Rs 15
Not on the menu
switch jumped to case 2 and, with no break, kept running every line below it: this is fall-through, like a lift with broken brakes. With -Wextra, g++ warns: warning: this statement may fall through [-Wimplicit-fallthrough=].
Fall-through can be useful when several cases share one block:
char grade;
cin >> grade;
switch (grade) {
case 'A':
case 'B': cout << "Well done!" << endl; break;
case 'C': cout << "Passed" << endl; break;
default: cout << "Work harder" << endl;
}
| Input | Output |
|---|---|
A |
Well done! (falls into case 'B') |
B |
Well done! |
C |
Passed |
F |
Work harder |
When a case has code and you fall through on purpose, write a comment (or C++17's [[fallthrough]];) so readers know it isn't a forgotten break.
switch or else if?
Use switch when... |
Use else if when... |
|---|---|
| one value is compared against fixed options (menu numbers, letter grades) | you test ranges (age < 18) |
the value is an integer type: int, char, long, bool, an enum |
conditions use AND, OR or several variables |
| you only need equality | the value is a string or double |
switch on a string:
string item;
cin >> item;
switch (item) {
case "chai": cout << "Rs 15" << endl; break;
}
main.cpp: In function 'int main()':
main.cpp:8:13: error: switch quantity not an integer
8 | switch (item) {
| ^~~~
The value in switch's brackets (its "quantity") must be an integer type. For text, use if (item == "chai") ... else if ....
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
= instead of == |
if (bill = 500) |
no error; bill becomes 500 and the condition is true. With -Wall: suggest parentheses around assignment used as truth value |
if (bill == 500) |
; after if (...) |
if (bill > 200); { ... } |
no error; the block always runs | remove the ; |
| Missing braces | if (x) + two indented lines |
no error; only the first line is guarded | always use { } |
Missing braces before else |
if (x) a; b; else c; |
error: 'else' without a previous 'if' |
if (x) { a; b; } else { c; } |
| Wrong ladder order | if (age < 60) ... else if (age < 18) |
no error; the later branches never run | narrowest condition first |
a < x < b |
if (18 <= age <= 25) |
no error; always true (see episode 3) | if (age >= 18 && age <= 25) |
Forgotten break |
case 2: ...; with no break |
no error; runs every case below (fall-through) | break; after each case |
switch on a string |
switch (item) |
error: switch quantity not an integer |
use if / else if |
| Off-by-one at the edge | bill > 200 when you meant "200 or more" |
no error; 200 takes the else path | bill >= 200; test the edge value |
The else error, live:
int bill;
cin >> bill;
if (bill > 200)
cout << "Free chai!" << endl;
cout << "Free samosa too!" << endl;
else
cout << "No offer" << endl;
main.cpp: In function 'int main()':
main.cpp:11:5: error: 'else' without a previous 'if'
11 | else
| ^~~~
The if owned only the Free chai! line; the samosa line ended it, so the else has nothing to attach to. With braces (if (bill > 200) { ... } else { ... }), input 120 prints No offer.
Mini project: canteen order
Read an item number and a quantity. A switch sets the price (1 dosa ₹60, 2 idli ₹40, 3 chai ₹15). Validate everything, print the total, and give free chai over ₹200 with the ternary operator.
#include <iostream>
using namespace std;
int main() {
int item, qty, price = 0;
cin >> item >> qty;
switch (item) {
case 1: price = 60; break; // dosa
case 2: price = 40; break; // idli
case 3: price = 15; break; // chai
}
if (cin.fail() || price == 0 || qty <= 0) {
cout << "Invalid order" << endl;
return 1;
}
int total = price * qty;
cout << "Total: Rs " << total << endl;
cout << (total > 200 ? "Free chai!" : "No gift") << endl;
return 0;
}
| Input | Output |
|---|---|
1 4 |
Total: Rs 240 then Free chai! |
2 3 |
Total: Rs 120 then No gift |
9 1 |
Invalid order (no case matched, price stayed 0) |
1 abc |
Invalid order (cin.fail()) |
3 0 |
Invalid order (quantity not positive) |
Notice the trick: price starts at 0 and only a valid item changes it, so price == 0 means "not on the menu". Extend it: add vada as item 4 (₹30), and a weekend 10% discount.
Practice
- Read a number and print whether it is even or odd.
- Read marks (0–100) and print the grade: A (80+), B (60+), C (33+) or Fail. Reject marks outside 0–100.
- Read a year and print whether it is a leap year (divisible by 4 but not by 100, or divisible by 400).
- A calculator: read
a op b(for example7 / 2) and useswitchon the operator character. Don't divide by zero.
Solution
1. n % 2 is the remainder after dividing by 2. Input 7 prints 7 is odd; 10 prints 10 is even.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
if (n % 2 == 0) {
cout << n << " is even" << endl;
} else {
cout << n << " is odd" << endl;
}
return 0;
}
2. Validate first, then a ladder from the highest grade down. 85 → Grade A, 65 → Grade B, 40 → Grade C, 20 → Fail, 150 → Invalid marks.
#include <iostream>
using namespace std;
int main() {
int marks;
cin >> marks;
if (cin.fail() || marks < 0 || marks > 100) {
cout << "Invalid marks" << endl;
return 1;
}
if (marks >= 80) {
cout << "Grade A" << endl;
} else if (marks >= 60) {
cout << "Grade B" << endl;
} else if (marks >= 33) {
cout << "Grade C" << endl;
} else {
cout << "Fail" << endl;
}
return 0;
}
3. 2024 → 2024 is a leap year, 1900 → 1900 is not a leap year, 2000 → 2000 is a leap year, 2026 → 2026 is not a leap year.
#include <iostream>
using namespace std;
int main() {
int year;
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
cout << year << " is a leap year" << endl;
} else {
cout << year << " is not a leap year" << endl;
}
return 0;
}
4. cin >> a >> op >> b reads 7, then the character /, then 2. 7 / 2 → 3.5, 6 * 4 → 24, 5 / 0 → Cannot divide by zero, 3 x 4 → Unknown operator.
#include <iostream>
using namespace std;
int main() {
double a, b;
char op;
cin >> a >> op >> b;
switch (op) {
case '+': cout << a + b << endl; break;
case '-': cout << a - b << endl; break;
case '*': cout << a * b << endl; break;
case '/':
if (b == 0) {
cout << "Cannot divide by zero" << endl;
} else {
cout << a / b << endl;
}
break;
default: cout << "Unknown operator" << endl;
}
return 0;
}
Quick quiz
What does this print?
int x = 5;
if (x = 0)
cout << "A" << endl;
else
cout << "B" << endl;
- A.
A - B.
B - C.
AandB - D. Compile error
Answer
B. x = 0 is an assignment, not a comparison: it puts 0 into x, and the value 0 counts as false, so the else runs (verified). With x == 0 it would also print B, but for a different reason: 5 is not 0.
Interview questions
- What is the difference between
=and==?=assigns (stores a value and gives that value back);==compares and givestrue/false.if (x = 0)is legal C++ and always false;if (x = 5)is always true. - What does
if (x)mean whenxis anint? It's true whenxis non-zero and false when it is 0. Pointers,chars anddoubles convert the same way. - What is the difference between a chain of separate
ifs and anelse ifladder? Separateifs are each checked, so several can run; in a ladder at most one block runs, the first whose condition is true. - What is fall-through in a
switch? Withoutbreak, execution continues into the following cases' code. It's useful for sharing code between cases (case 'A': case 'B':), and C++17 adds[[fallthrough]];to mark it as intentional. - Which types can a
switchtake? Integral and enumeration types (int,char,long,bool,enum), or class types that convert to one. Notstringordouble;caselabels must be compile-time constants. - When would you choose
switchoverelse if? When one integral value is compared for equality against several constants: it reads better and the compiler can turn it into a jump table. - What does the ternary operator return? A value:
c ? a : bevaluatesc, then exactly one ofaorb. Both branches must have compatible types. - What does
return 1;inmaindo? Ends the program and reports exit code 1 to whoever started it; non-zero conventionally signals failure.
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Decision | Running some code only when something is true | free chai only over ₹200 |
| Condition | An expression that is true or false | bill > 200 |
bool |
The type with just two values, true and false |
bool student = true; |
if |
Runs a block only when its condition is true | if (bill > 200) { ... } |
| Block | The statements between { and }, treated as one unit |
{ cout << "Free chai!"; } |
else |
The block that runs when the if's condition is false |
} else { ... } |
| Edge value | The input exactly on the boundary of a condition | 200 for bill > 200 |
Assignment = |
Stores a value in a variable | bill = 500; |
Comparison == |
Asks whether two values are equal (true/false) | bill == 500 |
| Empty statement | A lone ; that does nothing |
if (x); |
| Silent bug | A mistake that compiles and runs but gives a wrong result | if (bill = 500) |
| Warning | A message from the compiler about suspicious code; the program is still built | -Wparentheses |
-Wall |
g++ option that turns on the common warnings | g++ -Wall main.cpp |
| Indentation | Spaces at the start of a line, for humans only; C++ ignores them | the lying samosa line |
else if ladder |
A chain of conditions where the first true one wins | metro fares |
Logical AND (&&) |
True only if both sides are true | day == 6 && bill > 100 |
| Logical OR (two bars) | True if at least one side is true | Saturday or Sunday: day 6 or day 7 |
| Precedence | Which operator is applied first | AND is applied before OR |
| Nested if | An if inside another if's block |
the student fare for adults |
cin.fail() |
True when the last read failed (e.g. letters for an int) |
input abc |
| Input validation | Checking input is sensible before using it | if (cin.fail()) { return 1; } |
return (in main) |
Ends the program immediately | return 1; |
| Exit code | The number a program reports when it ends: 0 fine, non-zero error | return 1; → 1 |
Ternary operator ?: |
Picks one of two values based on a condition | bill > 200 ? "Free chai!" : "No chai" |
switch |
Jumps to the case that matches one value | switch (choice) { ... } |
case |
One labelled option inside a switch |
case 2: |
break |
Jumps out of the switch |
case 1: ...; break; |
default |
The switch option used when no case matches |
default: cout << "Not on the menu"; |
| Fall-through | Running on into the next case because there was no break |
idli order prints four items |
| Integer type | A whole-number type: int, char, long, bool |
what switch needs |
char literal |
One character in single quotes | 'A', '+' |
Remainder % |
What's left after whole-number division | 7 % 2 is 1 |
| Compile error | A mistake g++ finds before the program runs; no program is produced | 'else' without a previous 'if' |
Summary
- Without decisions, every line always runs.
if (condition) { ... }runs a block only when the condition is true. elseis the other path: exactly one of the two blocks runs. Test the edge value.- Three silent bugs:
=instead of==; a;afterif (...); missing braces (only one line is guarded). Always use braces; turn on-Wallto catch them. - Separate
ifs can all run; in anelse ifladder the first match wins, so put the narrowest condition first. &&needs both,||needs one; put brackets around the||part. A nested if asks a second question inside the first.if (cin.fail()) { ...; return 1; }is input validation: check before you use.c ? a : bpicks one of two values.switchcompares one integer value against fixedcases;breakafter each case,defaultfor the rest. Nobreakmeans fall-through. Noswitchon strings:switch quantity not an integer.
Next episode: loops. Raju's hostel friend needs to print 100 meal coupons, and nobody wants to write 100 cout lines. Your program learns to repeat, with while, for and do-while.