Recursion in C Language | Programs of recursion in C Language

You must first complete Introduction to function in C Language before viewing this Lesson

Recursion in C Language | Programs of recursion in C Language

Function repeatedly calling itself is called recursion. We must specify some condition to stop recursion  otherwise function may run infinitely.

 Program using recursion to find factorial of a number .
#include<stdio.h>
int factorial(int no)
{
  if(no==1||no==0)
    return(1);
  else
    return(no*factorial(no-1));
}
int main()
{
  int f1,n;
  printf("\nEnter a number");
  scanf("%d",&n);
  f1=factorial(n);
  printf("\nFactorial =%d",f1);
  return(0);
}
Output
Enter a number=4
Factorial =24
Description
Suppose n is  4

Program will execute as follows

f = factorial (4); will be evaluated.

Inside function, return(no*factorial(no-1)); is executed.

This statement again calls factorial() function with value n-1  i.e. 4*fact(4-1);

This process continues until value of no is equal to 1 or 0 and when no is equal to 1 it returns 1 and execution of this function stops. Process  is as f0llows

f = 4* fact (3-1);
f =4*3* fact (3-1);
f = 4*3*2*fact (2-1);
f= 4*3*2*1;
f = 24;

Nesting of functions in C Language

It is the process in which a function calls another function.

 Program for nesting of function.
#include<stdio.h>
void msg()
{
  printf(”\nHello”);
}
void disp()
{
  printf(”Welcome”);
  msg();       /*Function msg() nested within function show().*/
}
int main()
{
  disp();
return(0);
}
Output
Welcome
Hello

Spread the love
Lesson tags: conditions of recursion, nesting of function in c, Nesting of functions in C Language, procedure of recursion in c, program to find factorial of a number using recursion in c, program to print fibonacci series using recursion in c, recursion in c
Back to: C Programming Language
Spread the love