Skip to content

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.
int add(int, int);

Function Call:

  • The statement that executes the function.
  • Transfers control to the function.
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 Declarations
int sum(int a, int b); // With arguments and with return value
void printstar(int n); // With arguments and without return value
int takenumber(); // Without arguments and with return value
void Star_pattern(); // Without arguments and without return value
int factorial(int n); // Recursion example
// Function Definitions
void 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 number
return i;
}
void Star_pattern() // No argument and no return value
{
int a = 3; // Predefined number
for (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 Function
int main()
{
int a = 9, b = 87;
int c = sum(a, b); // With arguments and return value
printf("The sum of %d and %d is %d \n", a, b, c);
printstar(5); // With arguments and without return value
int d = takenumber(); // Without arguments and with return value
printf("The predefined number taken is %d \n", d);
Star_pattern(); // No argument and no return value
int num = 5; // Predefined number for factorial
printf("Factorial of %d is %d \n", num, factorial(num));
return 0;
}