UNIVERSITY OF AGRICULTURE, FAISALABAD
Department of Computer Science
LECTURE 10 · STUDENT NOTES
Conditional Statements III: switch & the Conditional Operator
CS-307 Programming Fundamentals · BSCS Semester 1
Week | Slides | Linked practical | Reference ID |
4 | Lecture10_Switch_Conditional_Operator.pptx | Practical 7 | N10 |
Learning Outcomes
SLO | By the end of this lecture you can… | Builds CLO | Bloom level |
|---|---|---|---|
SLO 10.1 | Write a switch statement with case, break and default | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 10.2 | Explain fall-through and decide when switch is better than an else-if ladder | CLO4: Describe the syntax and semantics of the C++ programming language. | C2 |
SLO 10.3 | Use the conditional operator ?: for simple two-way choices | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
How to use these notes Read these notes after the lecture and before the practical. Section numbers (for example §3.2) are used in the question bank, so you can always find where an answer comes from. Type every code example yourself — do not copy-paste. |
1. Choosing from a Menu
Many programs choose one action from a list of exact values: a bank helpline ("press 1 for Urdu"), an ATM menu, a calculator's operators, day numbers 1–7. A long else-if ladder of choice == 1, choice == 2 … works, but C++ has a neater statement for this: switch. (Slide L10-S05)
Key word: EXACT switch compares one value with exact constants (1, 2, '+'). Ranges such as marks >= 50 still need if / else-if (Lecture 9). |
2. The switch Statement
2.1 Syntax
(Slide L10-S06)
Syntax switch (expression) { case value1: // statements break; case value2: // statements break; default: // no case matched } |
Part | Meaning |
|---|---|
switch (x) | the value to check — must be a whole-number type (int, char …) |
case 1: | a label: jump here when x is 1 (note the colon) |
break; | leave the switch now |
default: | runs when no case matches (optional, like the final else) |
Real-world: a lift — press 5 and it goes straight to floor 5, without stopping to ask at every floor.
2.2 Example: day name from a number
(Slide L10-S07)
day.cpp #include <iostream> using namespace std;
int main() { int day; cout << "Enter day number (1-7): "; cin >> day;
switch (day) { case 1: cout << "Monday" << endl; break; case 2: cout << "Tuesday" << endl; break; case 3: cout << "Wednesday" << endl; break; case 4: cout << "Thursday" << endl; break; case 5: cout << "Friday" << endl; break; case 6: cout << "Saturday" << endl; break; case 7: cout << "Sunday" << endl; break; default: cout << "Invalid day" << endl; } return 0; } |
Input | 5 | 7 | 9 |
|---|---|---|---|
Output | Friday | Sunday | Invalid day |
2.3 How switch runs
(Slide L10-S08)
1. Work out the value in switch ( ).
2. Jump straight to the matching case label (cases are not tested one by one like a ladder).
3. Run the statements after that label.
4. On reaching break; leave the switch and continue after the closing brace.
5. No matching label → jump to default; if there is no default, nothing runs.
2.4 Example: a simple calculator
Case labels can be characters in single quotes, and a case can contain any statements — here an if-else stops division by zero. (Slide L10-S09)
calc.cpp #include <iostream> using namespace std;
int main() { double a, b; char op; cout << "Enter expression (e.g. 12 * 4): "; cin >> a >> op >> b;
switch (op) { case '+': cout << "Result: " << a + b << endl; break; case '-': cout << "Result: " << a - b << endl; break; case '*': cout << "Result: " << a * b << endl; break; case '/': if (b != 0) { cout << "Result: " << a / b << endl; } else { cout << "Cannot divide by zero" << endl; } break; default: cout << "Unknown operator " << op << endl; } return 0; } |
Input | Output |
|---|---|
12 * 4 | Result: 48 |
7 / 2 | Result: 3.5 |
9 / 0 | Cannot divide by zero |
5 % 2 | Unknown operator % |
10 - 13.5 | Result: -3.5 |
3. break, Fall-Through and the Limits of switch
3.1 Forgetting break: fall-through
Case labels are only entry points. Without break, the program keeps running into the following cases until it meets a break or the closing brace. This is called fall-through. (Slide L10-S10)
fallthrough.cpp #include <iostream> using namespace std;
int main() { int choice = 2; switch (choice) { case 1: cout << "Tea" << endl; case 2: cout << "Coffee" << endl; case 3: cout << "Juice" << endl; default: cout << "Water" << endl; } return 0; } |
Output — ordered coffee, got three drinks Coffee Juice Water |
g++ with -Wextra warns: this statement may fall through. Fix: end every case with break;.
3.2 Grouping cases on purpose
Empty case labels stacked together share one block — useful fall-through. (Slide L10-S11)
vowel.cpp #include <iostream> using namespace std;
int main() { char ch; cout << "Enter a small letter: "; cin >> ch;
switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u': cout << ch << " is a vowel" << endl; break; default: cout << ch << " is a consonant" << endl; } return 0; } |
Run 1 Enter a small letter: e e is a vowel |
Run 2 Enter a small letter: k k is a consonant |
Real-world: Saturday and Sunday are both "Weekend": case 6: case 7: cout << "Weekend"; break;
3.3 What switch cannot do
(Slide L10-S12)
Rule | Wrong code | g++ message |
|---|---|---|
The switch value must be a whole-number type or char | switch (city) // city is a string | error: switch quantity not an integer |
Each case label must be a constant, not a condition | case marks >= 50: | error: the value of 'marks' is not usable in a constant expression |
Trick for ranges in bands of 10: switch on marks / 10 (87 / 10 = 8). This works only when every limit is a multiple of 10.
grade_switch.cpp (A 80+, B 70s, C 60s, D 50s) #include <iostream> using namespace std;
int main() { int marks; cout << "Enter marks (0-100): "; cin >> marks;
switch (marks / 10) { // 87 / 10 = 8 case 10: case 9: case 8: cout << "Grade A" << endl; break; case 7: cout << "Grade B" << endl; break; case 6: cout << "Grade C" << endl; break; case 5: cout << "Grade D" << endl; break; default: cout << "Grade F" << endl; } return 0; } |
marks | 100 | 87 | 80 | 79 | 72 | 65 | 50 | 49 | 34 |
|---|---|---|---|---|---|---|---|---|---|
Output | A | A | A | B | B | C | D | F | F |
3.4 switch or else-if ladder?
(Slide L10-S13)
switch | else-if ladder | |
|---|---|---|
Compares | one value with exact constants | any conditions (ranges, &&, ||) |
Types | int, char (whole-number types) | any type, including double and string |
Best for | menus, codes, day numbers, operators | grades, slabs, eligibility rules |
Watch out for | missing break (fall-through) | order of conditions |
4. The Conditional Operator ?:
4.1 Syntax
The conditional operator (also called the ternary operator, because it has three parts) chooses one of two values: condition ? valueIfTrue : valueIfFalse. Unlike if-else, it produces a value, so it can be used inside an assignment or a cout. (Slide L10-S14)
ternary.cpp #include <iostream> using namespace std;
int main() { int a = 14, b = 9, n = 7; bool isStudent = true;
int larger = (a > b) ? a : b; cout << "Larger: " << larger << endl; cout << n << " is " << (n % 2 == 0 ? "even" : "odd") << endl; int ticket = isStudent ? 500 : 800; cout << "Ticket: Rs. " << ticket << endl; return 0; } |
Output Larger: 14 7 is odd Ticket: Rs. 500 |
int larger = (a > b) ? a : b; does the same as if (a > b) larger = a; else larger = b;. Put brackets around ?: inside cout, because << has higher precedence.
4.2 When to use it
(Slide L10-S15)
Need | Use |
|---|---|
choose between two VALUES | ?: |
run different STATEMENTS | if-else |
many ranges | else-if ladder |
many exact values of one int/char | switch |
Nested ?: such as m >= 85 ? 'A' : m >= 70 ? 'B' : … is legal (72 gives 'B') but hard to read — use a ladder instead.
5. Word Bank (Key Terms)
Word | Simple meaning |
|---|---|
switch | Chooses a block by matching one value with exact constants |
case label | A constant after case — an entry point |
break | Leaves the switch immediately |
default | Runs when no case matches |
Fall-through | Running on into the next case because there is no break |
Constant expression | A value fixed when the program is compiled |
Conditional / ternary operator | condition ? a : b — picks one of two values |
6. Self-Check Questions
1. Write a switch that prints the name of a month for 1–12 and "Invalid" otherwise.
2. What does break do? What happens without it?
3. Why can't you write case marks >= 50:?
4. Which statement would you use for (a) an ATM menu, (b) a temperature warning with decimal values, (c) choosing Rs. 500 or Rs. 800 for a ticket?
5. Rewrite with ?: if (age < 12) fare = 600; else fare = 1200;
6. What is printed by fallthrough.cpp if choice is 3?
Answers are in §2.1, §3.1, §3.3, §3.4 and §4.2, §4.1 (fare = (age < 12) ? 600 : 1200;), §3.1 (Juice and Water). Homework is on Slide L10-S18.