cpp

exercises

exercises.cpp⚙️
/**
 * C++ Arrays - Exercises
 * 
 * Practice problems to reinforce understanding of C++ arrays.
 * 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 <array>
#include <algorithm>
#include <cmath>

using namespace std;

// ============================================================
// Exercise 1: Find Maximum Element ⭐
// ============================================================
/**
 * Find and return the maximum element in an array.
 * 
 * Examples:
 *   findMax({3, 7, 2, 9, 1}, 5) returns 9
 *   findMax({-5, -2, -8}, 3) returns -2
 */
int findMax(int arr[], int size) {
    // TODO: Find and return the maximum element
    // Hint: Initialize max with first element, then compare with rest
    
    return 0; // Replace with your implementation
}

// ============================================================
// Exercise 2: Calculate Average ⭐
// ============================================================
/**
 * Calculate and return the average of all elements.
 * 
 * Examples:
 *   average({10, 20, 30}, 3) returns 20.0
 *   average({1, 2, 3, 4, 5}, 5) returns 3.0
 */
double average(int arr[], int size) {
    // TODO: Calculate and return the average
    // Hint: Sum all elements, then divide by size
    // Hint: Use double for accurate division
    
    return 0.0; // Replace with your implementation
}

// ============================================================
// Exercise 3: Reverse Array ⭐
// ============================================================
/**
 * Reverse the array in place.
 * 
 * Examples:
 *   reverse({1, 2, 3, 4, 5}, 5) -> {5, 4, 3, 2, 1}
 *   reverse({1, 2}, 2) -> {2, 1}
 */
void reverseArray(int arr[], int size) {
    // TODO: Reverse the array in place
    // Hint: Swap elements from both ends, moving toward center
    // Hint: Only need to iterate size/2 times
    
}

// ============================================================
// Exercise 4: Count Occurrences ⭐
// ============================================================
/**
 * Count how many times a target value appears in the array.
 * 
 * Examples:
 *   countOccurrences({1, 2, 3, 2, 4, 2}, 6, 2) returns 3
 *   countOccurrences({1, 1, 1, 1}, 4, 1) returns 4
 */
int countOccurrences(int arr[], int size, int target) {
    // TODO: Count occurrences of target
    // Hint: Loop through and increment counter when found
    
    return 0; // Replace with your implementation
}

// ============================================================
// Exercise 5: Check if Sorted ⭐⭐
// ============================================================
/**
 * Check if the array is sorted in ascending order.
 * 
 * Examples:
 *   isSorted({1, 2, 3, 4, 5}, 5) returns true
 *   isSorted({1, 3, 2, 4}, 4) returns false
 *   isSorted({5, 5, 5}, 3) returns true (equal elements are OK)
 */
bool isSorted(int arr[], int size) {
    // TODO: Check if array is sorted ascending
    // Hint: Compare each element with the next one
    
    return false; // Replace with your implementation
}

// ============================================================
// Exercise 6: Remove Duplicates ⭐⭐
// ============================================================
/**
 * Remove duplicate elements from a SORTED array.
 * Return the new size after removing duplicates.
 * 
 * Examples:
 *   removeDuplicates({1, 1, 2, 2, 3}, 5) returns 3, array becomes {1, 2, 3, ?, ?}
 *   removeDuplicates({1, 2, 3}, 3) returns 3, array unchanged
 */
int removeDuplicates(int arr[], int size) {
    // TODO: Remove duplicates from sorted array
    // Hint: Use two-pointer technique
    // Hint: One pointer for reading, one for writing
    
    return size; // Replace with your implementation
}

// ============================================================
// Exercise 7: Rotate Array ⭐⭐
// ============================================================
/**
 * Rotate the array to the right by k positions.
 * 
 * Examples:
 *   rotate({1, 2, 3, 4, 5}, 5, 2) -> {4, 5, 1, 2, 3}
 *   rotate({1, 2, 3}, 3, 1) -> {3, 1, 2}
 */
void rotateArray(int arr[], int size, int k) {
    // TODO: Rotate array right by k positions
    // Hint: k = k % size to handle k > size
    // Hint: One approach: reverse whole array, then reverse first k, then rest
    
}

// ============================================================
// Exercise 8: Merge Sorted Arrays ⭐⭐
// ============================================================
/**
 * Merge two sorted arrays into a result array (must be pre-allocated).
 * 
 * Examples:
 *   merge({1, 3, 5}, 3, {2, 4, 6}, 3, result) -> result = {1, 2, 3, 4, 5, 6}
 */
void mergeSortedArrays(int arr1[], int size1, int arr2[], int size2, int result[]) {
    // TODO: Merge two sorted arrays
    // Hint: Use two pointers, one for each array
    // Hint: Compare elements and add smaller one to result
    
}

// ============================================================
// Exercise 9: Find Two Sum ⭐⭐⭐
// ============================================================
/**
 * Find indices of two numbers that add up to target.
 * Return through i1 and i2 parameters.
 * If not found, set both to -1.
 * 
 * Examples:
 *   twoSum({2, 7, 11, 15}, 4, 9) sets i1=0, i2=1 (2+7=9)
 *   twoSum({3, 2, 4}, 3, 6) sets i1=1, i2=2 (2+4=6)
 */
void twoSum(int arr[], int size, int target, int& i1, int& i2) {
    // TODO: Find two indices that sum to target
    // Hint: Use nested loops (O(n²)) or hash map for O(n)
    // Hint: For each element, look for (target - element)
    
    i1 = -1;
    i2 = -1;
}

// ============================================================
// Exercise 10: Matrix Multiplication ⭐⭐⭐
// ============================================================
/**
 * Multiply two 3x3 matrices.
 * C[i][j] = sum of A[i][k] * B[k][j] for all k
 * 
 * Example:
 *   A = {{1,2,3},{4,5,6},{7,8,9}}
 *   B = {{9,8,7},{6,5,4},{3,2,1}}
 *   C = A × B (result matrix)
 */
void multiplyMatrices(int A[3][3], int B[3][3], int C[3][3]) {
    // TODO: Multiply A and B, store result in C
    // Hint: C[i][j] = sum(A[i][k] * B[k][j]) for k = 0 to 2
    // Hint: Use three nested loops
    
}

// ============================================================
// BONUS Exercise: Find Majority Element ⭐⭐⭐
// ============================================================
/**
 * Find the majority element (appears more than n/2 times).
 * Return -1 if no majority element exists.
 * 
 * Examples:
 *   majorityElement({3, 3, 4, 2, 3, 3, 3}, 7) returns 3
 *   majorityElement({1, 2, 3}, 3) returns -1
 */
int majorityElement(int arr[], int size) {
    // TODO: Find majority element using Boyer-Moore Voting Algorithm
    // Hint: Keep a candidate and a count
    // Hint: Increment count if same, decrement if different
    // Hint: If count reaches 0, pick new candidate
    // Hint: Finally, verify the candidate is actually majority
    
    return -1; // Replace with your implementation
}

// ============================================================
// Test Functions
// ============================================================
void testExercise1() {
    cout << "\n=== Testing Exercise 1: Find Maximum ===" << endl;
    int arr1[] = {3, 7, 2, 9, 1};
    int arr2[] = {-5, -2, -8};
    cout << "findMax({3,7,2,9,1}, 5) = " << findMax(arr1, 5) << " (expected: 9)" << endl;
    cout << "findMax({-5,-2,-8}, 3) = " << findMax(arr2, 3) << " (expected: -2)" << endl;
}

void testExercise2() {
    cout << "\n=== Testing Exercise 2: Average ===" << endl;
    int arr1[] = {10, 20, 30};
    int arr2[] = {1, 2, 3, 4, 5};
    cout << "average({10,20,30}, 3) = " << average(arr1, 3) << " (expected: 20)" << endl;
    cout << "average({1,2,3,4,5}, 5) = " << average(arr2, 5) << " (expected: 3)" << endl;
}

void testExercise3() {
    cout << "\n=== Testing Exercise 3: Reverse Array ===" << endl;
    int arr[] = {1, 2, 3, 4, 5};
    cout << "Before: "; for (int x : arr) cout << x << " "; cout << endl;
    reverseArray(arr, 5);
    cout << "After:  "; for (int x : arr) cout << x << " "; cout << "(expected: 5 4 3 2 1)" << endl;
}

void testExercise4() {
    cout << "\n=== Testing Exercise 4: Count Occurrences ===" << endl;
    int arr[] = {1, 2, 3, 2, 4, 2};
    cout << "countOccurrences({1,2,3,2,4,2}, 6, 2) = " << countOccurrences(arr, 6, 2) << " (expected: 3)" << endl;
}

void testExercise5() {
    cout << "\n=== Testing Exercise 5: Is Sorted ===" << endl;
    int arr1[] = {1, 2, 3, 4, 5};
    int arr2[] = {1, 3, 2, 4};
    cout << boolalpha;
    cout << "isSorted({1,2,3,4,5}, 5) = " << isSorted(arr1, 5) << " (expected: true)" << endl;
    cout << "isSorted({1,3,2,4}, 4) = " << isSorted(arr2, 4) << " (expected: false)" << endl;
}

void testExercise6() {
    cout << "\n=== Testing Exercise 6: Remove Duplicates ===" << endl;
    int arr[] = {1, 1, 2, 2, 3};
    int newSize = removeDuplicates(arr, 5);
    cout << "removeDuplicates({1,1,2,2,3}, 5):" << endl;
    cout << "  New size: " << newSize << " (expected: 3)" << endl;
    cout << "  Array: "; for (int i = 0; i < newSize; i++) cout << arr[i] << " "; cout << "(expected: 1 2 3)" << endl;
}

void testExercise7() {
    cout << "\n=== Testing Exercise 7: Rotate Array ===" << endl;
    int arr[] = {1, 2, 3, 4, 5};
    cout << "Before: "; for (int x : arr) cout << x << " "; cout << endl;
    rotateArray(arr, 5, 2);
    cout << "After rotate by 2: "; for (int x : arr) cout << x << " "; cout << "(expected: 4 5 1 2 3)" << endl;
}

void testExercise8() {
    cout << "\n=== Testing Exercise 8: Merge Sorted Arrays ===" << endl;
    int arr1[] = {1, 3, 5};
    int arr2[] = {2, 4, 6};
    int result[6];
    mergeSortedArrays(arr1, 3, arr2, 3, result);
    cout << "merge({1,3,5}, {2,4,6}): ";
    for (int i = 0; i < 6; i++) cout << result[i] << " ";
    cout << "(expected: 1 2 3 4 5 6)" << endl;
}

void testExercise9() {
    cout << "\n=== Testing Exercise 9: Two Sum ===" << endl;
    int arr[] = {2, 7, 11, 15};
    int i1, i2;
    twoSum(arr, 4, 9, i1, i2);
    cout << "twoSum({2,7,11,15}, 9): indices " << i1 << " and " << i2 << " (expected: 0 and 1)" << endl;
}

void testExercise10() {
    cout << "\n=== Testing Exercise 10: Matrix Multiplication ===" << endl;
    int A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int B[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
    int C[3][3] = {};
    
    multiplyMatrices(A, B, C);
    cout << "A × B = " << endl;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << C[i][j] << " ";
        }
        cout << endl;
    }
    cout << "(expected: 30 24 18 / 84 69 54 / 138 114 90)" << endl;
}

void testBonus() {
    cout << "\n=== Testing BONUS: Majority Element ===" << endl;
    int arr1[] = {3, 3, 4, 2, 3, 3, 3};
    int arr2[] = {1, 2, 3};
    cout << "majorityElement({3,3,4,2,3,3,3}, 7) = " << majorityElement(arr1, 7) << " (expected: 3)" << endl;
    cout << "majorityElement({1,2,3}, 3) = " << majorityElement(arr2, 3) << " (expected: -1)" << endl;
}

// ============================================================
// Main Function
// ============================================================
int main() {
    cout << "╔════════════════════════════════════════════════════════════╗" << endl;
    cout << "║                C++ ARRAYS - 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
// ============================================================
/*
// Exercise 1: Find Maximum
int findMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

// Exercise 2: Average
double average(int arr[], int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return static_cast<double>(sum) / size;
}

// Exercise 3: Reverse Array
void reverseArray(int arr[], int size) {
    for (int i = 0; i < size / 2; i++) {
        swap(arr[i], arr[size - 1 - i]);
    }
}

// Exercise 4: Count Occurrences
int countOccurrences(int arr[], int size, int target) {
    int count = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            count++;
        }
    }
    return count;
}

// Exercise 5: Is Sorted
bool isSorted(int arr[], int size) {
    for (int i = 1; i < size; i++) {
        if (arr[i] < arr[i-1]) {
            return false;
        }
    }
    return true;
}

// Exercise 6: Remove Duplicates
int removeDuplicates(int arr[], int size) {
    if (size == 0) return 0;
    
    int writeIndex = 1;
    for (int i = 1; i < size; i++) {
        if (arr[i] != arr[i-1]) {
            arr[writeIndex] = arr[i];
            writeIndex++;
        }
    }
    return writeIndex;
}

// Exercise 7: Rotate Array
void rotateArray(int arr[], int size, int k) {
    k = k % size;
    if (k == 0) return;
    
    // Reverse entire array
    reverse(arr, arr + size);
    // Reverse first k elements
    reverse(arr, arr + k);
    // Reverse remaining elements
    reverse(arr + k, arr + size);
}

// Exercise 8: Merge Sorted Arrays
void mergeSortedArrays(int arr1[], int size1, int arr2[], int size2, int result[]) {
    int i = 0, j = 0, k = 0;
    
    while (i < size1 && j < size2) {
        if (arr1[i] <= arr2[j]) {
            result[k++] = arr1[i++];
        } else {
            result[k++] = arr2[j++];
        }
    }
    
    while (i < size1) {
        result[k++] = arr1[i++];
    }
    
    while (j < size2) {
        result[k++] = arr2[j++];
    }
}

// Exercise 9: Two Sum
void twoSum(int arr[], int size, int target, int& i1, int& i2) {
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (arr[i] + arr[j] == target) {
                i1 = i;
                i2 = j;
                return;
            }
        }
    }
    i1 = -1;
    i2 = -1;
}

// Exercise 10: Matrix Multiplication
void multiplyMatrices(int A[3][3], int B[3][3], int C[3][3]) {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            C[i][j] = 0;
            for (int k = 0; k < 3; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
}

// BONUS: Majority Element (Boyer-Moore Voting)
int majorityElement(int arr[], int size) {
    // Find candidate
    int candidate = arr[0];
    int count = 1;
    
    for (int i = 1; i < size; i++) {
        if (arr[i] == candidate) {
            count++;
        } else {
            count--;
            if (count == 0) {
                candidate = arr[i];
                count = 1;
            }
        }
    }
    
    // Verify candidate
    count = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] == candidate) {
            count++;
        }
    }
    
    return (count > size / 2) ? candidate : -1;
}
*/
Exercises - C++ Tutorial | DeepML