c

exercises

exercises.c🔧
/**
 * @file exercises.c
 * @brief Function Parameters and Arguments Exercises
 * 
 * Practice parameter passing in C.
 * 
 * Compile: gcc -Wall exercises.c -o exercises
 * Run: ./exercises
 */

#include <stdio.h>
#include <stdarg.h>

/* ============================================================
 * EXERCISE 1: SWAP TWO INTEGERS
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Write a function to swap two integers using pointers.
 */
void swap(int *a, int *b) {
    // TODO: Swap the values that a and b point to
    // Your code here
    
}

void exercise_1() {
    printf("\n=== Exercise 1: Swap Two Integers ===\n");
    
    int x = 10, y = 20;
    printf("Before: x=%d, y=%d\n", x, y);
    swap(&x, &y);
    printf("After: x=%d, y=%d (should be x=20, y=10)\n", x, y);
}

/* ============================================================
 * EXERCISE 2: ARRAY MINIMUM
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Find and return the minimum element in an array.
 */
int findMin(const int arr[], int size) {
    // TODO: Return minimum element
    // Your code here
    
    return 0;  // Replace this
}

void exercise_2() {
    printf("\n=== Exercise 2: Array Minimum ===\n");
    
    int arr[] = {45, 12, 78, 3, 56, 89, 23};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    printf("Minimum: %d (should be 3)\n", findMin(arr, size));
}

/* ============================================================
 * EXERCISE 3: REVERSE ARRAY
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Reverse an array in place.
 */
void reverseArray(int arr[], int size) {
    // TODO: Reverse the array in place
    // Your code here
    
}

void printArrayEx(int arr[], int size) {
    printf("[");
    for (int i = 0; i < size; i++) {
        printf("%d", arr[i]);
        if (i < size - 1) printf(", ");
    }
    printf("]\n");
}

void exercise_3() {
    printf("\n=== Exercise 3: Reverse Array ===\n");
    
    int arr[] = {1, 2, 3, 4, 5};
    int size = 5;
    
    printf("Before: ");
    printArrayEx(arr, size);
    
    reverseArray(arr, size);
    
    printf("After: ");
    printArrayEx(arr, size);
    printf("(should be [5, 4, 3, 2, 1])\n");
}

/* ============================================================
 * EXERCISE 4: COUNT OCCURRENCES
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Count how many times target appears in array.
 */
int countOccurrences(const int arr[], int size, int target) {
    // TODO: Return count of target in array
    // Your code here
    
    return 0;  // Replace this
}

void exercise_4() {
    printf("\n=== Exercise 4: Count Occurrences ===\n");
    
    int arr[] = {1, 3, 2, 3, 4, 3, 5};
    int size = 7;
    
    printf("Count of 3: %d (should be 3)\n", countOccurrences(arr, size, 3));
    printf("Count of 6: %d (should be 0)\n", countOccurrences(arr, size, 6));
}

/* ============================================================
 * EXERCISE 5: CALCULATE STATISTICS
 * ============================================================
 * Difficulty: Medium
 * 
 * Task: Calculate min, max, and average of array using pointers.
 */
void calculateStats(const int arr[], int size, 
                    int *min, int *max, float *avg) {
    // TODO: Set *min, *max, and *avg
    // Your code here
    
}

void exercise_5() {
    printf("\n=== Exercise 5: Calculate Statistics ===\n");
    
    int arr[] = {10, 25, 5, 30, 15};
    int size = 5;
    int min, max;
    float avg;
    
    calculateStats(arr, size, &min, &max, &avg);
    
    printf("Min: %d (should be 5)\n", min);
    printf("Max: %d (should be 30)\n", max);
    printf("Avg: %.2f (should be 17.00)\n", avg);
}

/* ============================================================
 * EXERCISE 6: STRING LENGTH
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Calculate length of string (without using strlen).
 */
int myStrlen(const char str[]) {
    // TODO: Return length of string
    // Your code here
    
    return 0;  // Replace this
}

void exercise_6() {
    printf("\n=== Exercise 6: String Length ===\n");
    
    printf("Length of 'Hello': %d (should be 5)\n", myStrlen("Hello"));
    printf("Length of '': %d (should be 0)\n", myStrlen(""));
    printf("Length of 'C Programming': %d (should be 13)\n", 
           myStrlen("C Programming"));
}

/* ============================================================
 * EXERCISE 7: COPY ARRAY
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Copy elements from source to destination array.
 */
void copyArray(int dest[], const int src[], int size) {
    // TODO: Copy all elements from src to dest
    // Your code here
    
}

void exercise_7() {
    printf("\n=== Exercise 7: Copy Array ===\n");
    
    int source[] = {1, 2, 3, 4, 5};
    int dest[5] = {0};
    int size = 5;
    
    copyArray(dest, source, size);
    
    printf("Copied: ");
    printArrayEx(dest, size);
    printf("(should be [1, 2, 3, 4, 5])\n");
}

/* ============================================================
 * EXERCISE 8: FILL ARRAY
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Fill an array with a given value.
 */
void fillArray(int arr[], int size, int value) {
    // TODO: Fill all elements with value
    // Your code here
    
}

void exercise_8() {
    printf("\n=== Exercise 8: Fill Array ===\n");
    
    int arr[5];
    
    fillArray(arr, 5, 42);
    
    printf("Filled: ");
    printArrayEx(arr, 5);
    printf("(should be [42, 42, 42, 42, 42])\n");
}

/* ============================================================
 * EXERCISE 9: SUM OF VARIABLE ARGUMENTS
 * ============================================================
 * Difficulty: Medium
 * 
 * Task: Write a variadic function to sum any number of integers.
 */
int sumVariadic(int count, ...) {
    // TODO: Return sum of all arguments
    // Use va_list, va_start, va_arg, va_end
    // Your code here
    
    return 0;  // Replace this
}

void exercise_9() {
    printf("\n=== Exercise 9: Variadic Sum ===\n");
    
    printf("sum(3, 10, 20, 30) = %d (should be 60)\n", 
           sumVariadic(3, 10, 20, 30));
    printf("sum(5, 1, 2, 3, 4, 5) = %d (should be 15)\n", 
           sumVariadic(5, 1, 2, 3, 4, 5));
}

/* ============================================================
 * EXERCISE 10: MATRIX ROW SUM
 * ============================================================
 * Difficulty: Medium
 * 
 * Task: Store sum of each row in a result array.
 */
void rowSums(int matrix[][3], int rows, int results[]) {
    // TODO: Store sum of each row in results array
    // Your code here
    
}

void exercise_10() {
    printf("\n=== Exercise 10: Matrix Row Sums ===\n");
    
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int results[3] = {0};
    
    rowSums(matrix, 3, results);
    
    printf("Row sums: ");
    printArrayEx(results, 3);
    printf("(should be [6, 15, 24])\n");
}

/* ============================================================
 * EXERCISE 11: FIND INDEX
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Return index of target, or -1 if not found.
 */
int findIndex(const int arr[], int size, int target) {
    // TODO: Return index of target or -1
    // Your code here
    
    return -1;  // Replace this
}

void exercise_11() {
    printf("\n=== Exercise 11: Find Index ===\n");
    
    int arr[] = {10, 20, 30, 40, 50};
    
    printf("Index of 30: %d (should be 2)\n", findIndex(arr, 5, 30));
    printf("Index of 60: %d (should be -1)\n", findIndex(arr, 5, 60));
}

/* ============================================================
 * EXERCISE 12: INCREMENT ALL
 * ============================================================
 * Difficulty: Easy
 * 
 * Task: Add a value to all elements in array.
 */
void incrementAll(int arr[], int size, int value) {
    // TODO: Add value to each element
    // Your code here
    
}

void exercise_12() {
    printf("\n=== Exercise 12: Increment All ===\n");
    
    int arr[] = {1, 2, 3, 4, 5};
    int size = 5;
    
    printf("Before: ");
    printArrayEx(arr, size);
    
    incrementAll(arr, size, 10);
    
    printf("After +10: ");
    printArrayEx(arr, size);
    printf("(should be [11, 12, 13, 14, 15])\n");
}

/* ============================================================
 * EXERCISE 13: SORT CHECK
 * ============================================================
 * Difficulty: Medium
 * 
 * Task: Return 1 if array is sorted ascending, 0 otherwise.
 */
int isSorted(const int arr[], int size) {
    // TODO: Return 1 if sorted ascending, 0 otherwise
    // Your code here
    
    return 0;  // Replace this
}

void exercise_13() {
    printf("\n=== Exercise 13: Sort Check ===\n");
    
    int sorted[] = {1, 2, 3, 4, 5};
    int unsorted[] = {1, 3, 2, 4, 5};
    
    printf("Sorted {1,2,3,4,5}: %s\n", 
           isSorted(sorted, 5) ? "Yes" : "No");
    printf("Sorted {1,3,2,4,5}: %s\n", 
           isSorted(unsorted, 5) ? "Yes" : "No");
}

/* ============================================================
 * EXERCISE 14: CONCATENATE STRINGS
 * ============================================================
 * Difficulty: Medium
 * 
 * Task: Concatenate src to end of dest.
 */
void myStrcat(char dest[], const char src[]) {
    // TODO: Append src to dest
    // Your code here
    
}

void exercise_14() {
    printf("\n=== Exercise 14: Concatenate Strings ===\n");
    
    char dest[50] = "Hello, ";
    const char src[] = "World!";
    
    myStrcat(dest, src);
    
    printf("Result: '%s' (should be 'Hello, World!')\n", dest);
}

/* ============================================================
 * EXERCISE 15: QUADRATIC ROOTS
 * ============================================================
 * Difficulty: Hard
 * 
 * Task: Find roots of ax² + bx + c = 0.
 * Return number of roots (0, 1, or 2).
 * Store roots in root1 and root2.
 */
int quadraticRoots(double a, double b, double c, 
                   double *root1, double *root2) {
    // TODO: Calculate roots
    // Return 0 if no real roots
    // Return 1 if one root (discriminant = 0)
    // Return 2 if two roots
    // Store roots in root1 and root2
    // Your code here
    
    return 0;  // Replace this
}

void exercise_15() {
    printf("\n=== Exercise 15: Quadratic Roots ===\n");
    
    double r1, r2;
    int numRoots;
    
    // x² - 5x + 6 = 0 (roots: 2, 3)
    numRoots = quadraticRoots(1, -5, 6, &r1, &r2);
    printf("x² - 5x + 6 = 0: %d roots", numRoots);
    if (numRoots > 0) printf(" (%.1f, %.1f)", r1, r2);
    printf("\n");
    
    // x² - 4x + 4 = 0 (root: 2)
    numRoots = quadraticRoots(1, -4, 4, &r1, &r2);
    printf("x² - 4x + 4 = 0: %d root", numRoots);
    if (numRoots > 0) printf(" (%.1f)", r1);
    printf("\n");
    
    // x² + 1 = 0 (no real roots)
    numRoots = quadraticRoots(1, 0, 1, &r1, &r2);
    printf("x² + 1 = 0: %d roots\n", numRoots);
}

/* ============================================================
 * MAIN FUNCTION
 * ============================================================ */
int main() {
    printf("╔════════════════════════════════════════════════╗\n");
    printf("║    PARAMETERS & ARGUMENTS - EXERCISES          ║\n");
    printf("║    Practice parameter passing                  ║\n");
    printf("╚════════════════════════════════════════════════╝\n");
    
    // Uncomment exercises as you complete them:
    
    // exercise_1();
    // exercise_2();
    // exercise_3();
    // exercise_4();
    // exercise_5();
    // exercise_6();
    // exercise_7();
    // exercise_8();
    // exercise_9();
    // exercise_10();
    // exercise_11();
    // exercise_12();
    // exercise_13();
    // exercise_14();
    // exercise_15();
    
    printf("\n=== Uncomment exercises in main() to run them ===\n");
    
    return 0;
}

/* ============================================================
 * ANSWER KEY
 * ============================================================
 *
 * EXERCISE 1:
 * void swap(int *a, int *b) {
 *     int temp = *a;
 *     *a = *b;
 *     *b = temp;
 * }
 *
 * EXERCISE 2:
 * int findMin(const int arr[], int size) {
 *     int min = arr[0];
 *     for (int i = 1; i < size; i++) {
 *         if (arr[i] < min) min = arr[i];
 *     }
 *     return min;
 * }
 *
 * EXERCISE 3:
 * void reverseArray(int arr[], int size) {
 *     for (int i = 0; i < size / 2; i++) {
 *         int temp = arr[i];
 *         arr[i] = arr[size - 1 - i];
 *         arr[size - 1 - i] = temp;
 *     }
 * }
 *
 * EXERCISE 4:
 * int countOccurrences(const 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:
 * void calculateStats(const int arr[], int size, 
 *                     int *min, int *max, float *avg) {
 *     *min = arr[0];
 *     *max = arr[0];
 *     int sum = 0;
 *     for (int i = 0; i < size; i++) {
 *         if (arr[i] < *min) *min = arr[i];
 *         if (arr[i] > *max) *max = arr[i];
 *         sum += arr[i];
 *     }
 *     *avg = (float)sum / size;
 * }
 *
 * EXERCISE 6:
 * int myStrlen(const char str[]) {
 *     int len = 0;
 *     while (str[len] != '\0') len++;
 *     return len;
 * }
 *
 * EXERCISE 7:
 * void copyArray(int dest[], const int src[], int size) {
 *     for (int i = 0; i < size; i++) {
 *         dest[i] = src[i];
 *     }
 * }
 *
 * EXERCISE 8:
 * void fillArray(int arr[], int size, int value) {
 *     for (int i = 0; i < size; i++) {
 *         arr[i] = value;
 *     }
 * }
 *
 * EXERCISE 9:
 * int sumVariadic(int count, ...) {
 *     va_list args;
 *     va_start(args, count);
 *     int sum = 0;
 *     for (int i = 0; i < count; i++) {
 *         sum += va_arg(args, int);
 *     }
 *     va_end(args);
 *     return sum;
 * }
 *
 * EXERCISE 10:
 * void rowSums(int matrix[][3], int rows, int results[]) {
 *     for (int i = 0; i < rows; i++) {
 *         results[i] = 0;
 *         for (int j = 0; j < 3; j++) {
 *             results[i] += matrix[i][j];
 *         }
 *     }
 * }
 *
 * EXERCISE 11:
 * int findIndex(const int arr[], int size, int target) {
 *     for (int i = 0; i < size; i++) {
 *         if (arr[i] == target) return i;
 *     }
 *     return -1;
 * }
 *
 * EXERCISE 12:
 * void incrementAll(int arr[], int size, int value) {
 *     for (int i = 0; i < size; i++) {
 *         arr[i] += value;
 *     }
 * }
 *
 * EXERCISE 13:
 * int isSorted(const int arr[], int size) {
 *     for (int i = 0; i < size - 1; i++) {
 *         if (arr[i] > arr[i + 1]) return 0;
 *     }
 *     return 1;
 * }
 *
 * EXERCISE 14:
 * void myStrcat(char dest[], const char src[]) {
 *     int i = 0, j = 0;
 *     while (dest[i] != '\0') i++;
 *     while (src[j] != '\0') {
 *         dest[i++] = src[j++];
 *     }
 *     dest[i] = '\0';
 * }
 *
 * EXERCISE 15:
 * #include <math.h>
 * int quadraticRoots(double a, double b, double c, 
 *                    double *root1, double *root2) {
 *     double discriminant = b*b - 4*a*c;
 *     if (discriminant < 0) return 0;
 *     if (discriminant == 0) {
 *         *root1 = *root2 = -b / (2*a);
 *         return 1;
 *     }
 *     double sqrtD = sqrt(discriminant);
 *     *root1 = (-b + sqrtD) / (2*a);
 *     *root2 = (-b - sqrtD) / (2*a);
 *     return 2;
 * }
 *
 * ============================================================
 */
Exercises - C Programming Tutorial | DeepML