What is modular programming?

28 Dec 2022 Balmiki Mandal 0 C Programming

Factorial Function in C

In C, modular programming is achieved by using functions. A function is a block of code that performs a specific task and returns a value. Functions can be defined by the user or they can be built-in functions.

To write modular code in C, you should follow these steps:

  1. Identify the different tasks that your program needs to perform.
  2. Create a function for each task.
  3. Each function should have a clear and concise purpose.
  4. The functions should be independent of each other.
  5. The functions should communicate with each other through well-defined interfaces.

Here is an example of a modular program in C:

C Programming
#include <stdio.h>

void factorial(int n) {
  int i, fact = 1;
  for (i = 1; i <= n; i++) {
    fact *= i;
  }
  printf("The factorial of %d is %d\n", n, fact);
}

int main() {
  int n;
  printf("Enter a number: ");
  scanf("%d", &n);
  factorial(n);
  return 0;
}
Output of the program you provided is:
Enter a number: 5
The factorial of 5 is 120

This program has two functions: factorial() and main(). The factorial() function calculates the factorial of a number and the main() function prompts the user for a number and calls the factorial() function.

The factorial() function is independent of the main() function. It does not need to know anything about the main() function and the main() function does not need to know anything about the factorial() function. This makes the program easier to understand, maintain, and debug.

Modular programming is a powerful technique that can help you write better C programs. If you are new to C, I recommend that you start by learning about functions and how to use them to write modular code.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.