Functions & Recusion
Functions: A function is a block of code that performs a specific task. It simplifies programming by breaking a large program into smaller, reusable pieces. This improves readability, modularity, and code reuse.
Prototype:
- A declaration that specifies the function name, return type, and parameter types without the body.
- Tells the compiler about the function before its definition.
Syntax Example:
Section titled “Syntax Example:”int add(int, int);
Function Call:
- The statement that executes the function.
- Transfers control to the function.
Example:
Section titled “Example:”result = add(5, 3);
User-Defined Functions: A user-defined function is created by the programmer to perform a specific task.
- Provides code reusability and modularity.
- Unlike built-in functions, their logic is defined by the user, and no extra header file is required.
Types of User-Defined Functions:
- Function with no arguments and no return value
- Function with arguments and no return value
- Function with arguments and a return value
- Function with no arguments and a return value
Recursion: A recursive function is a function that calls itself.
- Useful for problems that can be broken into smaller sub-problems (e.g., factorial, Fibonacci).
- Not always efficient because it may cause stack overflow if used excessively.
#include <stdio.h>// Function Declarationsint sum(int a, int b); // With arguments and with return valuevoid printstar(int n); // With arguments and without return valueint takenumber(); // Without arguments and with return valuevoid Star_pattern(); // Without arguments and without return valueint factorial(int n); // Recursion example// Function Definitionsvoid printstar(int n) // With arguments and without return value{for (int i = 0; i < n; i++){ printf("*\n");}}
int takenumber() // Without arguments and with return value{int i = 12; // Predefined numberreturn i;}
void Star_pattern() // No argument and no return value{int a = 3; // Predefined numberfor (int i = 0; i < a; i++){ printf("*\n");}}int sum(int a, int b) // With arguments and with return value{return a + b;}int factorial(int n) // Recursion example{if (n == 0 || n == 1) return 1;else return n * factorial(n - 1); // Recursive call}// Main Functionint main(){int a = 9, b = 87;int c = sum(a, b); // With arguments and return valueprintf("The sum of %d and %d is %d \n", a, b, c);printstar(5); // With arguments and without return valueint d = takenumber(); // Without arguments and with return valueprintf("The predefined number taken is %d \n", d);Star_pattern(); // No argument and no return valueint num = 5; // Predefined number for factorialprintf("Factorial of %d is %d \n", num, factorial(num));
return 0;}
The sum of 9 and 87 is 96*****The predefined number taken is 12***Factorial of 5 is 120