c

exercises

exercises.cšŸ”§
/**
 * @file exercises.c
 * @brief Comments and Documentation Exercises
 * 
 * Complete these exercises to practice documentation skills.
 * 
 * Compile: gcc -Wall exercises.c -o exercises
 * Run: ./exercises
 */

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

/*
 * ============================================================================
 * EXERCISE 1: Add Function Documentation
 * ============================================================================
 * Difficulty: Easy
 * 
 * Task: Add proper documentation comments to this function.
 * Include: @brief, @param, @return, and @example
 */

// TODO: Add documentation comment here
int add(int a, int b) {
    return a + b;
}

void exercise_1() {
    printf("\n=== Exercise 1: Function Documentation ===\n");
    printf("Check source code - add documentation to add() function\n");
    printf("add(5, 3) = %d\n", add(5, 3));
}

/*
 * ============================================================================
 * EXERCISE 2: Add Inline Comments
 * ============================================================================
 * Difficulty: Easy
 * 
 * Task: Add meaningful inline comments explaining each step
 * of this function. Focus on WHY, not WHAT.
 */

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;
}

void exercise_2() {
    printf("\n=== Exercise 2: Inline Comments ===\n");
    printf("Check source code - add inline comments to findMax()\n");
    
    int numbers[] = {3, 7, 2, 9, 5};
    printf("Max value: %d\n", findMax(numbers, 5));
}

/*
 * ============================================================================
 * EXERCISE 3: Document a Structure
 * ============================================================================
 * Difficulty: Easy
 * 
 * Task: Add documentation to this structure and its fields.
 * Use @struct and field documentation syntax.
 */

// TODO: Add structure documentation
typedef struct {
    char title[100];
    char author[50];
    int year;
    float price;
    int inStock;
} Book;

void exercise_3() {
    printf("\n=== Exercise 3: Structure Documentation ===\n");
    printf("Check source code - document the Book structure\n");
    
    Book book = {"The C Programming Language", "K&R", 1988, 59.99, 1};
    printf("Book: %s by %s (%d)\n", book.title, book.author, book.year);
}

/*
 * ============================================================================
 * EXERCISE 4: Explain an Algorithm
 * ============================================================================
 * Difficulty: Medium
 * 
 * Task: This function implements bubble sort. Add a multi-line
 * comment at the top explaining how the algorithm works.
 * Add inline comments for key operations.
 */

// TODO: Add algorithm explanation here
void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void exercise_4() {
    printf("\n=== Exercise 4: Algorithm Documentation ===\n");
    printf("Check source code - document bubbleSort algorithm\n");
    
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    bubbleSort(arr, n);
    
    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

/*
 * ============================================================================
 * EXERCISE 5: Add TODO and FIXME Markers
 * ============================================================================
 * Difficulty: Easy
 * 
 * Task: This function has several issues. Add appropriate
 * markers (TODO, FIXME, NOTE, WARNING) where indicated.
 */

int divide(int a, int b) {
    // ??? Add marker: doesn't handle b=0
    
    // ??? Add marker: integer division loses precision
    return a / b;
}

char* getName() {
    // ??? Add marker: returning local variable is dangerous
    static char name[] = "Example";
    return name;
}

void exercise_5() {
    printf("\n=== Exercise 5: TODO/FIXME Markers ===\n");
    printf("Check source code - add appropriate markers\n");
    printf("10 / 3 = %d\n", divide(10, 3));
    printf("Name: %s\n", getName());
}

/*
 * ============================================================================
 * EXERCISE 6: Create File Header
 * ============================================================================
 * Difficulty: Easy
 * 
 * Task: This file is missing a proper header comment at the top.
 * Go to the top of this file and improve the header to include:
 * - @file
 * - @brief (more detailed)
 * - @author (your name)
 * - @date
 * - @version
 * - Compilation instructions
 */

void exercise_6() {
    printf("\n=== Exercise 6: File Header ===\n");
    printf("Improve the file header comment at the top of this file\n");
}

/*
 * ============================================================================
 * EXERCISE 7: Convert Bad Comments to Good Comments
 * ============================================================================
 * Difficulty: Medium
 * 
 * Task: The comments below are poor quality. Rewrite them to be
 * meaningful and helpful.
 */

void badCommentsExample() {
    // i is 0
    int i = 0;
    
    // increment
    i++;
    
    // loop
    while (i < 10) {
        // print
        printf("%d ", i);
        // add 1
        i = i + 1;
    }
}

void exercise_7() {
    printf("\n=== Exercise 7: Improve Bad Comments ===\n");
    printf("Check source code - fix the comments in badCommentsExample()\n");
    badCommentsExample();
    printf("\n");
}

/*
 * ============================================================================
 * EXERCISE 8: Document Error Codes
 * ============================================================================
 * Difficulty: Medium
 * 
 * Task: Add documentation to this enum explaining each error code.
 */

// TODO: Add enum documentation
typedef enum {
    SUCCESS,
    ERR_NULL_POINTER,
    ERR_OUT_OF_BOUNDS,
    ERR_INVALID_INPUT,
    ERR_FILE_NOT_FOUND,
    ERR_MEMORY_ALLOC
} ErrorCode;

// TODO: Add function documentation
ErrorCode validateInput(int* ptr, int value) {
    if (ptr == NULL) {
        return ERR_NULL_POINTER;
    }
    if (value < 0 || value > 100) {
        return ERR_INVALID_INPUT;
    }
    *ptr = value;
    return SUCCESS;
}

void exercise_8() {
    printf("\n=== Exercise 8: Document Error Codes ===\n");
    printf("Check source code - document ErrorCode enum\n");
    
    int result;
    ErrorCode code = validateInput(&result, 50);
    printf("Validation result: %d (0 = SUCCESS)\n", code);
}

/*
 * ============================================================================
 * EXERCISE 9: Self-Documenting Code
 * ============================================================================
 * Difficulty: Medium
 * 
 * Task: Refactor this code to be self-documenting.
 * Replace magic numbers with named constants.
 * Use descriptive variable and function names.
 */

// Cryptic version - refactor this:
int f(int x) {
    if (x < 0) return 0;
    if (x < 18) return 1;
    if (x < 65) return 2;
    return 3;
}

void exercise_9() {
    printf("\n=== Exercise 9: Self-Documenting Code ===\n");
    printf("Check source code - make f() self-documenting\n");
    
    // What does this even mean?
    printf("Category for age 25: %d\n", f(25));
}

/*
 * ============================================================================
 * EXERCISE 10: Complete Documentation Project
 * ============================================================================
 * Difficulty: Hard
 * 
 * Task: Create a fully documented mini library.
 * Include:
 * - File header
 * - Section dividers
 * - Function documentation
 * - Structure documentation
 * - Inline comments for complex logic
 */

// TODO: Create a well-documented "calculator" mini library
// with functions for add, subtract, multiply, divide
// Include proper error handling and documentation

void exercise_10() {
    printf("\n=== Exercise 10: Complete Documentation ===\n");
    printf("Create a fully documented calculator library\n");
    printf("Include all documentation elements learned\n");
}

/*
 * ============================================================================
 * MAIN FUNCTION
 * ============================================================================
 */
int main() {
    printf("╔════════════════════════════════════════════════╗\n");
    printf("ā•‘    COMMENTS AND DOCUMENTATION - EXERCISES      ā•‘\n");
    printf("ā•‘    Practice your documentation skills          ā•‘\n");
    printf("ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•\n");
    
    // Uncomment each exercise as you complete it
    
    // exercise_1();
    // exercise_2();
    // exercise_3();
    // exercise_4();
    // exercise_5();
    // exercise_6();
    // exercise_7();
    // exercise_8();
    // exercise_9();
    // exercise_10();
    
    printf("\n=== Uncomment exercises in main() to run them ===\n");
    
    return 0;
}

/*
 * ============================================================================
 * ANSWER KEY - EXAMPLE SOLUTIONS
 * ============================================================================
 * 
 * EXERCISE 1 - Function Documentation:
 * 
 * /**
 *  * @brief Adds two integers together.
 *  * 
 *  * Performs addition of two integer values and
 *  * returns the sum.
 *  * 
 *  * @param a First integer operand
 *  * @param b Second integer operand
 *  * @return Sum of a and b
 *  * 
 *  * @note May overflow for large values
 *  * 
 *  * @example
 *  *     int sum = add(5, 3);  // sum = 8
 *  * /
 * 
 * EXERCISE 2 - Inline Comments:
 * 
 * int findMax(int arr[], int size) {
 *     // Start by assuming first element is the maximum
 *     int max = arr[0];
 *     
 *     // Compare each remaining element with current max
 *     for (int i = 1; i < size; i++) {
 *         // Found a larger value - update our maximum
 *         if (arr[i] > max) {
 *             max = arr[i];
 *         }
 *     }
 *     
 *     return max;
 * }
 * 
 * EXERCISE 3 - Structure Documentation:
 * 
 * /**
 *  * @struct Book
 *  * @brief Represents a book in the inventory system.
 *  * /
 * typedef struct {
 *     char title[100];    /**< Full title of the book * /
 *     char author[50];    /**< Author name * /
 *     int year;           /**< Year of publication * /
 *     float price;        /**< Price in USD * /
 *     int inStock;        /**< Quantity in stock * /
 * } Book;
 * 
 * EXERCISE 4 - Algorithm Documentation:
 * 
 * /**
 *  * Bubble Sort Algorithm:
 *  * 
 *  * Repeatedly steps through the list, compares adjacent
 *  * elements, and swaps them if they are in wrong order.
 *  * 
 *  * Each pass through the list places the next largest
 *  * element in its correct position at the end.
 *  * 
 *  * Time Complexity: O(n²)
 *  * Space Complexity: O(1)
 *  * /
 * 
 * EXERCISE 5 - Markers:
 * 
 * int divide(int a, int b) {
 *     // FIXME: Division by zero will crash - add check
 *     // TODO: Return float for precise division
 *     return a / b;
 * }
 * 
 * char* getName() {
 *     // NOTE: Using static to avoid returning stack variable
 *     // WARNING: Not thread-safe due to static variable
 *     static char name[] = "Example";
 *     return name;
 * }
 * 
 * EXERCISE 9 - Self-Documenting:
 * 
 * #define AGE_CHILD_MAX 17
 * #define AGE_ADULT_MAX 64
 * 
 * typedef enum {
 *     AGE_CATEGORY_INVALID = 0,
 *     AGE_CATEGORY_CHILD = 1,
 *     AGE_CATEGORY_ADULT = 2,
 *     AGE_CATEGORY_SENIOR = 3
 * } AgeCategory;
 * 
 * AgeCategory getAgeCategory(int age) {
 *     if (age < 0) return AGE_CATEGORY_INVALID;
 *     if (age <= AGE_CHILD_MAX) return AGE_CATEGORY_CHILD;
 *     if (age <= AGE_ADULT_MAX) return AGE_CATEGORY_ADULT;
 *     return AGE_CATEGORY_SENIOR;
 * }
 * 
 * ============================================================================
 */
Exercises - C Programming Tutorial | DeepML