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?
- Reduces code complexity
- Improves code readability
- Easier debugging and testing
- Supports reusability
- Helps multiple developers work together
How Modular Programming Works in C?
C supports modular programming through:
- Functions
- Header Files (.h)
- Source Files (.c)
- Separate Compilation (gcc file1.c file2.c)
Structure of a Modular C Program
- main.c → main logic
- module.h → declarations
- module.c → definitions
main.c → main() uses functions math.c → function definitions math.h → function declarations
Benefits of Modules
- Independent compilation
- Cleaner code organization
- Faster development
- Prevents naming conflicts
- Allows team collaboration
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
- What is modular programming?
- Explain modules, headers, and source files.
- Why are header files important?
- Difference between declaration and definition?
- Create a module to calculate simple interest.