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:

  1. The program randomly generates a number from 1-100
  2. The user enters their guess
  3. If the guess is too high, prompt "Too high"
  4. If the guess is too low, prompt "Too low"
  5. If the guess is correct, congratulate the user and show how many attempts it took
  6. The user can choose to play again

▶ Example 1: Complete Number Guessing Game (Difficulty ⭐⭐)

TEXT 📖 Display only
#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:

TEXT 📖 Display only
========== 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:

TEXT 📖 Display only
========== 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:

  1. Outer do-while: Controls "play again"
  2. Inner do-while: Main guessing loop
  3. if-else if-else: Checks if guess is too high/too low/correct
  4. 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:

  1. Display a menu (add contact, show contacts, exit)
  2. User selects an operation
  3. Use a loop to allow continuous operations until the user chooses to exit

▶ Example 2: Simple Address Book (Difficulty ⭐⭐⭐)

CPP 📖 Display only
#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;
}
44 logic lines (exceeds 40-line limit, display only)

Output:

TEXT 📖 Display only
========== 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:

  1. Display a menu (addition, subtraction, multiplication, division, exit)
  2. User selects an operation
  3. Enter two numbers, output the result
  4. Use a loop to allow continuous calculations

▶ Example 3: Extended Calculator (Difficulty ⭐⭐)

TEXT 📖 Display only
#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:

TEXT 📖 Display only
========== 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:

CPP
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:

CPP
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:

CPP
// ❌ 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:

CPP
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 ⭐⭐⭐)

CPP 📖 Display only
#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;
}
45 logic lines (exceeds 40-line limit, display only)

Output:

TEXT 📖 Display only
========== 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:

TEXT 📖 Display only
========== 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

Q When should I use for vs while?
A Use 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.
Q How do break and continue work together in a loop?
A 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.
Q Why does my program have issues when reading strings in a loop?
A This is usually caused by mixing cin >> and getline. Solution: add cin.ignore() after cin >> to discard the newline character.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Write a program that lets the user enter a positive integer n, then outputs all even numbers from 1 to n.

  2. Intermediate (Difficulty ⭐⭐): Write a program that implements a "Rock-Paper-Scissors" game:

    1. Let the user enter 1 (rock), 2 (scissors), 3 (paper)
    2. The program randomly generates a choice
    3. Determine the winner and output the result
    4. The user can choose to "play again"
  3. 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


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!

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏