Saturday 8 May 2021

Recursion concept in C with example program

 A recursion is a repetitive process where a function calls it self. Every recursive function has two major cases: base case and general case.

Base case: In this case the problem is simple enough to be solved directly without marking any further call to the same function.

General case: Int this case, first the problem at hand is divided into simple sub parts. second the function calls it self with sub parts of the problem obtained in the first step. Third the result is obtained by combining the solutions of simple sub parts.


 

The following are the rules for designing recursive function

  1. Determine the base case 
  2. Determine the general case
  3. Combine the base case and general case into a function.

Here is an example how to calculate the factorial of a number using recursion.


As the process solves each general case in turn the process can solve higher general case until it finally solves the most general case. That is the original problem.

Example: C program to find factorial of a given number using recursion 

int fact(int n);
int main()
{
 int m,f;
printf(“ enter a number”);
scanf(“%d”,&n);
f-fact(n);
printf(“ factorial of given number is=%d”,f);
return 0;
}
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1));
}

Example: C program to find GCD of two numbers using recursion 

int GCD(int a, int b);
int main()
{
int a,b;
printf(“ enter a,b values”);
scanf(“%d%d”,&a,&b);
int result=GCD(a,b);
printf(“ GCD of two numbers is %d”,result);
return 0;
}

int GCD(int a, int b)
{
 int rem;
 rem=a%b;
if(rem==0)
retrun b;
else
return(GCD(b,rem));
}

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top