Functions in C
A function is a named block of code that performs a specific task. Functions make code reusable, organized, and easier to debug. The golden rule: Do One Thing Well.
Parts of a Function
c
// Return type Name Parameters
// ↓ ↓ ↓
int add (int a, int b)
{
return a + b; // return value
}Complete Functions Example
c
#include <stdio.h>
// ── Function DECLARATIONS (prototypes) ───────────
void greet(char name[]); // returns nothing
int add(int a, int b); // returns int
float average(int arr[], int n); // returns float
int isEven(int n); // returns 0 or 1
// ── main() ───────────────────────────────────────
int main() {
greet("Arjun");
int result = add(15, 27);
printf("15 + 27 = %d\n", result);
int marks[] = {85, 92, 78, 95, 88};
float avg = average(marks, 5);
printf("Average: %.1f\n", avg);
printf("10 is %s\n", isEven(10) ? "EVEN" : "ODD");
printf("7 is %s\n", isEven(7) ? "EVEN" : "ODD");
return 0;
}
// ── Function DEFINITIONS ─────────────────────────
void greet(char name[]) {
printf("Hello, %s! Welcome to C!\n", name);
}
int add(int a, int b) {
return a + b;
}
float average(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) sum += arr[i];
return (float) sum / n;
}
int isEven(int n) {
return (n % 2 == 0); // returns 1 if even, 0 if odd
}▶ Output
Hello, Arjun! Welcome to C! 15 + 27 = 42 Average: 87.6 10 is EVEN 7 is ODD
Why Use Functions?
- Reusability — write once, use many times
- Modularity — each function does one job
- Readability — code reads like English sentences
- Easy debugging — test each function independently
- Collaboration — team members work on different functions
📌 Note: In C, you must declare or define a function BEFORE calling it. That's why we write prototypes at the top.