C++: Practice: Branching and Loops Comprehensive
Last updated: 2026-08-26
Previous lessons covered conditionals and loops separately, but in real programs they are used together.
In this lesson, we'll practice making branching and loops work together through several comprehensive examples.
1. Example 1: Number Guessing Game (Complete Version)
(1) 1.1 Requirements Analysis
We'll build a complete number guessing game:
- The program randomly generates a number from 1-100
- The user enters their guess
- If the guess is too high, prompt "Too high"
- If the guess is too low, prompt "Too low"
- If the guess is correct, congratulate the user and show how many attempts it took
- The user can choose to play again
▶ Example 1: Complete Number Guessing Game (Difficulty ⭐⭐)
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
std::srand(static_cast<unsigned int>(std::time(nullptr)));
char playAgain;
do {
int secretNumber = std::rand() % 100 + 1;
int guess;
int attempts = 0;
std::cout << "========== Number Guessing Game ==========\n";
std::cout << "I'm thinking of a number from 1-100, guess it!\n\n";
do {
std::cout << "Enter your guess: ";
std::cin >> guess;
attempts++;
if (guess > secretNumber) {
std::cout << "Too high! Try again.\n";
} else if (guess < secretNumber) {
std::cout << "Too low! Try again.\n";
} else {
std::cout << "\n🎉 Congratulations! You got it!\n";
std::cout << "You guessed " << attempts << " times.\n";
if (attempts <= 5) {
std::cout << "You're amazing!\n";
} else if (attempts <= 10) {
std::cout << "Not bad!\n";
} else {
std::cout << "Keep trying, aim for fewer attempts next time!\n";
}
}
} while (guess != secretNumber);
std::cout << "\nWant to play again? (y/n): ";
std::cin >> playAgain;
std::cout << std::endl;
} while (playAgain == 'y' || playAgain == 'Y');
std::cout << "Thanks for playing, goodbye!" << std::endl;
return 0;
}
Output:
========== Number Guessing Game ==========
I'm thinking of a number from 1-100, guess it!
Enter your guess:
Too high! Try again.
Too low! Try again.
🎉 Congratulations! You got it!
You guessed times.
You're amazing!
Not bad!
Keep trying, aim for fewer attempts next time!
Want to play again? (y/n):
Thanks for playing, goodbye!
Sample run:
========== Number Guessing Game ==========
I'm thinking of a number from 1-100, guess it!
Enter your guess: 50
Too high! Try again.
Enter your guess: 25
Too low! Try again.
Enter your guess: 37
Too high! Try again.
Enter your guess: 31
🎉 Congratulations! You got it!
You guessed 4 times.
You're amazing!
Want to play again? (y/n): n
Thanks for playing, goodbye!
Code analysis:
- Outer
do-while: Controls "play again" - Inner
do-while: Main guessing loop if-else if-else: Checks if guess is too high/too low/correct- Nested
if-else: Rates performance based on number of attempts
2. Example 2: Simple Address Book
(1) 2.1 Requirements Analysis
Build a simple address book program:
- Display a menu (add contact, show contacts, exit)
- User selects an operation
- Use a loop to allow continuous operations until the user chooses to exit
▶ Example 2: Simple Address Book (Difficulty ⭐⭐⭐)
#include <iostream>
#include <string>
int main() {
const int MAX_CONTACTS = 100;
std::string names[MAX_CONTACTS];
std::string phones[MAX_CONTACTS];
int count = 0;
int choice;
do {
// Display menu
std::cout << "========== Simple Address Book ==========\n";
std::cout << "1. Add contact\n";
std::cout << "2. Show all contacts\n";
std::cout << "3. Exit\n";
std::cout << "Choose (1-3): ";
std::cin >> choice;
if (choice == 1) {
// Add contact
if (count >= MAX_CONTACTS) {
std::cout << "Address book is full!" << std::endl;
} else {
std::cout << "Enter name: ";
std::cin.ignore(); // Discard newline
std::getline(std::cin, names[count]);
std::cout << "Enter phone: ";
std::getline(std::cin, phones[count]);
count++;
std::cout << "Added successfully!" << std::endl;
}
} else if (choice == 2) {
// Show contacts
if (count == 0) {
std::cout << "Address book is empty!" << std::endl;
} else {
std::cout << "\n========== Contact List ==========\n";
for (int i = 0; i < count; i++) {
std::cout << i + 1 << ". " << names[i] << " - " << phones[i] << std::endl;
}
std::cout << "================================\n\n";
}
} else if (choice == 3) {
std::cout << "Goodbye!" << std::endl;
} else {
std::cout << "Error: Please enter a number between 1-3!" << std::endl;
}
std::cout << std::endl;
} while (choice != 3);
return 0;
}
Output:
========== Simple Address Book ==========
1. Add contact
2. Show all contacts
3. Exit
Choose (1-3):
Address book is full!
Enter name:
Enter phone:
Added successfully!
Address book is empty!
========== Contact List ==========
. -
================================
Goodbye!
Error: Please enter a number between 1-3!
💡 Tip: This program uses arrays (covered in detail in lesson 09). You can copy it for now and understand the general approach.
3. Example 3: Simple Calculator (Extended Version)
(1) 3.1 Requirements Analysis
Build a calculator that supports multiple calculations:
- Display a menu (addition, subtraction, multiplication, division, exit)
- User selects an operation
- Enter two numbers, output the result
- Use a loop to allow continuous calculations
▶ Example 3: Extended Calculator (Difficulty ⭐⭐)
#include <iostream>
#include <iomanip>
int main() {
int choice;
do {
// Display menu
std::cout << "========== Simple Calculator ==========\n";
std::cout << "1. Addition\n";
std::cout << "2. Subtraction\n";
std::cout << "3. Multiplication\n";
std::cout << "4. Division\n";
std::cout << "5. Exit\n";
std::cout << "Choose (1-5): ";
std::cin >> choice;
if (choice >= 1 && choice <= 4) {
double num1, num2;
std::cout << "Enter the first number: ";
std::cin >> num1;
std::cout << "Enter the second number: ";
std::cin >> num2;
double result;
bool valid = true;
switch (choice) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
} else {
std::cout << "Error: Divisor cannot be 0!" << std::endl;
valid = false;
}
break;
}
if (valid) {
std::cout << std::fixed << std::setprecision(2);
std::cout << "Result: " << result << std::endl;
}
} else if (choice == 5) {
std::cout << "Goodbye!" << std::endl;
} else {
std::cout << "Error: Please enter a number between 1-5!" << std::endl;
}
std::cout << std::endl;
} while (choice != 5);
return 0;
}
Output:
========== Simple Calculator ==========
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Choose (1-5):
Enter the first number:
Enter the second number:
Error: Divisor cannot be 0!
Result:
Goodbye!
Error: Please enter a number between 1-5!
4. Common Errors and Debugging
(1) 4.1 Infinite Loops
Error example:
int i = 1;
while (i <= 10) {
std::cout << i << " ";
// ❌ Forgot i++, i is always 1, loop never ends
}
Debugging tip: Add output inside the loop to check the loop variable's value:
int i = 1;
while (i <= 10) {
std::cout << "[DEBUG] i = " << i << std::endl;
std::cout << i << " ";
i++; // ✅ Remember to update the loop variable
}
(2) 4.2 Wrong Loop Condition
Error example:
// ❌ Want to output 1-10, but condition is i < 10, only outputs 1-9
for (int i = 1; i < 10; i++) {
std::cout << i << " ";
}
Debugging tip: Before the loop starts, output the loop variable's initial value and condition:
int i = 1;
std::cout << "[DEBUG] Initial value i = " << i << ", condition i <= 10" << std::endl;
while (i <= 10) {
std::cout << i << " ";
i++;
}
5. Practice Exercise: ATM Simulator
▶ Example 4: Simple ATM Simulator (Difficulty ⭐⭐⭐)
#include <iostream>
#include <iomanip>
int main() {
double balance = 1000.00; // Initial balance
int choice;
do {
// Display menu
std::cout << "========== ATM Simulator ==========\n";
std::cout << "1. Check balance\n";
std::cout << "2. Deposit\n";
std::cout << "3. Withdraw\n";
std::cout << "4. Exit\n";
std::cout << "Choose (1-4): ";
std::cin >> choice;
if (choice == 1) {
// Check balance
std::cout << std::fixed << std::setprecision(2);
std::cout << "Current balance: " << balance << std::endl;
} else if (choice == 2) {
// Deposit
double amount;
std::cout << "Enter deposit amount: ";
std::cin >> amount;
if (amount > 0) {
balance += amount;
std::cout << "Deposit successful!" << std::endl;
} else {
std::cout << "Error: Deposit amount must be greater than 0!" << std::endl;
}
} else if (choice == 3) {
// Withdraw
double amount;
std::cout << "Enter withdrawal amount: ";
std::cin >> amount;
if (amount > 0 && amount <= balance) {
balance -= amount;
std::cout << "Withdrawal successful!" << std::endl;
} else if (amount <= 0) {
std::cout << "Error: Withdrawal amount must be greater than 0!" << std::endl;
} else {
std::cout << "Error: Insufficient balance!" << std::endl;
}
} else if (choice == 4) {
std::cout << "Thank you for using, goodbye!" << std::endl;
} else {
std::cout << "Error: Please enter a number between 1-4!" << std::endl;
}
std::cout << std::endl;
} while (choice != 4);
return 0;
}
Output:
========== ATM Simulator ==========
1. Check balance
2. Deposit
3. Withdraw
4. Exit
Choose (1-4):
Current balance:
Enter deposit amount:
Deposit successful!
Error: Deposit amount must be greater than 0!
Enter withdrawal amount:
Withdrawal successful!
Error: Withdrawal amount must be greater than 0!
Error: Insufficient balance!
Thank you for using, goodbye!
Error: Please enter a number between 1-4!
Sample run:
========== ATM Simulator ==========
1. Check balance
2. Deposit
3. Withdraw
4. Exit
Choose (1-4): 1
Current balance: 1000.00
Choose (1-4): 2
Enter deposit amount: 500
Deposit successful!
Choose (1-4): 1
Current balance: 1500.00
Choose (1-4): 4
Thank you for using, goodbye!
❓ FAQ
for when you know the number of iterations (e.g., print 100 times); use while when you don't know the count but know the condition (e.g., guess until correct); use do-while when the body must execute at least once.break exits the entire loop, continue skips the current iteration and moves to the next. They can be mixed, but make sure the logic is clear — break terminates completely, continue only skips the current iteration.cin >> and getline. Solution: add cin.ignore() after cin >> to discard the newline character.📖 Summary
- Real programs often mix branching and loops
do-whilefits "must execute at least once" scenarios (e.g., menus)switch-casefits "choose one of many" scenarios (e.g., menu selections)- When debugging loops, add output inside the loop (e.g.,
[DEBUG] i = ...) - Be careful to avoid infinite loops (remember to update loop variables)
📝 Exercises
-
Basic (Difficulty ⭐): Write a program that lets the user enter a positive integer n, then outputs all even numbers from 1 to n.
-
Intermediate (Difficulty ⭐⭐): Write a program that implements a "Rock-Paper-Scissors" game:
- Let the user enter 1 (rock), 2 (scissors), 3 (paper)
- The program randomly generates a choice
- Determine the winner and output the result
- The user can choose to "play again"
-
Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "Simple Student Grade Management System": 5. Features: add students (name, grade), show all students, calculate average, exit 6. Use a menu loop for continuous operations 7. (Optional) Add a "sort by grade" feature
- Real programs mix branching and loops
- do-while fits scenarios that execute at least once (e.g., menus)
- switch-case fits choose-one-of-many scenarios
- In nested loops, break only exits the current level
- When debugging loops, use cout to output variable values and trace execution
6. 🚀 Next Steps
Congratulations! You've completed all lessons in Phase 1 (Basics). Next, we enter Phase 2 (Functions), learning how to encapsulate code into reusable modules for cleaner, more maintainable programs!