Modular Programming

Break large programs into smaller reusable functions.

Introduction

Modular programming involves dividing a program into independent functions (modules). Each function performs a specific task, reducing complexity and improving reusability.

Why Modular Programming?

  • Cleaner code structure
  • Easier debugging
  • Improved reusability
  • Independent module testing
  • Faster development

Example 1: Simple Function

#include <stdio.h>

void greet() {
    printf("Hello! Welcome to modular programming.\n");
}

int main() {
    greet();
    return 0;
}

Example 2: Function with Arguments

#include <stdio.h>

int multiply(int a, int b) {
    return a * b;
}

int main() {
    printf("Result = %d\n", multiply(4, 6));
    return 0;
}

Example 3: Function Declaration, Definition & Call

#include <stdio.h>

int add(int x, int y); // function declaration

int main() {
    int sum = add(7, 5);
    printf("Sum = %d\n", sum);
}

int add(int x, int y) { // function definition
    return x + y;
}

Types of User-Defined Functions

  • No arguments, no return value
  • Arguments but no return value
  • No arguments but return value
  • Arguments and return value

Practice

Write functions to:

  • Calculate factorial
  • Check prime number
  • Reverse a number
  • Find largest of 3 numbers

Try Code in Online Compiler