Functions in C
1. Definition of Function
A function is a self-contained block of code that performs a specific task. Functions are used to
divide a large program into smaller, manageable, and reusable sections.
2. Types of Functions in C
• Library Functions: Predefined in C libraries (e.g., printf(), scanf()).
• User-Defined Functions: Functions created by the user to perform specific tasks.
3. Advantages of Functions
• Code reusability
• Easier debugging and maintenance
• Improved code clarity and readability
• Facilitates code testing
4. Categories of User-Defined Functions
• Functions without arguments and without return values
• Functions without arguments and with return values
• Functions with arguments and without return values
• Functions with arguments and with return values
5. Function Declaration, Definition, and Calling
• Declaration: Function prototype, specifying the function name, return type, and parameters.
int add(int, int);
• Definition: The actual implementation of the function.
int add(int a, int b) {
return a + b;
• Calling: Executing the function using its name.
int result = add(5, 10);
6. Function Call Types
• Call by Value: Copies the value of actual parameters into formal parameters.
o Example:
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
• Call by Reference: Passes the address of actual parameters, allowing changes to be reflected
outside the function.
o Example:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
7. Formal vs. Actual Parameters
• Formal Parameters: Variables declared in the function definition.
• Actual Parameters: Values or variables passed to the function during the function call.
8. Recursive Functions
A recursive function is a function that calls itself directly or indirectly.
• Example:
int factorial(int n) {
if (n == 0) return 1;
else return n * factorial(n - 1);
9. Example Programs
1. Area of a Sphere
#include <stdio.h>
#define PI 3.14159
float sphereArea(float radius) {
return 4 * PI * radius * radius;
int main() {
float r;
printf("Enter the radius of the sphere: ");
scanf("%f", &r);
printf("Area of the sphere: %.2f", sphereArea(r));
return 0;
2. Prime Number Check
#include <stdio.h>
int isPrime(int num) {
if (num <= 1) return 0;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) return 0;
return 1;
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (isPrime(n))
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
3. Area of a Rectangle
#include <stdio.h>
int rectangleArea(int length, int width) {
return length * width;
int main() {
int l, w;
printf("Enter length and width of the rectangle: ");
scanf("%d %d", &l, &w);
printf("Area of the rectangle: %d", rectangleArea(l, w));
return 0;