Goal: Encapsulate code into named, callable blocks. This is the key to clean, modular programs.
return_type function_name(parameter_list) {
// body
return value; // if return_type is not 'void'
}
#include <stdio.h>
int max(int a, int b) {
if (a > b) return a;
else return b;
}
int main() {
int x = 10, y = 20;
printf("Max: %d\n", max(x, y));
return 0;
}
void greet(void) {
printf("Hello, world!\n");
}
Write a function int square(int n) that returns n*n. Test it in main().
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
printf("%d\n", square(5)); // 25
return 0;
}
Write a function int isEven(int n) that returns 1 if n is even, 0 otherwise. Use it to print "even" or "odd" for user input.
#include <stdio.h>
int isEven(int n) {
return (n % 2 == 0);
}
int main() {
int num;
printf("Enter number: ");
scanf("%d", &num);
if (isEven(num)) printf("even\n");
else printf("odd\n");
return 0;
}
Write a function int factorial(int n) that computes n! using a loop. Call it from main() for n = 5 and n = 7.
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
printf("5! = %d\n", factorial(5)); // 120
printf("7! = %d\n", factorial(7)); // 5040
return 0;
}