Welcome to our comprehensive guide on C Modular Programming! In this lesson, we'll dive deep into understanding what modular programming is, its benefits, and how to create and use modules in C. Let's get started!
Modular programming is a process of dividing a large program into smaller, manageable, and reusable pieces called modules or functions. This approach enhances program organization, reduces complexity, and makes code maintenance easier.
To create a module in C, you'll write a function, which can be defined in a separate file (.c). This file can be included in other files using the #include preprocessor directive.
Here's a simple function example:
// Function definition in a separate file (hello.c)
void sayHello(char *name) {
printf("Hello, %s!\n", name);
}To use the above function in another file, include it like this:
// Main program (main.c)
#include <stdio.h>
#include "hello.h"
int main() {
sayHello("World");
return 0;
}In the example above, we've created a header file (hello.h) to declare our function:
// Function declaration in a header file (hello.h)
void sayHello(char *name);Let's take a look at a more complex example, where we create multiple functions and include them in a main program.
// Functions for calculating area (area.c)
#include <stdio.h>
void areaCircle(double radius) {
printf("Area of Circle: %.2f\n", 3.14159 * radius * radius);
}
void areaRectangle(double length, double width) {
printf("Area of Rectangle: %.2f\n", length * width);
}// Main program (main.c)
#include <stdio.h>
#include "area.h"
int main() {
double radius = 5.0;
double length = 10.0;
double width = 5.0;
areaCircle(radius);
areaRectangle(length, width);
return 0;
}What is the purpose of modular programming in C?