C Functions and Modular Programming

Learn to write reusable code with functions, understand scope, and build modular programs.

What are Functions?

Functions are reusable blocks of code that perform a specific task. They help in:
- Breaking down complex programs into smaller, manageable pieces
- Avoiding code duplication
- Making programs easier to read, debug, and maintain
- Enabling code reusability

A function consists of:
- Function declaration/prototype
- Function definition
- Function call

Basic syntax:
```c
// Function declaration
return_type function_name(parameter_list);

// Function definition
return_type function_name(parameter_list) {
    // function body
    return value;  // optional
}

// Function call
function_name(arguments);
```

Function Declaration and Definition

Function Declaration (Prototype):
- Tells the compiler about the function's name, return type, and parameters
- Must be declared before the function is called
- Usually placed at the top of the file or in header files

Function Definition:
- Contains the actual implementation of the function
- Must match the declaration

Example:
```c
#include <stdio.h>

// Function declaration
int add(int a, int b);

int main() {
    int result = add(5, 3);  // Function call
    printf("Sum: %d\n", result);
    return 0;
}

// Function definition
int add(int a, int b) {
    return a + b;
}
```

Parameters and Arguments

Parameters vs Arguments:
- Parameters: Variables in the function definition
- Arguments: Actual values passed to the function

Types of parameters:
1. Value parameters (pass by value)
2. Reference parameters (pass by reference using pointers)

Pass by Value:
```c
void modifyValue(int x) {
    x = 100;  // Changes only the local copy
}

int main() {
    int num = 10;
    modifyValue(num);
    printf("%d\n", num);  // Still prints 10
    return 0;
}
```

Pass by Reference:
```c
void modifyValue(int *x) {
    *x = 100;  // Changes the original variable
}

int main() {
    int num = 10;
    modifyValue(&num);
    printf("%d\n", num);  // Prints 100
    return 0;
}
```

Return Values

Functions can return values using the return statement:
- The return type must match the function declaration
- Use `void` if the function doesn't return anything
- Only one value can be returned directly
- Use pointers or structures to return multiple values

Examples:
```c
// Function that returns a value
int multiply(int a, int b) {
    return a * b;
}

// Function that returns nothing
void printMessage() {
    printf("Hello, World!\n");
    // No return statement needed
}

// Function that returns a pointer
int* createArray(int size) {
    int *arr = malloc(size * sizeof(int));
    return arr;
}
```

Recursion

Recursion is when a function calls itself. It's useful for:
- Solving problems that can be broken down into similar sub-problems
- Mathematical calculations like factorials, Fibonacci series
- Tree and graph traversals

Key points:
- Must have a base case to stop recursion
- Must have a recursive case that calls itself
- Each recursive call should work on a smaller problem

Example - Factorial:
```c
int factorial(int n) {
    // Base case
    if (n <= 1) {
        return 1;
    }
    // Recursive case
    return n * factorial(n - 1);
}
```

Practice Examples

Try these examples in our online C compiler to reinforce your learning:

Basic Function Example

Demonstrates basic function declaration, definition, and calling.

#include <stdio.h>

// Function declaration
int add(int a, int b);
void printResult(int result);

int main() {
    int num1 = 10, num2 = 20;
    int sum = add(num1, num2);
    printResult(sum);
    return 0;
}

// Function definition
int add(int a, int b) {
    return a + b;
}

void printResult(int result) {
    printf("The sum is: %d\n", result);
}

Function with Multiple Parameters

Shows how to work with multiple parameters in a function.

#include <stdio.h>

// Function to find maximum of three numbers
int findMax(int a, int b, int c) {
    int max = a;
    if (b > max) max = b;
    if (c > max) max = c;
    return max;
}

int main() {
    int x = 15, y = 25, z = 10;
    int maximum = findMax(x, y, z);
    printf("Maximum of %d, %d, %d is: %d\n", x, y, z, maximum);
    return 0;
}

Recursive Function - Fibonacci

Demonstrates recursion with the Fibonacci sequence.

#include <stdio.h>

// Recursive function to calculate Fibonacci number
int fibonacci(int n) {
    if (n <= 1) {
        return n;  // Base case
    }
    return fibonacci(n - 1) + fibonacci(n - 2);  // Recursive case
}

int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    
    printf("Fibonacci sequence up to %d terms:\n", n);
    for (int i = 0; i < n; i++) {
        printf("%d ", fibonacci(i));
    }
    printf("\n");
    
    return 0;
}

Ready for the Next Step?

Continue your C programming journey with our next tutorial.

Next: C Arrays and Strings →