cpp
exercises
exercises.cpp⚙️cpp
/**
* C++ Function Basics - Exercises
*
* Practice problems to reinforce understanding of C++ functions.
* Each exercise includes a description, TODO section, and hints.
*
* 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>
#include <algorithm>
using namespace std;
// ============================================================
// Exercise 1: Square of a Number ⭐
// ============================================================
/**
* Write a function that returns the square of a number.
*
* Examples:
* square(5) returns 25
* square(-3) returns 9
* square(0) returns 0
*/
int square(int n) {
// TODO: Implement this function
// Hint: Multiply n by itself
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 2: Maximum of Two ⭐
// ============================================================
/**
* Write a function that returns the maximum of two integers.
*
* Examples:
* maxOfTwo(5, 3) returns 5
* maxOfTwo(-1, -5) returns -1
* maxOfTwo(7, 7) returns 7
*/
int maxOfTwo(int a, int b) {
// TODO: Implement this function
// Hint: Use if-else or ternary operator
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 3: Maximum of Three ⭐
// ============================================================
/**
* Write a function that returns the maximum of three integers.
* Try to reuse the maxOfTwo function!
*
* Examples:
* maxOfThree(1, 2, 3) returns 3
* maxOfThree(5, 2, 1) returns 5
* maxOfThree(-1, -2, -3) returns -1
*/
int maxOfThree(int a, int b, int c) {
// TODO: Implement this function
// Hint: Use maxOfTwo function twice
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 4: Is Vowel ⭐
// ============================================================
/**
* Write a function that checks if a character is a vowel.
* Should work for both uppercase and lowercase.
*
* Examples:
* isVowel('a') returns true
* isVowel('E') returns true
* isVowel('x') returns false
*/
bool isVowel(char c) {
// TODO: Implement this function
// Hint: Check against 'a', 'e', 'i', 'o', 'u' (and uppercase)
return false; // Replace with your implementation
}
// ============================================================
// Exercise 5: Count Vowels ⭐
// ============================================================
/**
* Write a function that counts the number of vowels in a string.
* Use the isVowel function!
*
* Examples:
* countVowels("Hello World") returns 3
* countVowels("AEIOU") returns 5
* countVowels("xyz") returns 0
*/
int countVowels(const string& str) {
// TODO: Implement this function
// Hint: Loop through string, use isVowel for each character
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 6: Celsius to Fahrenheit ⭐
// ============================================================
/**
* Write a function to convert Celsius to Fahrenheit.
* Formula: F = C * 9/5 + 32
*
* Examples:
* celsiusToFahrenheit(0) returns 32.0
* celsiusToFahrenheit(100) returns 212.0
* celsiusToFahrenheit(-40) returns -40.0
*/
double celsiusToFahrenheit(double celsius) {
// TODO: Implement this function
return 0.0; // Replace with your implementation
}
// ============================================================
// Exercise 7: Sum of Array ⭐⭐
// ============================================================
/**
* Write a function that calculates the sum of all elements in a vector.
*
* Examples:
* sumArray({1, 2, 3, 4, 5}) returns 15
* sumArray({-1, 1}) returns 0
* sumArray({}) returns 0
*/
int sumArray(const vector<int>& arr) {
// TODO: Implement this function
// Hint: Use a loop or std::accumulate
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 8: Average of Array ⭐⭐
// ============================================================
/**
* Write a function that calculates the average of all elements.
* Return 0 for empty array.
*
* Examples:
* average({1, 2, 3, 4, 5}) returns 3.0
* average({10, 20}) returns 15.0
* average({}) returns 0.0
*/
double average(const vector<int>& arr) {
// TODO: Implement this function
// Hint: Use sumArray and divide by size
return 0.0; // Replace with your implementation
}
// ============================================================
// Exercise 9: Power Function ⭐⭐
// ============================================================
/**
* Write a function to calculate base raised to the power exponent.
* Handle negative exponents too.
* Do NOT use pow() from <cmath>.
*
* Examples:
* power(2, 3) returns 8.0
* power(5, 0) returns 1.0
* power(2, -2) returns 0.25
*/
double power(double base, int exponent) {
// TODO: Implement this function
// Hint: Loop for positive exponent
// Hint: For negative, use 1 / power(base, -exponent)
return 0.0; // Replace with your implementation
}
// ============================================================
// Exercise 10: GCD (Greatest Common Divisor) ⭐⭐
// ============================================================
/**
* Write a function to find the GCD of two numbers using Euclidean algorithm.
*
* Examples:
* gcd(48, 18) returns 6
* gcd(17, 13) returns 1
* gcd(100, 25) returns 25
*/
int gcd(int a, int b) {
// TODO: Implement using Euclidean algorithm
// Hint: gcd(a, b) = gcd(b, a % b) until b is 0
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 11: LCM (Least Common Multiple) ⭐⭐
// ============================================================
/**
* Write a function to find the LCM of two numbers.
* Use the GCD function!
* Formula: LCM(a, b) = (a * b) / GCD(a, b)
*
* Examples:
* lcm(4, 6) returns 12
* lcm(3, 7) returns 21
* lcm(12, 18) returns 36
*/
int lcm(int a, int b) {
// TODO: Implement using GCD function
return 0; // Replace with your implementation
}
// ============================================================
// Exercise 12: Is Prime ⭐⭐
// ============================================================
/**
* Write a function to check if a number is prime.
*
* Examples:
* isPrime(2) returns true
* isPrime(17) returns true
* isPrime(4) returns false
* isPrime(1) returns false
*/
bool isPrime(int n) {
// TODO: Implement this function
// Hint: Check divisibility from 2 to sqrt(n)
return false; // Replace with your implementation
}
// ============================================================
// Exercise 13: Print Number Pattern ⭐⭐
// ============================================================
/**
* Write a function that prints a number pattern.
* For n=4, should print:
* 1
* 12
* 123
* 1234
*
* Use default argument to control whether numbers are spaced.
*/
void printPattern(int n, bool spaced = false) {
// TODO: Implement this function
// Hint: Nested loops - outer for rows, inner for numbers
}
// ============================================================
// Exercise 14: String Repeat ⭐⭐
// ============================================================
/**
* Write a function that repeats a string n times.
* Use default argument for separator.
*
* Examples:
* repeatString("ab", 3) returns "ababab"
* repeatString("Hi", 2, "-") returns "Hi-Hi"
* repeatString("x", 5, ", ") returns "x, x, x, x, x"
*/
string repeatString(const string& str, int n, const string& separator = "") {
// TODO: Implement this function
return ""; // Replace with your implementation
}
// ============================================================
// Exercise 15: Find Min and Max ⭐⭐⭐
// ============================================================
/**
* Write a function that finds both minimum and maximum in an array.
* Return them as a pair<int, int> where first is min, second is max.
*
* Examples:
* findMinMax({3, 1, 4, 1, 5}) returns {1, 5}
* findMinMax({7}) returns {7, 7}
* findMinMax({}) returns {0, 0}
*/
#include <utility>
pair<int, int> findMinMax(const vector<int>& arr) {
// TODO: Implement this function
// Hint: Initialize min/max with first element
// Hint: Loop through and update
return {0, 0}; // Replace with your implementation
}
// ============================================================
// Exercise 16: Digit Operations ⭐⭐⭐
// ============================================================
/**
* Write three related functions:
* 1. countDigits(n) - count number of digits
* 2. sumDigits(n) - sum of all digits
* 3. reverseDigits(n) - reverse the number
*
* Examples:
* countDigits(12345) returns 5
* sumDigits(123) returns 6
* reverseDigits(12345) returns 54321
*/
int countDigits(int n) {
// TODO: Implement
// Hint: Keep dividing by 10 until n becomes 0
return 0;
}
int sumDigits(int n) {
// TODO: Implement
// Hint: Extract each digit using % 10, then divide by 10
return 0;
}
int reverseDigits(int n) {
// TODO: Implement
// Hint: Build reversed number: rev = rev * 10 + n % 10
return 0;
}
// ============================================================
// Exercise 17: Armstrong Number ⭐⭐⭐
// ============================================================
/**
* An Armstrong number is a number that is equal to the sum of
* its own digits each raised to the power of the number of digits.
*
* Examples:
* isArmstrong(153) returns true (1³ + 5³ + 3³ = 153)
* isArmstrong(370) returns true (3³ + 7³ + 0³ = 370)
* isArmstrong(123) returns false
*
* Use countDigits and power functions!
*/
bool isArmstrong(int n) {
// TODO: Implement this function
return false;
}
// ============================================================
// Exercise 18: Perfect Number ⭐⭐⭐
// ============================================================
/**
* A perfect number equals the sum of its proper divisors.
* Proper divisors exclude the number itself.
*
* Examples:
* isPerfect(6) returns true (1 + 2 + 3 = 6)
* isPerfect(28) returns true (1 + 2 + 4 + 7 + 14 = 28)
* isPerfect(12) returns false (1 + 2 + 3 + 4 + 6 = 16 ≠ 12)
*/
bool isPerfect(int n) {
// TODO: Implement this function
// Hint: Find all divisors from 1 to n/2 and sum them
return false;
}
// ============================================================
// BONUS Exercise: Calculate Expression ⭐⭐⭐
// ============================================================
/**
* Write a simple expression evaluator.
* Given two numbers and an operator (+, -, *, /), calculate result.
* Use default values: b defaults to 0, op defaults to '+'.
*
* Examples:
* calculate(5, 3, '+') returns 8.0
* calculate(10, 2, '/') returns 5.0
* calculate(5) returns 5.0 (5 + 0)
* calculate(5, 3) returns 8.0 (5 + 3)
*/
double calculate(double a, double b = 0, char op = '+') {
// TODO: Implement this function
// Hint: Use switch statement for operators
// Hint: Handle division by zero
return 0.0;
}
// ============================================================
// Test Functions
// ============================================================
void testExercise1() {
cout << "\n=== Testing Exercise 1: Square ===" << endl;
cout << "square(5) = " << square(5) << " (expected: 25)" << endl;
cout << "square(-3) = " << square(-3) << " (expected: 9)" << endl;
cout << "square(0) = " << square(0) << " (expected: 0)" << endl;
}
void testExercise2() {
cout << "\n=== Testing Exercise 2: Maximum of Two ===" << endl;
cout << "maxOfTwo(5, 3) = " << maxOfTwo(5, 3) << " (expected: 5)" << endl;
cout << "maxOfTwo(-1, -5) = " << maxOfTwo(-1, -5) << " (expected: -1)" << endl;
cout << "maxOfTwo(7, 7) = " << maxOfTwo(7, 7) << " (expected: 7)" << endl;
}
void testExercise3() {
cout << "\n=== Testing Exercise 3: Maximum of Three ===" << endl;
cout << "maxOfThree(1, 2, 3) = " << maxOfThree(1, 2, 3) << " (expected: 3)" << endl;
cout << "maxOfThree(5, 2, 1) = " << maxOfThree(5, 2, 1) << " (expected: 5)" << endl;
cout << "maxOfThree(-1, -2, -3) = " << maxOfThree(-1, -2, -3) << " (expected: -1)" << endl;
}
void testExercise4() {
cout << "\n=== Testing Exercise 4: Is Vowel ===" << endl;
cout << boolalpha;
cout << "isVowel('a') = " << isVowel('a') << " (expected: true)" << endl;
cout << "isVowel('E') = " << isVowel('E') << " (expected: true)" << endl;
cout << "isVowel('x') = " << isVowel('x') << " (expected: false)" << endl;
}
void testExercise5() {
cout << "\n=== Testing Exercise 5: Count Vowels ===" << endl;
cout << "countVowels(\"Hello World\") = " << countVowels("Hello World") << " (expected: 3)" << endl;
cout << "countVowels(\"AEIOU\") = " << countVowels("AEIOU") << " (expected: 5)" << endl;
cout << "countVowels(\"xyz\") = " << countVowels("xyz") << " (expected: 0)" << endl;
}
void testExercise6() {
cout << "\n=== Testing Exercise 6: Celsius to Fahrenheit ===" << endl;
cout << "celsiusToFahrenheit(0) = " << celsiusToFahrenheit(0) << " (expected: 32)" << endl;
cout << "celsiusToFahrenheit(100) = " << celsiusToFahrenheit(100) << " (expected: 212)" << endl;
cout << "celsiusToFahrenheit(-40) = " << celsiusToFahrenheit(-40) << " (expected: -40)" << endl;
}
void testExercise7() {
cout << "\n=== Testing Exercise 7: Sum of Array ===" << endl;
cout << "sumArray({1,2,3,4,5}) = " << sumArray({1,2,3,4,5}) << " (expected: 15)" << endl;
cout << "sumArray({-1,1}) = " << sumArray({-1,1}) << " (expected: 0)" << endl;
cout << "sumArray({}) = " << sumArray({}) << " (expected: 0)" << endl;
}
void testExercise8() {
cout << "\n=== Testing Exercise 8: Average ===" << endl;
cout << "average({1,2,3,4,5}) = " << average({1,2,3,4,5}) << " (expected: 3)" << endl;
cout << "average({10,20}) = " << average({10,20}) << " (expected: 15)" << endl;
cout << "average({}) = " << average({}) << " (expected: 0)" << endl;
}
void testExercise9() {
cout << "\n=== Testing Exercise 9: Power ===" << endl;
cout << "power(2, 3) = " << power(2, 3) << " (expected: 8)" << endl;
cout << "power(5, 0) = " << power(5, 0) << " (expected: 1)" << endl;
cout << "power(2, -2) = " << power(2, -2) << " (expected: 0.25)" << endl;
}
void testExercise10() {
cout << "\n=== Testing Exercise 10: GCD ===" << endl;
cout << "gcd(48, 18) = " << gcd(48, 18) << " (expected: 6)" << endl;
cout << "gcd(17, 13) = " << gcd(17, 13) << " (expected: 1)" << endl;
cout << "gcd(100, 25) = " << gcd(100, 25) << " (expected: 25)" << endl;
}
void testExercise11() {
cout << "\n=== Testing Exercise 11: LCM ===" << endl;
cout << "lcm(4, 6) = " << lcm(4, 6) << " (expected: 12)" << endl;
cout << "lcm(3, 7) = " << lcm(3, 7) << " (expected: 21)" << endl;
cout << "lcm(12, 18) = " << lcm(12, 18) << " (expected: 36)" << endl;
}
void testExercise12() {
cout << "\n=== Testing Exercise 12: Is Prime ===" << endl;
cout << boolalpha;
cout << "isPrime(2) = " << isPrime(2) << " (expected: true)" << endl;
cout << "isPrime(17) = " << isPrime(17) << " (expected: true)" << endl;
cout << "isPrime(4) = " << isPrime(4) << " (expected: false)" << endl;
cout << "isPrime(1) = " << isPrime(1) << " (expected: false)" << endl;
}
void testExercise13() {
cout << "\n=== Testing Exercise 13: Print Pattern ===" << endl;
cout << "printPattern(4):" << endl;
printPattern(4);
cout << "printPattern(3, true):" << endl;
printPattern(3, true);
}
void testExercise14() {
cout << "\n=== Testing Exercise 14: String Repeat ===" << endl;
cout << "repeatString(\"ab\", 3) = \"" << repeatString("ab", 3) << "\" (expected: \"ababab\")" << endl;
cout << "repeatString(\"Hi\", 2, \"-\") = \"" << repeatString("Hi", 2, "-") << "\" (expected: \"Hi-Hi\")" << endl;
cout << "repeatString(\"x\", 5, \", \") = \"" << repeatString("x", 5, ", ") << "\" (expected: \"x, x, x, x, x\")" << endl;
}
void testExercise15() {
cout << "\n=== Testing Exercise 15: Find Min Max ===" << endl;
auto [min1, max1] = findMinMax({3, 1, 4, 1, 5});
cout << "findMinMax({3,1,4,1,5}) = {" << min1 << ", " << max1 << "} (expected: {1, 5})" << endl;
auto [min2, max2] = findMinMax({7});
cout << "findMinMax({7}) = {" << min2 << ", " << max2 << "} (expected: {7, 7})" << endl;
}
void testExercise16() {
cout << "\n=== Testing Exercise 16: Digit Operations ===" << endl;
cout << "countDigits(12345) = " << countDigits(12345) << " (expected: 5)" << endl;
cout << "sumDigits(123) = " << sumDigits(123) << " (expected: 6)" << endl;
cout << "reverseDigits(12345) = " << reverseDigits(12345) << " (expected: 54321)" << endl;
}
void testExercise17() {
cout << "\n=== Testing Exercise 17: Armstrong Number ===" << endl;
cout << boolalpha;
cout << "isArmstrong(153) = " << isArmstrong(153) << " (expected: true)" << endl;
cout << "isArmstrong(370) = " << isArmstrong(370) << " (expected: true)" << endl;
cout << "isArmstrong(123) = " << isArmstrong(123) << " (expected: false)" << endl;
}
void testExercise18() {
cout << "\n=== Testing Exercise 18: Perfect Number ===" << endl;
cout << boolalpha;
cout << "isPerfect(6) = " << isPerfect(6) << " (expected: true)" << endl;
cout << "isPerfect(28) = " << isPerfect(28) << " (expected: true)" << endl;
cout << "isPerfect(12) = " << isPerfect(12) << " (expected: false)" << endl;
}
void testBonus() {
cout << "\n=== Testing BONUS: Calculate ===" << endl;
cout << "calculate(5, 3, '+') = " << calculate(5, 3, '+') << " (expected: 8)" << endl;
cout << "calculate(10, 2, '/') = " << calculate(10, 2, '/') << " (expected: 5)" << endl;
cout << "calculate(5) = " << calculate(5) << " (expected: 5)" << endl;
cout << "calculate(5, 3) = " << calculate(5, 3) << " (expected: 8)" << endl;
}
// ============================================================
// Main Function
// ============================================================
int main() {
cout << "╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ C++ FUNCTION BASICS - EXERCISES ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
testExercise1();
testExercise2();
testExercise3();
testExercise4();
testExercise5();
testExercise6();
testExercise7();
testExercise8();
testExercise9();
testExercise10();
testExercise11();
testExercise12();
testExercise13();
testExercise14();
testExercise15();
testExercise16();
testExercise17();
testExercise18();
testBonus();
cout << "\n╔════════════════════════════════════════════════════════════╗" << endl;
cout << "║ Complete the TODO sections and re-run! ║" << endl;
cout << "╚════════════════════════════════════════════════════════════╝" << endl;
return 0;
}
// ============================================================
// ANSWER KEY
// ============================================================
/*
int square(int n) { return n * n; }
int maxOfTwo(int a, int b) { return (a > b) ? a : b; }
int maxOfThree(int a, int b, int c) { return maxOfTwo(maxOfTwo(a, b), c); }
bool isVowel(char c) {
c = tolower(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
int countVowels(const string& str) {
int count = 0;
for (char c : str) {
if (isVowel(c)) count++;
}
return count;
}
double celsiusToFahrenheit(double celsius) {
return celsius * 9.0/5.0 + 32;
}
int sumArray(const vector<int>& arr) {
int sum = 0;
for (int n : arr) sum += n;
return sum;
}
double average(const vector<int>& arr) {
if (arr.empty()) return 0.0;
return static_cast<double>(sumArray(arr)) / arr.size();
}
double power(double base, int exponent) {
if (exponent == 0) return 1;
if (exponent < 0) return 1.0 / power(base, -exponent);
double result = 1;
for (int i = 0; i < exponent; i++) result *= base;
return result;
}
int gcd(int a, int b) {
a = abs(a); b = abs(b);
while (b != 0) { int temp = b; b = a % b; a = temp; }
return a;
}
int lcm(int a, int b) { return (a / gcd(a, b)) * b; }
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0) return false;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
void printPattern(int n, bool spaced) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << j;
if (spaced && j < i) cout << " ";
}
cout << endl;
}
}
string repeatString(const string& str, int n, const string& separator) {
if (n <= 0) return "";
string result = str;
for (int i = 1; i < n; i++) result += separator + str;
return result;
}
pair<int, int> findMinMax(const vector<int>& arr) {
if (arr.empty()) return {0, 0};
int minV = arr[0], maxV = arr[0];
for (int n : arr) { if (n < minV) minV = n; if (n > maxV) maxV = n; }
return {minV, maxV};
}
int countDigits(int n) {
if (n == 0) return 1;
n = abs(n);
int count = 0;
while (n > 0) { count++; n /= 10; }
return count;
}
int sumDigits(int n) {
n = abs(n);
int sum = 0;
while (n > 0) { sum += n % 10; n /= 10; }
return sum;
}
int reverseDigits(int n) {
int rev = 0;
while (n > 0) { rev = rev * 10 + n % 10; n /= 10; }
return rev;
}
bool isArmstrong(int n) {
int digits = countDigits(n);
int sum = 0, temp = n;
while (temp > 0) {
sum += power(temp % 10, digits);
temp /= 10;
}
return sum == n;
}
bool isPerfect(int n) {
if (n <= 1) return false;
int sum = 1;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
sum += i;
if (i != n / i) sum += n / i;
}
}
return sum == n;
}
double calculate(double a, double b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return b != 0 ? a / b : 0;
default: return 0;
}
}
*/