Slide 2
Quick Recap of Lecture 11
5 minutes · homework check
Homework 3
Remember
- int n, rev = 0;
- cin >> n;
- while (n > 0) {
- rev = rev * 10 + n % 10;
- n = n / 10;
- }
- cout << "Reversed: " << rev; // 4072 → 2704
- while checks FIRST — may run 0 times
- Start · condition · update
- Accumulator starts at 0
- Infinite loop: condition never false
- Ctrl + C stops a hung program
- Today's question
- savings.cpp looped for ever when the user typed 0. How can a program refuse bad input and ask again?
Recap
Programming Fundamentals · Lecture 12
Slide 3
Today's Plan
50 minutes · 8 parts
Recap & homework check
5 min
Learning outcomes & 'ask at least once'
3 min
The do-while loop
10 min
Input validation & menus
12 min
Sentinel-controlled loops
9 min
Class activity
7 min
Mistakes & recap quiz
3 min
Homework & next lecture
1 min
Programming Fundamentals · Lecture 12
Slide 4
Learning Outcomes (SLOs)
By the end of this lecture, you will be able to: (tag = course outcome it builds · Bloom level)
Explain the difference between a pre-test (while) and a post-test (do-while) loop
SLO 12.1 → CLO4 · C2
Use do-while to validate input and to repeat a menu until the user exits
SLO 12.2 → CLO4 · C3
SLO 12.3 → CLO1 · C3
Write sentinel-controlled loops that stop when a special value is entered
- CLO1 Identify the necessary properties of good problem-solving techniques.
- CLO4 Describe the syntax and semantics of the C++ programming language.
Programming Fundamentals · Lecture 12
Slide 5
Some Things Must Happen At Least Once
Do first, then decide whether to do it again
ATM
Waiter
Ask for the PIN — then check it. Wrong? ask again.
Take an order — then ask 'anything else?'
Form
Game menu
Ask for your age — then check it is 1 to 120.
Show the menu — then repeat until 'Exit'.
while: check → do. do-while: do → check. The body always runs at least once.
Module 1 · The do-while Loop
Programming Fundamentals · Lecture 12
Slide 6
The do-while Loop
Body first, condition at the bottom
before the loop
Syntax
- do {
- // body: runs at least once
- } while (condition); // ; needed!
- // continues here when false
body
condition?
true
- Pre-test vs post-test
- while = pre-test: checks before the body (0 or more runs).
- do-while = post-test: checks after the body (1 or more runs).
false
after the loop
Module 1 · The do-while Loop
Programming Fundamentals · Lecture 12
Slide 7
while vs do-while: When the Condition Starts False
Real output — n is 10, the condition is n < 5
compare.cpp
- int n = 10;
- while (n < 5) {
- cout << "while body ran" << endl;
- }
- do {
- cout << "do-while body ran" << endl;
- } while (n < 5);
- cout << "End" << endl;
Output
Rule: if the body must run at least once → do-while.
- do-while body ran
- End
Module 1 · The do-while Loop
Programming Fundamentals · Lecture 12
Slide 8
Input Validation with do-while
Ask, check, and ask again until the input is acceptable
validate.cpp
Output
- int marks;
- do {
- cout << "Enter marks (0-100): ";
- cin >> marks;
- if (marks < 0 || marks > 100) {
- cout << "Invalid! Try again." << endl;
- }
- } while (marks < 0 || marks > 100);
- cout << "Marks accepted: " << marks << endl;
- Enter marks (0-100): 120
- Invalid! Try again.
- Enter marks (0-100): -5
- Invalid! Try again.
- Enter marks (0-100): 78
- Marks accepted: 78
Loop condition = the INVALID case.
Real-world: an online admission form will not let you continue until the CNIC has 13 digits.
Module 2 · Input Validation & Menus
Programming Fundamentals · Lecture 12
Slide 9
Never Trust Input
What goes wrong when input is not checked
- Programmer's rule
- Check input as soon as it is read, before any calculation uses it.
Module 2 · Input Validation & Menus
Programming Fundamentals · Lecture 12
Slide 10
Menus with do-while + switch
Show the menu, do the choice, repeat until Exit
menu.cpp
Session (menu lines not shown)
- int balance = 12000, choice;
- do {
- cout << "1. Balance 2. Deposit 1000 3. Exit" << endl;
- cout << "Choice: ";
- cin >> choice;
- switch (choice) {
- case 1: cout << "Balance: Rs. " << balance << endl; break;
- case 2: balance += 1000; cout << "Deposited." << endl; break;
- case 3: cout << "Goodbye!" << endl; break;
- default: cout << "Invalid choice" << endl;
- }
- } while (choice != 3);
- Choice: 1
- Balance: Rs. 12000
- Choice: 2
- Deposited.
- Choice: 1
- Balance: Rs. 13000
- Choice: 7
- Invalid choice
- Choice: 3
- Goodbye!
The loop condition is 'not Exit': while (choice != 3).
Module 2 · Input Validation & Menus
Programming Fundamentals · Lecture 12
Slide 11
Example: ATM PIN with Three Tries
A loop that stops for one of TWO reasons
pin.cpp
Session 1
- const int CORRECT_PIN = 4321;
- int pin, attempts = 0;
- do {
- cout << "Enter PIN: ";
- cin >> pin;
- attempts++;
- } while (pin != CORRECT_PIN && attempts < 3);
- if (pin == CORRECT_PIN) {
- cout << "Welcome!" << endl;
- } else {
- cout << "Card blocked after 3 wrong attempts." << endl;
- }
- Enter PIN: 1111
- Enter PIN: 4321
- Welcome!
Session 2
- Enter PIN: 1
- Enter PIN: 2
- Enter PIN: 3
- Card blocked after 3 wrong attempts.
De Morgan (Lecture 4): the loop stops when pin == CORRECT_PIN || attempts >= 3.
Module 2 · Input Validation & Menus
Programming Fundamentals · Lecture 12
Slide 12
Sentinel-Controlled Loops
Keep reading until a special 'stop' value appears
sentinel.cpp
Run 1
- int marks, count = 0, total = 0;
- cout << "Enter marks (-1 to stop): ";
- cin >> marks; // first read
- while (marks != -1) { // -1 is the sentinel
- total = total + marks;
- count++;
- cin >> marks; // next read
- }
- if (count > 0) {
- cout << "Students: " << count << endl;
- cout << "Average : " << static_cast<double>(total) / count << endl;
- } else {
- cout << "No marks entered." << endl;
- }
- Enter marks (-1 to stop): 70 85 64 -1
- Students: 3
- Average : 73
Run 2
- Enter marks (-1 to stop): -1
- No marks entered.
- Real-world
- A cashier keeps scanning items until the customer says 'that's all'.
Module 3 · Sentinel-Controlled Loops
Programming Fundamentals · Lecture 12
Slide 13
Choosing and Using a Sentinel
Three rules
1 Impossible as data
marks: -1 · prices: 0 · names: "end"
2 Read at the end
use the value, then read the next one — the sentinel is never processed
3 Guard the average
if (count > 0) before dividing by count
Counter, condition or sentinel? — a sentinel loop is a kind of condition-controlled loop.
Module 3 · Sentinel-Controlled Loops
Programming Fundamentals · Lecture 12
Slide 14
CLASS ACTIVITY · 7 MIN · IN PAIRS
Validate, Sentinel, Choose
Write code for 1 and 2; answer 3.
Tasks
Check yourself
- 1. Ask for an age until it is between 1 and 120 (do-while).
- 2. A shop bill: read prices until 0 is entered; print the number of items and the total. Test: 250 120 80 0.
- 3. Which loop? (a) print 1 to 50 (b) a menu (c) read marks until -1
- What is your loop condition — the valid or the invalid case?
- Where is the second cin in task 2?
Slide 15
Common Mistakes
Real results
Missing ; after do-while
} while (i <= 3)
error: expected ';' before 'cout'
✗
&& instead of || in validation
} while (marks < 0 && marks > 100);
input 120 → Marks accepted: 120
✗
Sentinel added to the total
do { cin >> m; total += m; count++; } while (m != -1);
70 85 64 -1 → Average : 54.5 (should be 73)
✗
Programming Fundamentals · Lecture 12
Slide 16
Quick Recap
Answer aloud
Q1
How many times does a do-while body run if the condition is false?
Q2
Why is do-while a good choice for input validation?
Q3
What is a sentinel value? Give one for a list of prices.
Q4
Why must while (marks < 0 || marks > 100) use || and not &&?
Programming Fundamentals · Lecture 12
Slide 17
Homework
Fix savings.cpp from Lecture 11 so the monthly saving is asked again until it is more than 0.
Read the daily temperatures of a week until 999 is entered; print the highest, lowest and average.
Menu: 1 add to cart (input a price), 2 show total, 3 checkout and exit. Use do-while + switch.
Write while (x != 5 && tries < 3) as the condition for stopping (use De Morgan).
Next lecture: the for loop — counting loops made neat