🔧 Functions in C Language
Definition, Types, Examples
🔹 What is a Function?A function in C is a block of code that performs a specific task. It helps in code reusability, modularity, and readability.
✅ Advantages of Functions
- Reduces code repetition
- Improves readability
- Easy to debug and maintain
- Supports modular programming
📌 Basic Structure of a Function
return_type function_name(parameters) {
// function body
return value;
}
📘 Example of a Simple Function
#include <stdio.h>
void display() {
printf("Hello C");
}
int main() {
display();
return 0;
}
📂 Types of Functions in C
Functions in C are mainly classified into two types:
- Library Functions
- User-Defined Functions
1️⃣ Library Functions
Definition:
Library functions are predefined functions provided by C standard libraries.
| Function | Header File |
|---|---|
| printf() | stdio.h |
| scanf() | stdio.h |
| strlen() | string.h |
| sqrt() | math.h |
#include <stdio.h>
#include <math.h>
int main() {
printf("%.2f", sqrt(16));
return 0;
}
2️⃣ User-Defined Functions
Definition:
Functions created by the programmer to perform specific tasks.
📌 Types of User-Defined Functions
(Based on Arguments and Return Value)
🔹 1. No Arguments and No Return Value
#include <stdio.h>
void greet() {
printf("Welcome to C");
}
int main() {
greet();
return 0;
}
🔹 2. Arguments and No Return Value
#include <stdio.h>
void add(int a, int b) {
printf("Sum = %d", a + b);
}
int main() {
add(5, 3);
return 0;
}
🔹 3. No Arguments and Return Value
#include <stdio.h>
int getNumber() {
return 10;
}
int main() {
int x = getNumber();
printf("%d", x);
return 0;
}
🔹 4. Arguments and Return Value
#include <stdio.h>
int multiply(int a, int b) {
return a * b;
}
int main() {
printf("%d", multiply(4, 5));
return 0;
}
📘 Function Declaration, Definition, and Call
1. Function Declaration (Prototype)
int add(int, int);
int add(int a, int b) {
return a + b;
}
add(2, 3);
📚 FAQs on Functions in C
Q1. What is a function?
A function is a reusable block of code that performs a specific task.
Q2. What are library functions?
Predefined functions provided by C libraries like printf() and scanf().
Q3. What are user-defined functions?
Functions created by programmers to perform their own tasks.
Q4. Why use functions in C?
To reduce code duplication and improve program structure.
Q5. Can a function return multiple values?
Directly no, but it can be done using pointers or structures.
🔑 Key Points to Remember
- Every C program has at least one function: main()
- Functions improve modularity
- Arguments are optional
- Return type can be void