Modular Programming in C

Modular Programming is the technique of breaking a large program into small, manageable, independent modules (files or functions). Each module performs a specific task, making the program easier to develop, debug, test, and reuse.

Why Modular Programming?

How Modular Programming Works in C?

C supports modular programming through:

Structure of a Modular C Program

main.c  → main() uses functions  
math.c  → function definitions  
math.h  → function declarations  

Benefits of Modules

Examples (5 Modular Programming Examples)

Example 1 — Separate Math Module

/* math.h */
int add(int a, int b);

/* math.c */
#include "math.h"
int add(int a, int b){
    return a + b;
}

/* main.c */
#include <stdio.h>
#include "math.h"

int main(){
    printf("Sum = %d", add(5, 10));
    return 0;
}

Example 2 — Multiple Modules

/* student.h */
void display();

/* student.c */
#include <stdio.h>
#include "student.h"
void display(){
    printf("Hello Student!");
}

/* main.c */
#include "student.h"
int main(){
    display();
    return 0;
}

Example 3 — Area Calculation

/* area.h */
float areaCircle(float r);

/* area.c */
#include "area.h"
#define PI 3.14
float areaCircle(float r){
    return PI * r * r;
}

/* main.c */
#include <stdio.h>
#include "area.h"

int main(){
    printf("Area = %.2f", areaCircle(5));
    return 0;
}

Example 4 — Modular String Function

/* stringutil.h */
int countChars(char *s);

/* stringutil.c */
#include "stringutil.h"
int countChars(char *s){
    int c = 0;
    while(s[c] != '\0') c++;
    return c;
}

/* main.c */
#include <stdio.h>
#include "stringutil.h"

int main(){
    printf("Length = %d", countChars("Hello"));
    return 0;
}

Example 5 — Calculator Modules

/* calc.h */
int add(int a, int b);
int sub(int a, int b);

/* calc.c */
#include "calc.h"
int add(int a, int b){ return a + b; }
int sub(int a, int b){ return a - b; }

/* main.c */
#include <stdio.h>
#include "calc.h"

int main(){
    printf("%d\n", add(8, 2));
    printf("%d\n", sub(8, 2));
    return 0;
}

Practice Questions

  1. What is modular programming?
  2. Explain modules, headers, and source files.
  3. Why are header files important?
  4. Difference between declaration and definition?
  5. Create a module to calculate simple interest.