cpp

exercises

exercises.cpp⚙️
/**
 * Function Overloading - Exercises
 * 
 * Practice problems for understanding function overloading in C++.
 * Each exercise includes TODO sections to complete.
 * 
 * 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: Display Function ⭐
// ============================================================
/**
 * Create overloaded display() functions for:
 * - int: shows "Integer: <value>"
 * - double: shows "Double: <value>" (2 decimal places)
 * - string: shows "String: \"<value>\""
 */
void display(int value) {
    // TODO: Implement
}

void display(double value) {
    // TODO: Implement
}

void display(const string& value) {
    // TODO: Implement
}

// ============================================================
// Exercise 2: Minimum Function ⭐
// ============================================================
/**
 * Create overloaded minimum() functions:
 * - Two integers
 * - Three integers
 * - Two doubles
 */
int minimum(int a, int b) {
    // TODO: Implement
    return 0;
}

int minimum(int a, int b, int c) {
    // TODO: Implement (use the two-argument version)
    return 0;
}

double minimum(double a, double b) {
    // TODO: Implement
    return 0.0;
}

// ============================================================
// Exercise 3: Contains Function ⭐⭐
// ============================================================
/**
 * Create overloaded contains() functions:
 * - Check if vector<int> contains a value
 * - Check if string contains a character
 * - Check if string contains a substring
 */
bool contains(const vector<int>& v, int value) {
    // TODO: Implement
    return false;
}

bool contains(const string& s, char c) {
    // TODO: Implement
    return false;
}

bool contains(const string& s, const string& sub) {
    // TODO: Implement
    return false;
}

// ============================================================
// Exercise 4: Multiply Function ⭐⭐
// ============================================================
/**
 * Create overloaded multiply() functions:
 * - Multiply two integers
 * - Multiply all elements in vector<int>, return product
 * - Multiply each element in vector by a scalar, modify in place
 */
int multiply(int a, int b) {
    // TODO: Implement
    return 0;
}

long long multiply(const vector<int>& v) {
    // TODO: Implement (return 1 for empty vector)
    return 0;
}

void multiply(vector<int>& v, int scalar) {
    // TODO: Implement (modify each element in place)
}

// ============================================================
// Exercise 5: Area Function ⭐⭐
// ============================================================
/**
 * Create overloaded area() functions for different shapes:
 * - Square: area(side)
 * - Rectangle: area(width, height)
 * - Circle: area(radius, true) - the bool indicates it's a circle
 * - Triangle: area(base, height, 't') - char 't' for triangle
 */
double area(double side) {
    // TODO: Square
    return 0.0;
}

double area(double width, double height) {
    // TODO: Rectangle
    return 0.0;
}

double area(double radius, bool isCircle) {
    // TODO: Circle (use 3.14159 for PI)
    (void)isCircle;  // Unused parameter marker
    return 0.0;
}

double area(double base, double height, char shapeType) {
    // TODO: Triangle if shapeType == 't' or 'T'
    (void)shapeType;
    return 0.0;
}

// ============================================================
// Exercise 6: Concatenate Function ⭐⭐
// ============================================================
/**
 * Create overloaded concat() functions:
 * - Two strings
 * - String and int (int converted to string)
 * - Vector of strings with separator
 */
string concat(const string& a, const string& b) {
    // TODO: Implement
    return "";
}

string concat(const string& s, int n) {
    // TODO: Implement
    return "";
}

string concat(const vector<string>& parts, const string& sep = "") {
    // TODO: Implement
    return "";
}

// ============================================================
// Exercise 7: Print Array Function ⭐⭐
// ============================================================
/**
 * Create overloaded printArray() functions:
 * - vector<int>
 * - vector<double>
 * - vector<string>
 * - C-style array with size
 * 
 * Format: [elem1, elem2, elem3]
 */
void printArray(const vector<int>& v) {
    // TODO: Implement
}

void printArray(const vector<double>& v) {
    // TODO: Implement
}

void printArray(const vector<string>& v) {
    // TODO: Implement (strings in quotes)
}

void printArray(const int* arr, size_t size) {
    // TODO: Implement
}

// ============================================================
// Exercise 8: Parse Function ⭐⭐⭐
// ============================================================
/**
 * Create overloaded parse() functions:
 * - Parse string to int (return 0 on failure)
 * - Parse string to double (return 0.0 on failure)
 * - Parse string to bool ("true"/"1" → true, otherwise false)
 */
int parse(const string& s, int defaultVal) {
    // TODO: Implement (use try-catch with stoi)
    (void)s;
    return defaultVal;
}

double parse(const string& s, double defaultVal) {
    // TODO: Implement (use try-catch with stod)
    (void)s;
    return defaultVal;
}

bool parse(const string& s, bool defaultVal) {
    // TODO: "true" or "1" → true, "false" or "0" → false, else default
    (void)s;
    return defaultVal;
}

// ============================================================
// Exercise 9: Range Function ⭐⭐⭐
// ============================================================
/**
 * Create overloaded range() functions that return vector<int>:
 * - range(end): [0, 1, 2, ..., end-1]
 * - range(start, end): [start, start+1, ..., end-1]
 * - range(start, end, step): [start, start+step, ...]
 */
vector<int> range(int end) {
    // TODO: Implement
    return {};
}

vector<int> range(int start, int end) {
    // TODO: Implement
    return {};
}

vector<int> range(int start, int end, int step) {
    // TODO: Implement (handle positive and negative step)
    return {};
}

// ============================================================
// Exercise 10: Format Function ⭐⭐⭐
// ============================================================
/**
 * Create overloaded format() functions:
 * - format(int): returns string representation
 * - format(double, precision): with decimal places
 * - format(int, width, fillChar): right-aligned with fill
 * - format(money, currency): "$123.45" format
 */
string format(int value) {
    // TODO: Implement
    return "";
}

string format(double value, int precision) {
    // TODO: Implement (use ostringstream with fixed/setprecision)
    return "";
}

string format(int value, int width, char fill) {
    // TODO: Implement (right-align with fill character)
    return "";
}

struct Money {
    int cents;
};

string format(Money m, const string& currency = "$") {
    // TODO: Format as "$12.34"
    (void)m;
    return currency;
}

// ============================================================
// TEST FUNCTIONS
// ============================================================

void testExercise1() {
    cout << "\n=== Exercise 1: Display ===" << endl;
    display(42);
    display(3.14159);
    display("Hello");
}

void testExercise2() {
    cout << "\n=== Exercise 2: Minimum ===" << endl;
    cout << "min(5, 3) = " << minimum(5, 3) << " (expected: 3)" << endl;
    cout << "min(5, 3, 7) = " << minimum(5, 3, 7) << " (expected: 3)" << endl;
    cout << "min(2.5, 1.5) = " << minimum(2.5, 1.5) << " (expected: 1.5)" << endl;
}

void testExercise3() {
    cout << "\n=== Exercise 3: Contains ===" << endl;
    cout << boolalpha;
    cout << "contains({1,2,3}, 2) = " << contains(vector<int>{1,2,3}, 2) << " (true)" << endl;
    cout << "contains(\"hello\", 'e') = " << contains(string("hello"), 'e') << " (true)" << endl;
    cout << "contains(\"hello\", \"ll\") = " << contains(string("hello"), string("ll")) << " (true)" << endl;
}

void testExercise4() {
    cout << "\n=== Exercise 4: Multiply ===" << endl;
    cout << "multiply(3, 4) = " << multiply(3, 4) << " (expected: 12)" << endl;
    cout << "multiply({2,3,4}) = " << multiply(vector<int>{2,3,4}) << " (expected: 24)" << endl;
    vector<int> v = {1, 2, 3};
    multiply(v, 2);
    cout << "multiply({1,2,3}, 2) = ";
    for (int n : v) cout << n << " ";
    cout << "(expected: 2 4 6)" << endl;
}

void testExercise5() {
    cout << "\n=== Exercise 5: Area ===" << endl;
    cout << "area(5) [square] = " << area(5.0) << " (expected: 25)" << endl;
    cout << "area(4, 6) [rect] = " << area(4.0, 6.0) << " (expected: 24)" << endl;
    cout << "area(3, true) [circle] = " << area(3.0, true) << " (expected: ~28.27)" << endl;
    cout << "area(4, 5, 't') [triangle] = " << area(4.0, 5.0, 't') << " (expected: 10)" << endl;
}

void testExercise6() {
    cout << "\n=== Exercise 6: Concatenate ===" << endl;
    cout << "concat(\"Hello\", \"World\") = " << concat("Hello", "World") << endl;
    cout << "concat(\"Count: \", 42) = " << concat("Count: ", 42) << endl;
    cout << "concat({\"a\",\"b\",\"c\"}, \"-\") = " << concat(vector<string>{"a","b","c"}, "-") << endl;
}

void testExercise7() {
    cout << "\n=== Exercise 7: Print Array ===" << endl;
    printArray(vector<int>{1, 2, 3});
    printArray(vector<double>{1.1, 2.2, 3.3});
    printArray(vector<string>{"a", "b", "c"});
    int arr[] = {10, 20, 30};
    printArray(arr, 3);
}

void testExercise8() {
    cout << "\n=== Exercise 8: Parse ===" << endl;
    cout << "parse(\"123\", 0) = " << parse("123", 0) << " (expected: 123)" << endl;
    cout << "parse(\"abc\", 0) = " << parse("abc", 0) << " (expected: 0)" << endl;
    cout << "parse(\"3.14\", 0.0) = " << parse("3.14", 0.0) << " (expected: 3.14)" << endl;
    cout << "parse(\"true\", false) = " << boolalpha << parse("true", false) << " (expected: true)" << endl;
}

void testExercise9() {
    cout << "\n=== Exercise 9: Range ===" << endl;
    cout << "range(5): ";
    for (int n : range(5)) cout << n << " ";
    cout << "(expected: 0 1 2 3 4)" << endl;
    
    cout << "range(2, 6): ";
    for (int n : range(2, 6)) cout << n << " ";
    cout << "(expected: 2 3 4 5)" << endl;
    
    cout << "range(0, 10, 2): ";
    for (int n : range(0, 10, 2)) cout << n << " ";
    cout << "(expected: 0 2 4 6 8)" << endl;
}

void testExercise10() {
    cout << "\n=== Exercise 10: Format ===" << endl;
    cout << "format(42) = \"" << format(42) << "\"" << endl;
    cout << "format(3.14159, 2) = \"" << format(3.14159, 2) << "\"" << endl;
    cout << "format(42, 6, '0') = \"" << format(42, 6, '0') << "\" (expected: \"000042\")" << endl;
    cout << "format(Money{1234}) = \"" << format(Money{1234}) << "\" (expected: \"$12.34\")" << endl;
}

// ============================================================
// MAIN FUNCTION
// ============================================================

int main() {
    cout << "╔════════════════════════════════════════════════════════════╗" << endl;
    cout << "║          FUNCTION OVERLOADING - EXERCISES                  ║" << endl;
    cout << "╚════════════════════════════════════════════════════════════╝" << endl;
    
    testExercise1();
    testExercise2();
    testExercise3();
    testExercise4();
    testExercise5();
    testExercise6();
    testExercise7();
    testExercise8();
    testExercise9();
    testExercise10();
    
    cout << "\n╔════════════════════════════════════════════════════════════╗" << endl;
    cout << "║         Complete the TODO sections and re-run!             ║" << endl;
    cout << "╚════════════════════════════════════════════════════════════╝" << endl;
    
    return 0;
}

// ============================================================
// ANSWER KEY
// ============================================================
/*
#include <iomanip>
#include <sstream>

// Exercise 1
void display(int value) { cout << "Integer: " << value << endl; }
void display(double value) { cout << "Double: " << fixed << setprecision(2) << value << endl; }
void display(const string& value) { cout << "String: \"" << value << "\"" << endl; }

// Exercise 2
int minimum(int a, int b) { return (a < b) ? a : b; }
int minimum(int a, int b, int c) { return minimum(minimum(a, b), c); }
double minimum(double a, double b) { return (a < b) ? a : b; }

// Exercise 3
bool contains(const vector<int>& v, int value) {
    for (int n : v) if (n == value) return true;
    return false;
}
bool contains(const string& s, char c) { return s.find(c) != string::npos; }
bool contains(const string& s, const string& sub) { return s.find(sub) != string::npos; }

// Exercise 4
int multiply(int a, int b) { return a * b; }
long long multiply(const vector<int>& v) {
    if (v.empty()) return 1;
    long long prod = 1;
    for (int n : v) prod *= n;
    return prod;
}
void multiply(vector<int>& v, int scalar) {
    for (int& n : v) n *= scalar;
}

// Exercise 5
double area(double side) { return side * side; }
double area(double width, double height) { return width * height; }
double area(double radius, bool isCircle) { (void)isCircle; return 3.14159 * radius * radius; }
double area(double base, double height, char t) { (void)t; return 0.5 * base * height; }

// Exercise 6
string concat(const string& a, const string& b) { return a + b; }
string concat(const string& s, int n) { return s + to_string(n); }
string concat(const vector<string>& parts, const string& sep) {
    string result;
    for (size_t i = 0; i < parts.size(); i++) {
        result += parts[i];
        if (i < parts.size() - 1) result += sep;
    }
    return result;
}

// Exercise 7
void printArray(const vector<int>& v) {
    cout << "[";
    for (size_t i = 0; i < v.size(); i++) {
        cout << v[i];
        if (i < v.size()-1) cout << ", ";
    }
    cout << "]" << endl;
}
void printArray(const vector<double>& v) {
    cout << "[";
    for (size_t i = 0; i < v.size(); i++) {
        cout << v[i];
        if (i < v.size()-1) cout << ", ";
    }
    cout << "]" << endl;
}
void printArray(const vector<string>& v) {
    cout << "[";
    for (size_t i = 0; i < v.size(); i++) {
        cout << "\"" << v[i] << "\"";
        if (i < v.size()-1) cout << ", ";
    }
    cout << "]" << endl;
}
void printArray(const int* arr, size_t size) {
    cout << "[";
    for (size_t i = 0; i < size; i++) {
        cout << arr[i];
        if (i < size-1) cout << ", ";
    }
    cout << "]" << endl;
}

// Exercise 8
int parse(const string& s, int defaultVal) {
    try { return stoi(s); } catch (...) { return defaultVal; }
}
double parse(const string& s, double defaultVal) {
    try { return stod(s); } catch (...) { return defaultVal; }
}
bool parse(const string& s, bool defaultVal) {
    if (s == "true" || s == "1") return true;
    if (s == "false" || s == "0") return false;
    return defaultVal;
}

// Exercise 9
vector<int> range(int end) { return range(0, end); }
vector<int> range(int start, int end) { return range(start, end, 1); }
vector<int> range(int start, int end, int step) {
    vector<int> result;
    if (step > 0) {
        for (int i = start; i < end; i += step) result.push_back(i);
    } else if (step < 0) {
        for (int i = start; i > end; i += step) result.push_back(i);
    }
    return result;
}

// Exercise 10
string format(int value) { return to_string(value); }
string format(double value, int precision) {
    ostringstream oss;
    oss << fixed << setprecision(precision) << value;
    return oss.str();
}
string format(int value, int width, char fill) {
    string s = to_string(value);
    if ((int)s.length() >= width) return s;
    return string(width - s.length(), fill) + s;
}
string format(Money m, const string& currency) {
    int dollars = m.cents / 100;
    int cents = m.cents % 100;
    ostringstream oss;
    oss << currency << dollars << "." << setw(2) << setfill('0') << cents;
    return oss.str();
}
*/
Exercises - C++ Tutorial | DeepML