Functions
Functions are an essential part of any programming language, including C. In C programming language, a function is a self-contained block of statements that perform some sort of coherent task. Functions are used to break down a program into smaller, manageable parts and can be called repeatedly. There are two types of functions in C programming language - predefined functions and user-defined functions.
Predefined functions or inbuilt functions are functions that are already defined in C header files such as stdio.h, stdlib.h, math.h, conio.h, etc. Examples of predefined functions in C include scanf(), printf(), gets(), puts(), etc. These functions are readily available for use in C programs.
On the other hand, user-defined functions are functions created by C programmers. These functions are declared and defined by the programmer and can be called within the program. User-defined functions help to make code reusable, modular, and easy to read.
Let's take a look at some examples of user-defined functions in C programming language.
Example 1
In this example, we are declaring and defining a function called "display". This function does not take any arguments, and its return type is int. Inside the function, we are printing a message to the console and returning the value 5. In the main function, we are calling the "display" function and storing its return value in the variable "a". Finally, we are printing the value of "a" to the console.
copy
#include <stdio.h>
// Function declaration
int display();
// Main function
int main()
{
int a;
// Function call
a = display();
printf("%d", a);
return 0;
}
// Function definition
int display()
{
printf("I am a function\n");
return 5;
}
Output
I am a function 5
Example 2
In this example, we are declaring and defining a function called "display" that takes two integer arguments and returns an integer value. Inside the function, we are adding the two integer arguments and returning their sum. In the main function, we are calling the "display" function with two integer arguments and storing its return value in the variable "a". Finally, we are printing the value of "a" to the console.
copy
#include <stdio.h>
// Function declaration
int display(int, int);
// Main function
int main()
{
int a;
// Function call
a = display(5, 6);
printf("%d", a);
return 0;
}
// Function definition
int display(int a, int b)
{
int c;
c = a + b;
return c;
}
Output
11
Now, let's create a function to display the multiplication of two numbers.
copy
#include <stdio.h>
// Function to multiply two numbers
int multy(int a, int b)
{
return a * b;
}
// Main function
int main()
{
int x = 5;
int y = 8;
printf("%d", multy(x, y));
return 0;
}
Output
40
In conclusion, functions are a crucial part of any programming language, including C. They help to make code reusable, modular, and easy to read.