A function in C is a self-contained block of code designed to perform a specific task. Functions are used to modularize programs, making them more organized, readable, and reusable .
Types of Functions in C:
Library Functions (Built-in Functions).
These are pre-defined functions provided as part of the C standard library. Their declarations are found in header files (e.g., stdio.h for input/output functions like printf() and scanf(), math.h for mathematical functions like sqrt(), pow(), etc.). To use them, you typically need to include the relevant header file in your program.
User Defined Functions .
These are functions created by the programmer to perform specific tasks tailored to their program's needs. They promote code reusability and help in breaking down complex problems into smaller, more manageable sub-problems. User-defined functions involve three main parts:
Function Declaration (Prototype): Declares the function's return type, name, and the types of its parameters.
Function Definition: Contains the actual code that the function executes.
Function Call: Invokes the function to execute its code.
#include <stdio.h>
#include <conio.h>
// Function declaration (prototype)
int add(int a, int b);
// Main function
int main() {
int x = 5, y = 10, result;
result = add(x, y); // Function call
printf("Sum = %d\n", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
int add(int a, int b) → This is a user-defined function.
add(x, y) → The function is called from main().
return a + b; → It returns the sum to the caller.
Actual Parameters
The real values or variables passed to the function during the call.
.
Formal Parameters
The variables declared in the function definition that receive the actual values.
Example:
#include <stdio.h>
#include<conio.h>
// Function declaration
void greet(char name[]); // 'name' is a formal parameter
int main() {
greet("Vikas Dhiman"); // "Vikas Dhiman" is the actual parameter
return 0;
}
// Function definition
void greet(char name[]) {
printf("Hello, %s!\n", name);
}
In C, there are two main techniques to pass parameters to functions:
Call by Value (Pass by Value) : -
A copy of the actual parameter is passed to the function.
Changes made to the parameter do not affect the original variable.
Call by Reference (Pass by Reference) : -
The address of the actual parameter is passed.
Changes made inside the function affect the original variable.
Program of Call by Value
#include<stdio.h>
#include<conio.