c

exercises

exercises.cšŸ”§
/**
 * Passing Arrays to Functions - Exercises
 * 
 * Practice problems for passing arrays to functions.
 * Complete each exercise by implementing the required function.
 * 
 * Compile: gcc exercises.c -o exercises
 * Run: ./exercises
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* ============================================================
 * EXERCISE 1: Count Occurrences
 * 
 * Write a function that counts how many times a value appears
 * in an array.
 * 
 * Parameters:
 *   - arr: the array to search
 *   - size: number of elements
 *   - value: value to count
 * 
 * Returns: number of occurrences
 * ============================================================ */

int countOccurrences(const int arr[], int size, int value) {
    // TODO: Implement this function
    // Hint: Loop through array and count matches
    
    return 0;  // Replace with your implementation
}

void test_exercise1(void) {
    printf("=== Exercise 1: Count Occurrences ===\n");
    
    int arr[] = {1, 2, 3, 2, 4, 2, 5, 2, 6};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    printf("Array: ");
    for (int i = 0; i < size; i++) printf("%d ", arr[i]);
    printf("\n");
    
    printf("Count of 2: %d (expected: 4)\n", countOccurrences(arr, size, 2));
    printf("Count of 5: %d (expected: 1)\n", countOccurrences(arr, size, 5));
    printf("Count of 9: %d (expected: 0)\n", countOccurrences(arr, size, 9));
}


/* ============================================================
 * EXERCISE 2: Remove Duplicates
 * 
 * Write a function that removes duplicate values from a sorted
 * array and returns the new size.
 * 
 * Parameters:
 *   - arr: sorted array (will be modified in place)
 *   - size: current number of elements
 * 
 * Returns: new size after removing duplicates
 * ============================================================ */

int removeDuplicates(int arr[], int size) {
    // TODO: Implement this function
    // Hint: Use two pointers - one for reading, one for writing
    
    return size;  // Replace with your implementation
}

void test_exercise2(void) {
    printf("\n=== Exercise 2: Remove Duplicates ===\n");
    
    int arr[] = {1, 1, 2, 2, 2, 3, 4, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    printf("Before: ");
    for (int i = 0; i < size; i++) printf("%d ", arr[i]);
    printf("(size: %d)\n", size);
    
    int newSize = removeDuplicates(arr, size);
    
    printf("After:  ");
    for (int i = 0; i < newSize; i++) printf("%d ", arr[i]);
    printf("(size: %d, expected: 5)\n", newSize);
}


/* ============================================================
 * EXERCISE 3: Merge Sorted Arrays
 * 
 * Write a function that merges two sorted arrays into a third
 * sorted array.
 * 
 * Parameters:
 *   - arr1, size1: first sorted array and its size
 *   - arr2, size2: second sorted array and its size
 *   - result: output array (must have size >= size1 + size2)
 * ============================================================ */

void mergeSorted(const int arr1[], int size1, 
                 const int arr2[], int size2, 
                 int result[]) {
    // TODO: Implement this function
    // Hint: Use three indices - one for each array
    
}

void test_exercise3(void) {
    printf("\n=== Exercise 3: Merge Sorted Arrays ===\n");
    
    int arr1[] = {1, 3, 5, 7, 9};
    int arr2[] = {2, 4, 6, 8, 10};
    int result[10];
    
    printf("Array 1: ");
    for (int i = 0; i < 5; i++) printf("%d ", arr1[i]);
    printf("\n");
    
    printf("Array 2: ");
    for (int i = 0; i < 5; i++) printf("%d ", arr2[i]);
    printf("\n");
    
    mergeSorted(arr1, 5, arr2, 5, result);
    
    printf("Merged:  ");
    for (int i = 0; i < 10; i++) printf("%d ", result[i]);
    printf("\n");
    printf("Expected: 1 2 3 4 5 6 7 8 9 10\n");
}


/* ============================================================
 * EXERCISE 4: Second Largest Element
 * 
 * Write a function that finds the second largest element.
 * 
 * Parameters:
 *   - arr: the array
 *   - size: number of elements (must be >= 2)
 * 
 * Returns: second largest value
 * ============================================================ */

int secondLargest(const int arr[], int size) {
    // TODO: Implement this function
    // Hint: Track both largest and second largest
    
    return 0;  // Replace with your implementation
}

void test_exercise4(void) {
    printf("\n=== Exercise 4: Second Largest Element ===\n");
    
    int arr1[] = {10, 5, 8, 20, 15};
    int arr2[] = {1, 1, 1, 2};
    int arr3[] = {100, 50, 75, 100, 25};
    
    printf("Array: 10 5 8 20 15 -> Second largest: %d (expected: 15)\n",
           secondLargest(arr1, 5));
    printf("Array: 1 1 1 2 -> Second largest: %d (expected: 1)\n",
           secondLargest(arr2, 4));
    printf("Array: 100 50 75 100 25 -> Second largest: %d (expected: 100 or 75)\n",
           secondLargest(arr3, 5));
}


/* ============================================================
 * EXERCISE 5: Rotate Array by K Positions
 * 
 * Write a function that rotates an array to the left by k
 * positions.
 * 
 * Parameters:
 *   - arr: the array to rotate
 *   - size: number of elements
 *   - k: positions to rotate left
 * ============================================================ */

void rotateByK(int arr[], int size, int k) {
    // TODO: Implement this function
    // Hint: Handle k > size by using k % size
    // Method 1: Use temporary array
    // Method 2: Reverse segments
    
}

void test_exercise5(void) {
    printf("\n=== Exercise 5: Rotate Array by K ===\n");
    
    int arr[] = {1, 2, 3, 4, 5};
    int size = 5;
    
    printf("Original: ");
    for (int i = 0; i < size; i++) printf("%d ", arr[i]);
    printf("\n");
    
    rotateByK(arr, size, 2);
    
    printf("Rotate 2: ");
    for (int i = 0; i < size; i++) printf("%d ", arr[i]);
    printf("\n");
    printf("Expected: 3 4 5 1 2\n");
}


/* ============================================================
 * EXERCISE 6: Check if Arrays are Equal
 * 
 * Write a function that checks if two arrays have the same
 * elements (regardless of order).
 * 
 * Parameters:
 *   - arr1, size1: first array and size
 *   - arr2, size2: second array and size
 * 
 * Returns: 1 if equal, 0 if not
 * ============================================================ */

int arraysEqual(const int arr1[], int size1, 
                const int arr2[], int size2) {
    // TODO: Implement this function
    // Hint: Sort copies of both arrays, then compare
    // Or: Count occurrences of each element
    
    return 0;  // Replace with your implementation
}

void test_exercise6(void) {
    printf("\n=== Exercise 6: Check Arrays Equal ===\n");
    
    int arr1[] = {1, 2, 3, 4, 5};
    int arr2[] = {5, 4, 3, 2, 1};
    int arr3[] = {1, 2, 3, 4, 6};
    int arr4[] = {1, 2, 3};
    
    printf("arr1: 1 2 3 4 5\n");
    printf("arr2: 5 4 3 2 1\n");
    printf("arr3: 1 2 3 4 6\n");
    printf("arr4: 1 2 3\n\n");
    
    printf("arr1 == arr2? %d (expected: 1)\n", arraysEqual(arr1, 5, arr2, 5));
    printf("arr1 == arr3? %d (expected: 0)\n", arraysEqual(arr1, 5, arr3, 5));
    printf("arr1 == arr4? %d (expected: 0)\n", arraysEqual(arr1, 5, arr4, 3));
}


/* ============================================================
 * EXERCISE 7: Matrix Row Sum
 * 
 * Write a function that calculates the sum of each row in a
 * 2D array and stores results in a 1D array.
 * 
 * Parameters:
 *   - matrix: 2D array
 *   - rows: number of rows
 *   - rowSums: output array for sums
 * ============================================================ */

#define COLS 4

void calculateRowSums(int matrix[][COLS], int rows, int rowSums[]) {
    // TODO: Implement this function
    
}

void test_exercise7(void) {
    printf("\n=== Exercise 7: Matrix Row Sum ===\n");
    
    int matrix[3][COLS] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };
    int rowSums[3];
    
    printf("Matrix:\n");
    for (int i = 0; i < 3; i++) {
        printf("  ");
        for (int j = 0; j < COLS; j++) {
            printf("%3d ", matrix[i][j]);
        }
        printf("\n");
    }
    
    calculateRowSums(matrix, 3, rowSums);
    
    printf("\nRow sums: ");
    for (int i = 0; i < 3; i++) {
        printf("%d ", rowSums[i]);
    }
    printf("\nExpected: 10 26 42\n");
}


/* ============================================================
 * EXERCISE 8: Matrix Column Average
 * 
 * Write a function that calculates the average of each column.
 * 
 * Parameters:
 *   - matrix: 2D array
 *   - rows: number of rows
 *   - colAvgs: output array for averages
 * ============================================================ */

void calculateColAverages(int matrix[][COLS], int rows, double colAvgs[]) {
    // TODO: Implement this function
    
}

void test_exercise8(void) {
    printf("\n=== Exercise 8: Matrix Column Average ===\n");
    
    int matrix[3][COLS] = {
        {10, 20, 30, 40},
        {20, 30, 40, 50},
        {30, 40, 50, 60}
    };
    double colAvgs[COLS];
    
    printf("Matrix:\n");
    for (int i = 0; i < 3; i++) {
        printf("  ");
        for (int j = 0; j < COLS; j++) {
            printf("%3d ", matrix[i][j]);
        }
        printf("\n");
    }
    
    calculateColAverages(matrix, 3, colAvgs);
    
    printf("\nColumn averages: ");
    for (int i = 0; i < COLS; i++) {
        printf("%.1f ", colAvgs[i]);
    }
    printf("\nExpected: 20.0 30.0 40.0 50.0\n");
}


/* ============================================================
 * EXERCISE 9: Binary Search
 * 
 * Implement binary search for a sorted array.
 * 
 * Parameters:
 *   - arr: sorted array
 *   - size: number of elements
 *   - target: value to find
 * 
 * Returns: index of target, or -1 if not found
 * ============================================================ */

int binarySearch(const int arr[], int size, int target) {
    // TODO: Implement this function
    // Hint: Use left, right, and mid pointers
    
    return -1;  // Replace with your implementation
}

void test_exercise9(void) {
    printf("\n=== Exercise 9: Binary Search ===\n");
    
    int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    printf("Sorted array: ");
    for (int i = 0; i < size; i++) printf("%d ", arr[i]);
    printf("\n\n");
    
    int tests[] = {23, 2, 91, 50, 38};
    for (int i = 0; i < 5; i++) {
        int result = binarySearch(arr, size, tests[i]);
        printf("Search %d: index %d\n", tests[i], result);
    }
    printf("\nExpected: 5, 0, 9, -1, 6\n");
}


/* ============================================================
 * EXERCISE 10: Partition Array
 * 
 * Write a function that partitions an array around a pivot.
 * Elements < pivot go to the left, elements >= pivot go right.
 * 
 * Parameters:
 *   - arr: array to partition
 *   - size: number of elements
 *   - pivot: partition value
 * 
 * Returns: index where partition occurs
 * ============================================================ */

int partition(int arr[], int size, int pivot) {
    // TODO: Implement this function
    // Hint: Two-pointer approach from both ends
    
    return 0;  // Replace with your implementation
}

void test_exercise10(void) {
    printf("\n=== Exercise 10: Partition Array ===\n");
    
    int arr[] = {7, 2, 8, 1, 9, 3, 5, 4, 6};
    int size = sizeof(arr) / sizeof(arr[0]);
    int pivot = 5;
    
    printf("Original: ");
    for (int i = 0; i < size; i++) printf("%d ", arr[i]);
    printf("\nPivot: %d\n", pivot);
    
    int partIdx = partition(arr, size, pivot);
    
    printf("After:    ");
    for (int i = 0; i < size; i++) printf("%d ", arr[i]);
    printf("\nPartition index: %d\n", partIdx);
    printf("Elements before index should be < %d\n", pivot);
}


/* ============================================================
 * EXERCISE 11: Find Majority Element
 * 
 * Write a function that finds the majority element (appears
 * more than n/2 times). Return -1 if no majority exists.
 * 
 * Parameters:
 *   - arr: the array
 *   - size: number of elements
 * 
 * Returns: majority element or -1
 * ============================================================ */

int findMajority(const int arr[], int size) {
    // TODO: Implement this function
    // Hint: Boyer-Moore voting algorithm or count each element
    
    return -1;  // Replace with your implementation
}

void test_exercise11(void) {
    printf("\n=== Exercise 11: Find Majority Element ===\n");
    
    int arr1[] = {3, 3, 4, 2, 4, 4, 2, 4, 4};
    int arr2[] = {1, 2, 3, 4, 5};
    int arr3[] = {7, 7, 7, 7, 1, 2, 3};
    
    printf("Array 1: 3 3 4 2 4 4 2 4 4 -> Majority: %d (expected: 4)\n",
           findMajority(arr1, 9));
    printf("Array 2: 1 2 3 4 5 -> Majority: %d (expected: -1)\n",
           findMajority(arr2, 5));
    printf("Array 3: 7 7 7 7 1 2 3 -> Majority: %d (expected: 7)\n",
           findMajority(arr3, 7));
}


/* ============================================================
 * EXERCISE 12: Multiply Matrices
 * 
 * Write a function to multiply two 3x3 matrices.
 * 
 * Parameters:
 *   - a: first matrix (3x3)
 *   - b: second matrix (3x3)
 *   - result: output matrix (3x3)
 * ============================================================ */

#define SIZE3 3

void multiplyMatrices(int a[][SIZE3], int b[][SIZE3], int result[][SIZE3]) {
    // TODO: Implement this function
    // Formula: result[i][j] = sum of a[i][k] * b[k][j] for k = 0 to n-1
    
}

void test_exercise12(void) {
    printf("\n=== Exercise 12: Matrix Multiplication ===\n");
    
    int a[SIZE3][SIZE3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int b[SIZE3][SIZE3] = {
        {9, 8, 7},
        {6, 5, 4},
        {3, 2, 1}
    };
    int result[SIZE3][SIZE3] = {0};
    
    printf("Matrix A:           Matrix B:\n");
    for (int i = 0; i < SIZE3; i++) {
        printf("  ");
        for (int j = 0; j < SIZE3; j++) printf("%3d ", a[i][j]);
        printf("     ");
        for (int j = 0; j < SIZE3; j++) printf("%3d ", b[i][j]);
        printf("\n");
    }
    
    multiplyMatrices(a, b, result);
    
    printf("\nResult (A x B):\n");
    for (int i = 0; i < SIZE3; i++) {
        printf("  ");
        for (int j = 0; j < SIZE3; j++) {
            printf("%3d ", result[i][j]);
        }
        printf("\n");
    }
    printf("\nExpected:\n  30  24  18\n  84  69  54\n 138 114  90\n");
}


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

int main(void) {
    printf("╔══════════════════════════════════════════════════════╗\n");
    printf("ā•‘   PASSING ARRAYS TO FUNCTIONS - EXERCISES            ā•‘\n");
    printf("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n\n");
    
    test_exercise1();
    test_exercise2();
    test_exercise3();
    test_exercise4();
    test_exercise5();
    test_exercise6();
    test_exercise7();
    test_exercise8();
    test_exercise9();
    test_exercise10();
    test_exercise11();
    test_exercise12();
    
    printf("\n════════════════════════════════════════════════════════\n");
    printf("Complete the TODO sections and verify your answers!\n");
    
    return 0;
}


/* ============================================================
 * ANSWER KEY
 * ============================================================
 * 
 * EXERCISE 1: Count Occurrences
 * int countOccurrences(const int arr[], int size, int value) {
 *     int count = 0;
 *     for (int i = 0; i < size; i++) {
 *         if (arr[i] == value) count++;
 *     }
 *     return count;
 * }
 * 
 * EXERCISE 2: Remove Duplicates
 * int removeDuplicates(int arr[], int size) {
 *     if (size <= 1) return size;
 *     int writeIdx = 1;
 *     for (int readIdx = 1; readIdx < size; readIdx++) {
 *         if (arr[readIdx] != arr[readIdx - 1]) {
 *             arr[writeIdx++] = arr[readIdx];
 *         }
 *     }
 *     return writeIdx;
 * }
 * 
 * EXERCISE 3: Merge Sorted Arrays
 * void mergeSorted(const int arr1[], int size1,
 *                  const 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 4: Second Largest
 * int secondLargest(const int arr[], int size) {
 *     int first = arr[0], second = arr[0];
 *     for (int i = 1; i < size; i++) {
 *         if (arr[i] > first) {
 *             second = first;
 *             first = arr[i];
 *         } else if (arr[i] > second && arr[i] != first) {
 *             second = arr[i];
 *         }
 *     }
 *     return second;
 * }
 * 
 * EXERCISE 5: Rotate by K
 * void rotateByK(int arr[], int size, int k) {
 *     k = k % size;
 *     int temp[100];
 *     for (int i = 0; i < size; i++) {
 *         temp[i] = arr[(i + k) % size];
 *     }
 *     for (int i = 0; i < size; i++) {
 *         arr[i] = temp[i];
 *     }
 * }
 * 
 * EXERCISE 6: Arrays Equal
 * int arraysEqual(const int arr1[], int size1,
 *                 const int arr2[], int size2) {
 *     if (size1 != size2) return 0;
 *     int temp1[100], temp2[100];
 *     for (int i = 0; i < size1; i++) temp1[i] = arr1[i];
 *     for (int i = 0; i < size2; i++) temp2[i] = arr2[i];
 *     // Sort both (using bubble sort)
 *     for (int i = 0; i < size1-1; i++) {
 *         for (int j = 0; j < size1-i-1; j++) {
 *             if (temp1[j] > temp1[j+1]) {
 *                 int t = temp1[j]; temp1[j] = temp1[j+1]; temp1[j+1] = t;
 *             }
 *             if (temp2[j] > temp2[j+1]) {
 *                 int t = temp2[j]; temp2[j] = temp2[j+1]; temp2[j+1] = t;
 *             }
 *         }
 *     }
 *     for (int i = 0; i < size1; i++) {
 *         if (temp1[i] != temp2[i]) return 0;
 *     }
 *     return 1;
 * }
 * 
 * EXERCISE 7: Row Sums
 * void calculateRowSums(int matrix[][COLS], int rows, int rowSums[]) {
 *     for (int i = 0; i < rows; i++) {
 *         rowSums[i] = 0;
 *         for (int j = 0; j < COLS; j++) {
 *             rowSums[i] += matrix[i][j];
 *         }
 *     }
 * }
 * 
 * EXERCISE 8: Column Averages
 * void calculateColAverages(int matrix[][COLS], int rows, double colAvgs[]) {
 *     for (int j = 0; j < COLS; j++) {
 *         int sum = 0;
 *         for (int i = 0; i < rows; i++) {
 *             sum += matrix[i][j];
 *         }
 *         colAvgs[j] = (double)sum / rows;
 *     }
 * }
 * 
 * EXERCISE 9: Binary Search
 * int binarySearch(const int arr[], int size, int target) {
 *     int left = 0, right = size - 1;
 *     while (left <= right) {
 *         int mid = left + (right - left) / 2;
 *         if (arr[mid] == target) return mid;
 *         if (arr[mid] < target) left = mid + 1;
 *         else right = mid - 1;
 *     }
 *     return -1;
 * }
 * 
 * EXERCISE 10: Partition
 * int partition(int arr[], int size, int pivot) {
 *     int left = 0, right = size - 1;
 *     while (left <= right) {
 *         while (left <= right && arr[left] < pivot) left++;
 *         while (left <= right && arr[right] >= pivot) right--;
 *         if (left < right) {
 *             int temp = arr[left];
 *             arr[left] = arr[right];
 *             arr[right] = temp;
 *             left++; right--;
 *         }
 *     }
 *     return left;
 * }
 * 
 * EXERCISE 11: Majority Element
 * int findMajority(const int arr[], int size) {
 *     int candidate = arr[0], count = 1;
 *     for (int i = 1; i < size; i++) {
 *         if (arr[i] == candidate) count++;
 *         else count--;
 *         if (count == 0) {
 *             candidate = arr[i];
 *             count = 1;
 *         }
 *     }
 *     count = 0;
 *     for (int i = 0; i < size; i++) {
 *         if (arr[i] == candidate) count++;
 *     }
 *     return (count > size / 2) ? candidate : -1;
 * }
 * 
 * EXERCISE 12: Matrix Multiplication
 * void multiplyMatrices(int a[][SIZE3], int b[][SIZE3], int result[][SIZE3]) {
 *     for (int i = 0; i < SIZE3; i++) {
 *         for (int j = 0; j < SIZE3; j++) {
 *             result[i][j] = 0;
 *             for (int k = 0; k < SIZE3; k++) {
 *                 result[i][j] += a[i][k] * b[k][j];
 *             }
 *         }
 *     }
 * }
 * 
 * ============================================================ */
Exercises - C Programming Tutorial | DeepML