Functions in C
As programs grow larger, writing everything inside main()
becomes confusing and hard to manage.
To solve this problem, C provides functions. Functions help us divide a program into smaller, manageable parts.
What Is a Function?
A function is a block of code that performs a specific task.
Once written, a function can be called multiple times from different parts of the program.
This improves:
- Code readability
- Reusability
- Maintainability
Why Functions Are Important
Think of functions like real-life tasks:
- Cooking rice
- Sending an email
- Calculating salary
Each task is done separately and reused when needed. Functions work the same way in programming.
Types of Functions in C
There are two main types of functions:
- Library Functions – provided by C
- User-Defined Functions – created by programmer
Examples of library functions:
printf()scanf()strlen()
Structure of a User-Defined Function
A function has three main parts:
- Function declaration
- Function definition
- Function call
Function Declaration
The declaration tells the compiler about:
- Function name
- Return type
- Parameters
int add(int, int);
Function Definition
The definition contains the actual code of the function.
int add(int a, int b) {
return a + b;
}
Function Call
A function is executed when it is called.
sum = add(10, 20);
Complete Example: Function to Add Two Numbers
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int result;
result = add(5, 7);
printf("Sum = %d", result);
return 0;
}
Here:
- The function
add()performs addition main()calls the function- The returned value is printed
Functions With and Without Return Value
Functions can be:
- With return value – returns data
- Without return value – uses
void
void greet() {
printf("Welcome to C Programming");
}
Real-World Thinking
Functions help teams work efficiently.
- One person writes a function
- Others reuse it
- Errors are fixed in one place
This is why functions are the backbone of large software systems.
Mini Practice
- Create a function to find square of a number
- Create a function to check even or odd
- Create a function to find maximum of two numbers
Quick Quiz
Q1. What is a function?
A function is a block of code that performs a specific task.
Q2. Why are functions used?
To improve reusability, readability, and maintenance.
Q3. What keyword is used for no return value?
void
Q4. Where does program execution start?
main() function
Q5. Can a function be called multiple times?
Yes, a function can be reused multiple times.