Skip to content

← Back to C Course Foundations

User Defined Functions (C)

Learning Objectives

  • Write and call C functions with/without arguments and return values.
  • Use functions from main() and from another function.
  • Implement recursive functions.

Function Types

  1. No arguments, no return value.
  2. No arguments, return value.
  3. With arguments, no return value.
  4. With arguments, return value.

C Example

#include <stdio.h>

void greet(void) {
    printf("Welcome\n");
}

int readNumber(void) {
    int n;
    scanf("%d", &n);
    return n;
}

void printSquare(int n) {
    printf("Square: %d\n", n * n);
}

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

int fact(int n) {
    if (n <= 1) return 1;
    return n * fact(n - 1);
}

int main(void) {
    greet();
    printf("Enter number: ");
    int x = readNumber();
    printSquare(x);
    printf("Sum(5,7) = %d\n", add(5, 7));
    printf("fact(5) = %d\n", fact(5));
    return 0;
}

Dry Run (Recursion)

fact(5) -> 5*fact(4) -> 5*4*fact(3) -> ... -> 5*4*3*2*1 = 120.

Common Mistakes

  • Missing function prototype (in older C flow).
  • Wrong return type.
  • Infinite recursion (no base condition).

Practice

  1. Create max-of-two function.
  2. Create sum-of-array function.
  3. Write recursive Fibonacci.