A function is a block of code that performs a specific task. Functions help us reuse code, divide logic into manageable parts, and improve readability.
printf(), scanf())return_type function_name(parameters) {
// body of the function
}
#include <stdio.h>
void greet() {
printf("Hello, welcome to C programming!\n");
}
int main() {
greet(); // Function call
return 0;
}
Output: Hello, welcome to C programming!
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
printf("Sum is %d", result);
return 0;
}
Output: Sum is 8
Example:
// Function with parameters
void displayMessage(char name[]) {
printf("Hello %s!\n", name);
}
int main() {
// "John" is the argument
displayMessage("John");
return 0;
}
Output: Hello John!
int add(int a, int b)void greet(char name[])int getValue()void display()Recursion is the process in which a function calls itself either directly or indirectly to solve a problem.
int factorial(int n) {
if (n == 0)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive call
}
int main() {
int result = factorial(5);
printf("Factorial of 5 is %d", result);
return 0;
}
Output: Factorial of 5 is 120