Function and Recursion in C language

Master functions and recursion in C! Write efficient, reusable code with functions & explore recursion for optimized problem-solving

Function and Recursion in C language
Function and Recursion in C language

Uses of Function and Recursion 

When sometime Our program bigger in size and it becomes difficult to know what the program does. 

To solve this problem, Functions or Recursion are used.

Functions allow us to break a program into smaller, manageable parts, while recursion enables solving complex problems using a divide-and-conquer approach.
  • The strengths of C language is "C Function".
  • There are easy to define and use.
  • A good coder use function in mostly program.

What is Function ? 

A function is a block of code which performs a specific task and programmer reused a code any number of times.

Declaration 

function type function name(parameter list)    
// function header
{
local variable declaration; 
executable statement_1;
executable statement_2;
//Body 
return statement;
}

Example: 
#include<stdio.h>
//int sum(int, int);         /* function prototype declaration */ 
int sum(int x ,int y){    /* function call */ 
printf("%d\n",x+y);
return x+y;
}
int main(){ 
   sum(5,6);        /* function definition */ 
   sum(7,8);
   sum(7,88);
    return 0;

Output: 
11
15
95

Recursion 

Recursion is a process in which a function calls itself directly or indirectly to solve a problem. It is  a continue to call it self until it rich a base case. Which a condition where the recursion stop.

Declaration 

return type function name(parameters) {
if (base condition) {
    return some value; // Base Case
else {
    return function name(modified parameters); // Recursive Call
    }
}

Example 
#include<stdio.h>
int factorial(int n){
    if (n==0|| n==1){
return 1;
    }
    return factorial (n-1)*n;
}
int main(){ 
    int n = 5;
    printf("%d",factorial(n));
    return 0;
}
Output: 120

Post a Comment