📘 Module 5: Functions – Reusable Logic

Goal: Encapsulate code into named, callable blocks. This is the key to clean, modular programs.

🔹 Function Basics

return_type function_name(parameter_list) {
    // body
    return value;   // if return_type is not 'void'
}

📖 Example: A function that returns the maximum of two integers

#include <stdio.h>

int max(int a, int b) {
    if (a > b) return a;
    else return b;
}

int main() {
    int x = 10, y = 20;
    printf("Max: %d\n", max(x, y));
    return 0;
}

🔹 Void Functions (no return value)

void greet(void) {
    printf("Hello, world!\n");
}

✏️ Exercise 1 (easy)

Write a function int square(int n) that returns n*n. Test it in main().

Solution
#include <stdio.h>
int square(int n) {
    return n * n;
}
int main() {
    printf("%d\n", square(5)); // 25
    return 0;
}

✏️ Exercise 2 (medium)

Write a function int isEven(int n) that returns 1 if n is even, 0 otherwise. Use it to print "even" or "odd" for user input.

Solution
#include <stdio.h>
int isEven(int n) {
    return (n % 2 == 0);
}
int main() {
    int num;
    printf("Enter number: ");
    scanf("%d", &num);
    if (isEven(num)) printf("even\n");
    else printf("odd\n");
    return 0;
}

✏️ Exercise 3 (practice)

Write a function int factorial(int n) that computes n! using a loop. Call it from main() for n = 5 and n = 7.

Solution
#include <stdio.h>
int factorial(int n) {
    int result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}
int main() {
    printf("5! = %d\n", factorial(5));   // 120
    printf("7! = %d\n", factorial(7));   // 5040
    return 0;
}
← Back to Module 4 - Loops Next: Module 6 - Recursion →