UNIVERSITY OF AGRICULTURE, FAISALABAD
Department of Computer Science
LECTURE 12 · STUDENT NOTES
Repetitive Statements II: do-while & Input Validation
CS-307 Programming Fundamentals · BSCS Semester 1
Week | Slides | Linked practical | Reference ID |
5 | Lecture12_Do_While_Input_Validation.pptx | Practical 8 | N12 |
Learning Outcomes
SLO | By the end of this lecture you can… | Builds CLO | Bloom level |
|---|---|---|---|
SLO 12.1 | Explain the difference between a pre-test (while) and a post-test (do-while) loop | CLO4: Describe the syntax and semantics of the C++ programming language. | C2 |
SLO 12.2 | Use do-while to validate input and to repeat a menu until the user exits | CLO4: Describe the syntax and semantics of the C++ programming language. | C3 |
SLO 12.3 | Write sentinel-controlled loops that stop when a special value is entered | CLO1: Identify the necessary properties of good problem-solving techniques. | 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. Some Things Must Happen At Least Once
A while loop (Lecture 11) checks first and may run zero times. Sometimes an action must happen at least once before we can decide whether to repeat it: an ATM asks for the PIN, a form asks for your age, a game shows its menu. (Slide L12-S05)
2. The do-while Loop
2.1 Syntax and flowchart
A do-while loop runs its body first and checks the condition afterwards. If the condition is true it goes back and runs the body again. (Slide L12-S06)
Syntax do { // body: runs at least once } while (condition); // ; needed! // continues here when false |
Figure 12.1 – Flowchart of a do-while loop: the body comes before the decision
Remember the semicolon A do-while must end with ; after while (condition). A while loop must not have one (Lecture 11, trap 2). |
2.2 while vs do-while
Both loops below have a false condition from the start. (Slide L12-S07)
compare.cpp #include <iostream> using namespace std;
int main() { int n = 10;
while (n < 5) { cout << "while body ran" << endl; }
do { cout << "do-while body ran" << endl; } while (n < 5);
cout << "End" << endl; return 0; } |
Output do-while body ran End |
while (pre-test) | do-while (post-test) | |
|---|---|---|
Condition checked | before the body | after the body |
Minimum number of runs | 0 | 1 |
; after while ( ) | never | required |
Best for | loops that may run 0 times | asking for input, menus |
Pre-test means the check comes before the body; post-test means it comes after.
3. Input Validation and Menus
3.1 Validating input
Validation means checking that input is acceptable before using it. With do-while we ask, check, and ask again while the input is invalid. (Slide L12-S08)
validate.cpp #include <iostream> using namespace std;
int main() { 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; return 0; } |
Output Enter marks (0-100): 120 Invalid! Try again. Enter marks (0-100): -5 Invalid! Try again. Enter marks (0-100): 78 Marks accepted: 78 |
The loop condition is the invalid case: marks < 0 || marks > 100.
3.2 Never trust input
(Slide L12-S09)
Program | Bad input | What happens | Validation |
|---|---|---|---|
savings.cpp (L11) | 0 per month | infinite loop | do … while (perMonth <= 0); |
average of n numbers | n = 0 | division by zero | do … while (n <= 0); |
grade ladder (L9) | 150 | Grade A for impossible marks | do … while (m < 0 || m > 100); |
ATM | -500 | balance goes up! | do … while (amount <= 0); |
Programmer's rule Check input as soon as it is read, before any calculation uses it. |
3.3 Menus with do-while and switch
A menu must be shown at least once, so do-while fits. Inside it, a switch (Lecture 10) does the chosen action. The loop repeats until the user chooses Exit. (Slide L12-S10)
menu.cpp #include <iostream> using namespace std;
int main() { 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); return 0; } |
Session (inputs 1, 2, 1, 7, 3) 1. Balance 2. Deposit 1000 3. Exit Choice: 1 Balance: Rs. 12000 1. Balance 2. Deposit 1000 3. Exit Choice: 2 Deposited. 1. Balance 2. Deposit 1000 3. Exit Choice: 1 Balance: Rs. 13000 1. Balance 2. Deposit 1000 3. Exit Choice: 7 Invalid choice 1. Balance 2. Deposit 1000 3. Exit Choice: 3 Goodbye! |
3.4 A loop with two reasons to stop: ATM PIN
(Slide L12-S11) The loop continues while the PIN is wrong and fewer than 3 attempts have been used. After the loop, an if tells which reason ended it.
pin.cpp #include <iostream> using namespace std;
int main() { 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; } return 0; } |
Session 1 Enter PIN: 1111 Enter PIN: 4321 Welcome! |
Session 2 Enter PIN: 1 Enter PIN: 2 Enter PIN: 3 Card blocked after 3 wrong attempts. |
By De Morgan's rule (Lecture 4) the loop stops when pin == CORRECT_PIN || attempts >= 3.
4. Sentinel-Controlled Loops
4.1 The pattern
A sentinel (guard) is a special value that is not real data and means "stop" — for example -1 for marks. Pattern: read the first value before the loop; inside the loop, use the value and then read the next one at the end of the body. (Slide L12-S12)
sentinel.cpp #include <iostream> using namespace std;
int main() { int marks, count = 0, total = 0; cout << "Enter marks (-1 to stop): "; cin >> marks;
while (marks != -1) { // -1 is the sentinel total = total + marks; count++; cin >> marks; }
if (count > 0) { cout << "Students: " << count << endl; cout << "Average : " << static_cast<double>(total) / count << endl; } else { cout << "No marks entered." << endl; } return 0; } |
Run 1 Enter marks (-1 to stop): 70 85 64 -1 Students: 3 Average : 73 |
Run 2 Enter marks (-1 to stop): -1 No marks entered. |
4.2 Three rules
(Slide L12-S13)
1. The sentinel must be a value that can never be real data (marks: -1; shop prices: 0).
2. Never add the sentinel to the total — that is why the next read is at the end of the body.
3. If the first value is already the sentinel, count is 0: check count > 0 before dividing.
What happens if rule 2 is broken:
bad_sentinel.cpp #include <iostream> using namespace std;
int main() { int marks, count = 0, total = 0; cout << "Enter marks (-1 to stop): "; do { cin >> marks; total = total + marks; // -1 is added too! count++; } while (marks != -1); cout << "Average : " << static_cast<double>(total) / count << endl; return 0; } |
Output — wrong (should be 73) Enter marks (-1 to stop): 70 85 64 -1 Average : 54.5 |
5. Common Mistakes
(Slide L12-S15)
Mistake | Code | Result |
|---|---|---|
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 (a number cannot be both, so the loop never repeats) |
Sentinel added to the total | do { cin >> m; total += m; count++; } while (m != -1); | average 54.5 instead of 73 |
bad_validate.cpp (input 120) #include <iostream> using namespace std;
int main() { int marks; do { cout << "Enter marks (0-100): "; cin >> marks; } while (marks < 0 && marks > 100); // && should be || cout << "Marks accepted: " << marks << endl; return 0; } |
Output — wrong Enter marks (0-100): 120 Marks accepted: 120 |
6. Word Bank (Key Terms)
Word | Simple meaning |
|---|---|
do-while loop | Runs the body first, then checks; always runs at least once |
Pre-test loop | Checks before the body (while, for) |
Post-test loop | Checks after the body (do-while) |
Validation | Checking that input is acceptable |
Menu-driven program | Repeats a list of choices until the user exits |
Sentinel | A special stop value that is not real data |
Sentinel-controlled loop | Repeats until the sentinel is read |
7. Self-Check Questions
1. Draw the flowchart of a do-while loop and compare it with a while loop.
2. How many times does a do-while body run if the condition is false from the start?
3. Write a do-while that asks for an age until it is between 1 and 120.
4. Why must the validation condition use || and not &&?
5. What is a sentinel? Why is the second cin placed at the end of the loop body?
6. Write a loop that reads prices until 0 and prints the number of items and the total.
Answers are in §2.1, §2.2 (once), §3.1, §5, §4.1–4.2 and the Lecture 12 teaching guide (250 120 80 0 → 3 items, Rs. 450). Homework is on Slide L12-S17.