cpp
exercises
exercises.cpp⚙️cpp
/**
* C++ Control Flow - Exercises
*
* Practice problems to reinforce understanding of C++ control flow.
* Each exercise includes a description, TODO section, and hints.
* Complete solutions are provided in the ANSWER KEY at the bottom.
*
* Difficulty Levels:
* ⭐ - Beginner
* ⭐⭐ - Intermediate
* ⭐⭐⭐ - Advanced
*
* Compile: g++ -std=c++17 -Wall -Wextra exercises.cpp -o exercises
* Run: ./exercises
*/
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
// ============================================================
// Exercise 1: FizzBuzz ⭐
// ============================================================
/**
* Classic FizzBuzz problem:
* For numbers 1 to n:
* - Print "Fizz" if divisible by 3
* - Print "Buzz" if divisible by 5
* - Print "FizzBuzz" if divisible by both 3 and 5
* - Otherwise print the number
*
* Example: fizzBuzz(15) should print:
* 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
*/
void fizzBuzz(int n) {
// TODO: Implement FizzBuzz
// Hint: Check divisibility using modulus (%)
// Hint: Check "both" condition first!
}
// ============================================================
// Exercise 2: Number Classifier ⭐
// ============================================================
/**
* Classify a number as:
* - "zero" if n == 0
* - "positive even" if n > 0 and divisible by 2
* - "positive odd" if n > 0 and not divisible by 2
* - "negative even" if n < 0 and divisible by 2
* - "negative odd" if n < 0 and not divisible by 2
*
* Examples:
* classify(4) returns "positive even"
* classify(-3) returns "negative odd"
*/
string classify(int n) {
// TODO: Implement the classifier
// Hint: Use if-else-if ladder
// Hint: Check for zero first
return ""; // Replace with your implementation
}
// ============================================================
// Exercise 3: Calculator with Switch ⭐
// ============================================================
/**
* Create a calculator that takes two numbers and an operator.
* Use a switch statement to perform the operation.
*
* Operators: '+', '-', '*', '/', '%'
* Return 0 for division by zero or invalid operator.
*
* Examples:
* calculate(10, 5, '+') returns 15
* calculate(10, 0, '/') returns 0
*/
double calculate(double a, double b, char op) {
// TODO: Implement using switch statement
// Hint: Handle division by zero
// Hint: For modulus, cast to int
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 4: Sum of Digits ⭐⭐
// ============================================================
/**
* Calculate the sum of digits of a positive integer.
* Use a while loop.
*
* Examples:
* sumDigits(123) returns 6 (1+2+3)
* sumDigits(9999) returns 36 (9+9+9+9)
*/
int sumDigits(int n) {
// TODO: Implement sum of digits
// Hint: Use % 10 to get last digit
// Hint: Use / 10 to remove last digit
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 5: Reverse Number ⭐⭐
// ============================================================
/**
* Reverse the digits of a positive integer.
*
* Examples:
* reverseNumber(12345) returns 54321
* reverseNumber(1000) returns 1 (leading zeros removed)
*/
int reverseNumber(int n) {
// TODO: Implement number reversal
// Hint: Build reversed number digit by digit
// Hint: reversed = reversed * 10 + last_digit
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 6: Prime Checker ⭐⭐
// ============================================================
/**
* Check if a number is prime.
* A prime number is greater than 1 and only divisible by 1 and itself.
*
* Examples:
* isPrime(2) returns true
* isPrime(4) returns false
* isPrime(17) returns true
*/
bool isPrime(int n) {
// TODO: Implement prime checker
// Hint: Only check up to sqrt(n)
// Hint: 0 and 1 are not prime
return false; // Replace with your implementation
}
// ============================================================
// Exercise 7: Print Pattern ⭐⭐
// ============================================================
/**
* Print a diamond pattern of size n (n should be odd).
*
* Example: printDiamond(5) should print:
* *
* ***
* *****
* ***
* *
*/
void printDiamond(int n) {
// TODO: Print diamond pattern
// Hint: Use nested loops
// Hint: Top half and bottom half are mirror images
// Hint: Calculate spaces and stars for each row
}
// ============================================================
// Exercise 8: Find Second Largest ⭐⭐
// ============================================================
/**
* Find the second largest element in an array.
* If array has less than 2 distinct elements, return -1.
*
* Examples:
* secondLargest({5, 1, 4, 2, 3}, 5) returns 4
* secondLargest({5, 5, 5}, 3) returns -1
*/
int secondLargest(int arr[], int size) {
// TODO: Find second largest
// Hint: Track both largest and second largest
// Hint: Update carefully when finding new largest
return -1; // Replace with your implementation
}
// ============================================================
// Exercise 9: Pascal's Triangle ⭐⭐⭐
// ============================================================
/**
* Print Pascal's Triangle with n rows.
* Each number is the sum of the two numbers above it.
*
* Example: printPascal(5) should print:
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* 1 4 6 4 1
*/
void printPascal(int n) {
// TODO: Print Pascal's triangle
// Hint: Each row starts and ends with 1
// Hint: Value = C(row, col) = row! / (col! * (row-col)!)
// Or use: value = prev_value * (row - col) / (col + 1)
}
// ============================================================
// Exercise 10: Binary to Decimal ⭐⭐⭐
// ============================================================
/**
* Convert a binary number (given as integer) to decimal.
*
* Examples:
* binaryToDecimal(1010) returns 10
* binaryToDecimal(11111) returns 31
* binaryToDecimal(100000) returns 32
*/
int binaryToDecimal(long long binary) {
// TODO: Convert binary to decimal
// Hint: Process each digit from right to left
// Hint: Multiply by powers of 2
return 0; // Replace with your implementation
}
// ============================================================
// BONUS Exercise: Number Guessing Game ⭐⭐⭐
// ============================================================
/**
* Simulate a number guessing game.
* The "secret" number is provided. Track guesses and return
* the number of attempts needed.
*
* Use binary search strategy:
* - Start with range [1, 100]
* - Guess middle of range
* - Narrow range based on whether guess is too high or too low
*
* Return the number of guesses needed to find the secret.
*/
int playGuessingGame(int secret) {
// TODO: Implement binary search guessing
// Hint: low = 1, high = 100
// Hint: guess = (low + high) / 2
// Hint: Adjust low or high based on comparison
return 0; // Replace with your implementation
}
// ============================================================
// Test Functions
// ============================================================
void testExercise1() {
cout << "\n=== Testing Exercise 1: FizzBuzz ===" << endl;
cout << "fizzBuzz(15):" << endl;
fizzBuzz(15);
cout << endl;
}
void testExercise2() {
cout << "\n=== Testing Exercise 2: Number Classifier ===" << endl;
cout << "classify(4) = \"" << classify(4) << "\" (expected: \"positive even\")" << endl;
cout << "classify(-3) = \"" << classify(-3) << "\" (expected: \"negative odd\")" << endl;
cout << "classify(0) = \"" << classify(0) << "\" (expected: \"zero\")" << endl;
cout << "classify(-8) = \"" << classify(-8) << "\" (expected: \"negative even\")" << endl;
}
void testExercise3() {
cout << "\n=== Testing Exercise 3: Calculator ===" << endl;
cout << "calculate(10, 5, '+') = " << calculate(10, 5, '+') << " (expected: 15)" << endl;
cout << "calculate(10, 5, '-') = " << calculate(10, 5, '-') << " (expected: 5)" << endl;
cout << "calculate(10, 5, '*') = " << calculate(10, 5, '*') << " (expected: 50)" << endl;
cout << "calculate(10, 3, '/') = " << calculate(10, 3, '/') << " (expected: 3.33...)" << endl;
cout << "calculate(10, 0, '/') = " << calculate(10, 0, '/') << " (expected: 0)" << endl;
}
void testExercise4() {
cout << "\n=== Testing Exercise 4: Sum of Digits ===" << endl;
cout << "sumDigits(123) = " << sumDigits(123) << " (expected: 6)" << endl;
cout << "sumDigits(9999) = " << sumDigits(9999) << " (expected: 36)" << endl;
cout << "sumDigits(0) = " << sumDigits(0) << " (expected: 0)" << endl;
}
void testExercise5() {
cout << "\n=== Testing Exercise 5: Reverse Number ===" << endl;
cout << "reverseNumber(12345) = " << reverseNumber(12345) << " (expected: 54321)" << endl;
cout << "reverseNumber(1000) = " << reverseNumber(1000) << " (expected: 1)" << endl;
cout << "reverseNumber(7) = " << reverseNumber(7) << " (expected: 7)" << endl;
}
void testExercise6() {
cout << "\n=== Testing Exercise 6: Prime Checker ===" << endl;
cout << boolalpha;
cout << "isPrime(2) = " << isPrime(2) << " (expected: true)" << endl;
cout << "isPrime(4) = " << isPrime(4) << " (expected: false)" << endl;
cout << "isPrime(17) = " << isPrime(17) << " (expected: true)" << endl;
cout << "isPrime(1) = " << isPrime(1) << " (expected: false)" << endl;
cout << "isPrime(97) = " << isPrime(97) << " (expected: true)" << endl;
}
void testExercise7() {
cout << "\n=== Testing Exercise 7: Print Diamond ===" << endl;
cout << "printDiamond(5):" << endl;
printDiamond(5);
}
void testExercise8() {
cout << "\n=== Testing Exercise 8: Second Largest ===" << endl;
int arr1[] = {5, 1, 4, 2, 3};
int arr2[] = {5, 5, 5};
int arr3[] = {1, 2};
cout << "secondLargest({5,1,4,2,3}, 5) = " << secondLargest(arr1, 5) << " (expected: 4)" << endl;
cout << "secondLargest({5,5,5}, 3) = " << secondLargest(arr2, 3) << " (expected: -1)" << endl;
cout << "secondLargest({1,2}, 2) = " << secondLargest(arr3, 2) << " (expected: 1)" << endl;
}
void testExercise9() {
cout << "\n=== Testing Exercise 9: Pascal's Triangle ===" << endl;
cout << "printPascal(5):" << endl;
printPascal(5);
}
void testExercise10() {
cout << "\n=== Testing Exercise 10: Binary to Decimal ===" << endl;
cout << "binaryToDecimal(1010) = " << binaryToDecimal(1010) << " (expected: 10)" << endl;
cout << "binaryToDecimal(11111) = " << binaryToDecimal(11111) << " (expected: 31)" << endl;
cout << "binaryToDecimal(100000) = " << binaryToDecimal(100000) << " (expected: 32)" << endl;
}
void testBonus() {
cout << "\n=== Testing BONUS: Guessing Game ===" << endl;
cout << "playGuessingGame(50) = " << playGuessingGame(50) << " guesses (expected: 1)" << endl;
cout << "playGuessingGame(25) = " << playGuessingGame(25) << " guesses (expected: <=7)" << endl;
cout << "playGuessingGame(73) = " << playGuessingGame(73) << " guesses (expected: <=7)" << endl;
}
// ============================================================
// Main Function
// ============================================================
int main() {
cout << "╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ C++ CONTROL FLOW - EXERCISES ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
testExercise1();
testExercise2();
testExercise3();
testExercise4();
testExercise5();
testExercise6();
testExercise7();
testExercise8();
testExercise9();
testExercise10();
testBonus();
cout << "\n╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ Complete the TODO sections and re-run! ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
return 0;
}
// ============================================================
// ANSWER KEY
// ============================================================
/*
* Below are the complete solutions for all exercises.
* Try to solve them yourself first before looking!
*/
/*
// Exercise 1: FizzBuzz
void fizzBuzz(int n) {
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
cout << "FizzBuzz ";
} else if (i % 3 == 0) {
cout << "Fizz ";
} else if (i % 5 == 0) {
cout << "Buzz ";
} else {
cout << i << " ";
}
}
}
// Exercise 2: Number Classifier
string classify(int n) {
if (n == 0) {
return "zero";
} else if (n > 0) {
return (n % 2 == 0) ? "positive even" : "positive odd";
} else {
return (n % 2 == 0) ? "negative even" : "negative odd";
}
}
// Exercise 3: Calculator with Switch
double calculate(double a, double b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0) return 0;
return a / b;
case '%':
if (b == 0) return 0;
return static_cast<int>(a) % static_cast<int>(b);
default:
return 0;
}
}
// Exercise 4: Sum of Digits
int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
// Exercise 5: Reverse Number
int reverseNumber(int n) {
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
// Exercise 6: Prime Checker
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
// Exercise 7: Print Diamond
void printDiamond(int n) {
// Ensure n is odd
if (n % 2 == 0) n++;
int mid = n / 2;
// Top half (including middle)
for (int i = 0; i <= mid; i++) {
// Print spaces
for (int s = 0; s < mid - i; s++) {
cout << " ";
}
// Print stars
for (int j = 0; j < 2 * i + 1; j++) {
cout << "*";
}
cout << endl;
}
// Bottom half
for (int i = mid - 1; i >= 0; i--) {
// Print spaces
for (int s = 0; s < mid - i; s++) {
cout << " ";
}
// Print stars
for (int j = 0; j < 2 * i + 1; j++) {
cout << "*";
}
cout << endl;
}
}
// Exercise 8: Find Second Largest
int secondLargest(int arr[], int size) {
if (size < 2) return -1;
int largest = INT_MIN;
int second = INT_MIN;
for (int i = 0; i < size; i++) {
if (arr[i] > largest) {
second = largest;
largest = arr[i];
} else if (arr[i] > second && arr[i] < largest) {
second = arr[i];
}
}
return (second == INT_MIN) ? -1 : second;
}
// Exercise 9: Pascal's Triangle
void printPascal(int n) {
for (int i = 0; i < n; i++) {
// Print leading spaces
for (int s = 0; s < n - i - 1; s++) {
cout << " ";
}
int value = 1;
for (int j = 0; j <= i; j++) {
cout << value << " ";
value = value * (i - j) / (j + 1);
}
cout << endl;
}
}
// Exercise 10: Binary to Decimal
int binaryToDecimal(long long binary) {
int decimal = 0;
int power = 1;
while (binary > 0) {
int digit = binary % 10;
decimal += digit * power;
power *= 2;
binary /= 10;
}
return decimal;
}
// BONUS: Guessing Game
int playGuessingGame(int secret) {
int low = 1, high = 100;
int guesses = 0;
while (low <= high) {
int guess = (low + high) / 2;
guesses++;
if (guess == secret) {
return guesses;
} else if (guess < secret) {
low = guess + 1;
} else {
high = guess - 1;
}
}
return guesses;
}
*/