In this tutorial, we are going to learn about Functions in C.
Functions in C Language:
A program can be used to solve a simple problem or a large complex problem. Programs solving simple problems are very easier to understand and identify mistakes, if any, in them.
The steps involved in programs solving large complex problems are difficult to understand. So, large programs are subdivided into a number of smaller programs called subprograms or modules.
Each subprogram specifies one or more actions to be performed for the larger program, such subprograms are called subroutines or functions. In some times we need to write a particular block of code more than once in our program. This may lead to bugs and irritation for the programmer.
C language provides an approach in which you need to declare and define a group of statements once and that can be called and used whenever required. This saves both time and space.
A Function is a self-contained block of statements that specifies one or more actions to be performed for the large program.
The main reasons for using functions are:
- to improve the readability of the code.
- improves the reusability of the code, the same function can be used in any program rather than writing the same code.
- debugging of the code would be easier if you use functions (errors are easy to be traced).
- reduces the size of the code, duplicate sets of statements are replaced by function calls.
A C program is made up of one or more functions. Functions are classified into 2 types, they are Library functions and User-defined functions.
Built–in functions are predefined functions, supplied along with the compiler and these can be used in any C program. They are also known as library functions and all these functions are available in the C library.
Some of the examples of library functions are scanf(), printf(), gets(), sqrt() and so on.
The functions defined by the users are called user-defined functions. The main() function is an example of a user-defined function because the code within the main() is written by the user.
Let us consider the following code.
#include
#include
void main() {
int a, b;
printf("Enter the value : ");
scanf("%d", &a);
b = sqrt(a);
printf("The square root of %d is : %d\n", a, b);
}
Output:
Enter the value : 25
The square root of 25 is : 5
Here main() is a user-defined function and scanf(), printf(), sqrt() are library functions.
The main() function invokes other functions within it and scanf(), printf(), sqrt() are invoked by the main() function.
Here main() is the calling function and the remaining are known as a called function.
A function that invokes another function is known as the calling function. A function that is invoked by another function is known as a called function. A called function may be a calling function for another function.
REFERENCES:
Happy Learning 🙂