Functions and Recursion in C

Functions in C

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.

Why Use Functions?

Types of Functions:

Syntax of a Function:

return_type function_name(parameters) {
  // body of the function
}

Example: Simple 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!

Function with Return Value

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

Parameters vs Arguments

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!

Types of Functions by Arguments and Return:

Recursion in C

Know more in Detail Know more in Detail 2

Recursion is the process in which a function calls itself either directly or indirectly to solve a problem.

Important Concepts:

Example: Factorial using Recursion

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

Advantages of Recursion:

Disadvantages of Recursion:

References