Course Introduction to Programming
Modularization
In this lesson, we will learn the concepts that involve the modularization of a program, addressing the following topics:
- What is modularization?
- Why modularize?
- What is a function?
- Functions in C
- Coding
What is modularization?
Modularizing means dividing your program into modules.
Each module will perform a specific task.
Until now, all our programs have been executed in a single module: the main function, which contained everything we wanted to execute.
Why modularize?
Modulating a program makes the programmer have to program small tasks at a time. This will:
- make debugging the code easier;
- improve code readability; and
- eliminate code redundancy.
If you still don't know what these concepts mean, here is a brief description of each one:
Debug: process of locating and reducing errors in the code. It is easier to find and fix errors in a code modularized in small tasks than it is in a not modularized one.
Legibility: ease of understanding what the code is doing. With this in mind, it is easier to understand the functionality of code modularized in small tasks than it is in not modularized one.
Redundancy: using the same piece of code more than once in the same program. In a modularized code, you can call the same task over and over again without having to rewrite it.
What is a function?
To modularize a program, we will divide it into functions.
A function is, in short, a block of code that receives certain parameters, performs their processing and returns a value.
Examples:
Functions in C
To create a function in C, we must specify:
Type of return: type of data the function will return;
- Name: name we will use to call the function;
Parameters: data that the function needs to work;
- Code: code of the function.
The creation of a function in C follows the template below:
<return type> <name> ( <parameters> ){
<code>
}
Observation: parameters must have their types identified, and if they are more than one, they need to be separated by commas.
Coding
Below is a code that defines and uses a function without parameters that only prints a phrase:
#include <stdio.h>
/*
Return type: integer
Name: prints
Parameters: none
Code: just a printf
*/
int prints(){
printf("Neps Academy\n");
}
int main(){
/* calls the "prints" function, providing the necessary parameters (in this case, none)
*/
prints();
}
/* Output:
Neps Academy
*/
Now that the function was created, we can call it as many times as we want within the main function, and the phrase "Neps Academy" will be printed as many times as the number of calls of the function.
Until the next lesson!