Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

C Programming Lab: Function Implementation and Recursion Examples

Tech 2

This lab explores fundamental C programming concepts through a series of tasks focusing on function implementation, recursion, and algorithmic problem-solving.

Task 1: Score to Grade Conversion

This task implements a function to convert a numerical score into a letter grade.

Implementation

#include <stdio.h>

char convert_to_grade(int score); // Function declaration

int main() {
    int user_score;
    char grade_letter;

    while (scanf("%d", &user_score) != EOF) {
        grade_letter = convert_to_grade(user_score); // Function call
        printf("Score: %d, Grade: %c\n\n", user_score, grade_letter);
    }
    return 0;
}

// Function definition
char convert_to_grade(int score) {
    char grade_result;
    switch (score / 10) {
        case 10:
        case 9: grade_result = 'A'; break;
        case 8: grade_result = 'B'; break;
        case 7: grade_result = 'C'; break;
        case 6: grade_result = 'D'; break;
        default: grade_result = 'E';
    }
    return grade_result;
}

Key Points

  • The function encapsulates the conversion logic, making it reusable and avoiding code duplication.
  • The function takes an int parameter and returns a char.
  • Without proper break statements in the switch cases, the function would produce incorrect results due to fall-through behavior.

Task 2: Sum of Digits

This task calculates the sum of digits of a given integer.

Implemantation

#include <stdio.h>

int calculate_digit_sum(int number); // Function declaration

int main() {
    int input_number;
    int result;

    while (printf("Enter n: "), scanf("%d", &input_number) != EOF) {
        result = calculate_digit_sum(input_number); // Function call
        printf("n = %d, sum = %d\n\n", input_number, result);
    }
    return 0;
}

// Function definition
int calculate_digit_sum(int number) {
    int sum = 0;
    while (number != 0) {
        sum += number % 10;
        number /= 10;
    }
    return sum;
}

Key Points

  • The function extracts and sums each digit of the input number.
  • This implementation uses an iterative approach. An equivalent recursive solution would involve: return (n == 0) ? 0 : (n % 10) + calculate_digit_sum(n / 10);

Task 3: Power Calculation Using Recursion

This task implements a recursive functon to calculate x raised to the power n.

Implementation

#include <stdio.h>

int compute_power(int base, int exponent); // Function declaration

int main() {
    int base_value, exponent_value;
    int power_result;

    while (printf("Enter x and n: "), scanf("%d%d", &base_value, &exponent_value) != EOF) {
        power_result = compute_power(base_value, exponent_value); // Function call
        printf("n = %d, result = %d\n\n", exponent_value, power_result);
    }
    return 0;
}

// Function definition
int compute_power(int base, int exponent) {
    int half_power;
    if (exponent == 0)
        return 1;
    else if (exponent % 2) // Odd exponent
        return base * compute_power(base, exponent - 1);
    else { // Even exponent
        half_power = compute_power(base, exponent / 2);
        return half_power * half_power;
    }
}

Mathematical Model

For compute_power(x, n):

  • When n = 0: compute_power(x, 0) = 1
  • When n > 0:
    • If n is odd: compute_power(x, n) = x * compute_power(x, n - 1)
    • If n is even: compute_power(x, n) = compute_power(x, n/2) * compute_power(x, n/2)

Task 4: Finding Twin Primes

This task identifies and counts twin prime pairs (primes with a difference of 2) within 100.

Implementation

#include <stdio.h>

int check_prime(int number) {
    if (number <= 1) return 0;
    for (int divisor = 2; divisor <= number/2; divisor++) {
        if (number % divisor == 0)
            return 0;
    }
    return 1;
}

int main() {
    int pair_count = 0;
    printf("Twin primes within 100:\n");
    for (int current = 1; current < 100; current++) {
        if (check_prime(current) && check_prime(current + 2)) {
            printf("%d %d\n", current, current + 2);
            pair_count++;
        }
    }
    printf("Total twin prime pairs within 100: %d\n", pair_count);
    return 0;
}

Task 5: Tower of Hanoi

This task implements the classic Tower of Hanoi puzzle using recursion.

Implementation

#include <stdio.h>

void solve_hanoi(int disks, char source, char target, char auxiliary);

int move_counter;

int main() {
    int disk_count;
    scanf("%d", &disk_count);
    solve_hanoi(disk_count, 'A', 'C', 'B');
    printf("Total moves: %d", move_counter);
    return 0;
}

void solve_hanoi(int disks, char source, char target, char auxiliary) {
    if (disks == 1) {
        printf("%d : %c --> %c\n", disks, source, target);
        move_counter++;
    } else {
        move_counter++;
        solve_hanoi(disks - 1, source, auxiliary, target);
        printf("%d : %c --> %c\n", disks, source, target);
        solve_hanoi(disks - 1, auxiliary, target, source);
    }
}

Task 6: Combination Calculation

This task calculates combinations C(n, m) using two different approaches.

Method 1: Iterative Calculation

#include <stdio.h>

int calculate_combination(int n, int m); // Function declaration

int main() {
    int n, m;
    int combination_result;
    while (scanf("%d%d", &n, &m) != EOF) {
        combination_result = calculate_combination(n, m); // Function call
        printf("n = %d, m = %d, C(n,m) = %d\n\n", n, m, combination_result);
    }
    return 0;
}

int calculate_combination(int n, int m) {
    if (m > n || m < 0) return 0;
    int numerator = 1;
    int denominator = 1;
    for (int i = n; i > n - m; i--) {
        numerator *= i;
    }
    for (int i = 1; i <= m; i++) {
        denominator *= i;
    }
    return numerator / denominator;
}

Method 2: Recursive Calculasion (Pascal's Identity)

#include <stdio.h>

int calculate_combination(int n, int m); // Function declaration

int main() {
    int n, m;
    int combination_result;
    while (scanf("%d%d", &n, &m) != EOF) {
        combination_result = calculate_combination(n, m); // Function call
        printf("n = %d, m = %d, C(n,m) = %d\n\n", n, m, combination_result);
    }
    return 0;
}

int calculate_combination(int n, int m) {
    if (m == 0 || m == n) return 1;
    if (m > n || m < 0) return 0;
    return calculate_combination(n - 1, m) + calculate_combination(n - 1, m - 1);
}

Task 7: Character Pattern Printing

This task prints a character pattern resembling a human figure.

Implementation

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

void print_figure_pattern(int size);

int main() {
    int pattern_size;
    printf("Enter n: ");
    scanf("%d", &pattern_size);
    print_figure_pattern(pattern_size); // Function call
    return 0;
}

void print_figure_pattern(int size) {
    int row, col;
    for (row = 0; row < size; row++) {
        // Print head row
        for (col = 0; col < row; col++) {
            printf("\t");
        }
        for (col = 0; col < size - row; col++) {
            printf(" O \t");
        }
        for (col = 0; col < size - row - 1; col++) {
            printf(" O \t");
        }
        printf("\n");

        // Print body row
        for (col = 0; col < row; col++) {
            printf("\t");
        }
        for (col = 0; col < size - row; col++) {
            printf("<H>\t");
        }
        for (col = 0; col < size - row - 1; col++) {
            printf("<H>\t");
        }
        printf("\n");

        // Print legs row
        for (col = 0; col < row; col++) {
            printf("\t");
        }
        for (col = 0; col < size - row; col++) {
            printf("I I\t");
        }
        for (col = 0; col < size - row - 1; col++) {
            printf("I I\t");
        }
        printf("\n\n");
    }
}

Summary

This lab demonstrates essential C programming concepts including:

  • Function declaration, definition, and calling
  • Parameter passing and return values
  • Recursive function design and implementation
  • Algorithmic problem-solving with both iterative and recursive approaches
  • Pattern generation and mathematical calculations

Each task reinforces the importance of modular programming through well-defined functions that encapsulate specific behaviors, making code more readable, maintainable, and reusable.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.