Definition:
‘C‘ allows user to define functions according to your need. Each ‘function‘ has Call and Body. It provides code reusability and modularity to our program. These ‘Functions‘ are known as User-Defined Function.
Syntax:
return_type function_name(parameter_type1 parameter_name1, parameter_type2 parameter_name2, …) {
// Function body
// Statements and calculations
return value; // Optional return statement
}
- return_type: Specifies the data type of the value the function returns. It can be int, float, void, etc.
- function_name: The name of the function, which is used to call it in the program.
- parameter_type1, parameter_type2, …: Specifies the data type of the input parameters the function accepts.
- parameter_name1, parameter_name2, …: The names of the parameters, which are used within the function to refer to the passed values.
How to create User-Defined Function:
Step 1: Function Definition
Define your user-defined function. This involves specifying the function name, return type, and parameters.
Example:
#include <stdio.h>
// Function definition
int add(int a, int b) {
int result = a + b;
return result;
}
Step 2: Function Call
Call your function from the main
function or any other part of your program where you want the function’s code to be executed. Pass the required arguments, if any.
Example:
int main() {
// Function call
int sum = add(3, 5);// Display the result
printf(“The sum is: %dn”, sum);return 0;
}
Step 3: Compilation
Make sure to include the function’s source code (either in the same file or through a header file) and compile your program. If the function is defined in a separate file, link it during compilation.
Step 4: Run the Program
Execute your compiled program. You should see the result of the function call in the output.
Complete Program:
#include <stdio.h>// Function definitionint multiply(int a, int b, int c) {int result = a * b * c;return result;}// Main functionint main() {// Function callint multi = multiply(3, 5, 6);// Display the resultprintf(“The result is: %dn”, multi);return 0;}
Output:
The result is: 90
Characteristics Of User-Defined Function: