Write C programs that use both recursive and non-recursive functions
i. To find the factorial of a given integer.
ii. To find the greatest common divisor of two given integers.

Program Logic:

Factorial of a given number by using Recursive function
1. Start
2. Read a number N
3. Call a function factorial(N) by passing the values of N
4. If N=1 then it returns 1 as the factorial
5. Otherwise, it calculates the factorial f = N * factorial(N-1) by calling the same function again and again
6. Display the factorial of number N
7. Stop
Factorial of a given number by using Recursive function
#include<stdio.h>
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
void main()
{
int n,f;
printf("\n enter a no.: ");
scanf("%d",&n);
f=fact(n);
printf("\n factorial of %d is %d",n,f);
}

Factorial of a given number by using Non-Recursive function
1. Start
2. Read a number N
3. Initialize fact =1
4. Calculate fact = fact * N using a loop and decrement N value till N =1
5. Display the factorial of number N
6. Stop
Factorial of a given number by using Non-Recursive function
#include<stdio.h>
int fact(int n)
{
int f=1,i;
if((n==0)||(n==1))
return(1);
else
{
for(i=1;i<=n;i++)
f=f*i;
}
return(f);
}
void main()
{
int n;
printf("enter the number :");
scanf("%d",&n);
printf("factoria of number%d",fact(n));
}

GCD of a given two integer by using Recursive Function
1. Start
2. Read two numbers a and b
3. Call a function gcd (a, b) by passing the value of a and b
4. Check a != b, then
5. Check a > b then calculate gcd of two numbers by calling the function gcd(a-b, b)
6. Otherwise calculate gcd of two numbers by calling the function gcd(a, b-a)
7. Display the gcd of two numbers
8. Stop
GCD of a given two integer by using Recursive Function
#include<stdio.h>
int gcd(int m,int n)
{
if(n==0)
return m;
else
gcd(n,m%n);
}
void main()
{
int a,b,g,l;
printf("\n enter a: ");
scanf("%d",&a);
printf("\n enter b: ");
scanf("%d",&b);
g=gcd(a,b);
l=(a*b)/g;
printf("\n GCD of %d and %d : %d",a,b,g);
printf("\n LCM of %d and %d : %d",a,b,l);
}

GCD of a given two integer by using Non-Recursive Function
1. Start
2. Read two numbers a and b
3. Check if a != b then
4. Check if a >= b - 1 then set a = a – b otherwise set b = b – a
5. Display the gcd as the value of a.
6. Stop
GCD of a given two integer by using Non-Recursive Function
#include<stdio.h>
int gcd(int,int);
void main()
{
int a,b,x;
printf("\n enter a: ");
scanf("%d",&a);
printf("\n enter b: ");
scanf("%d",&b);;
x=gcd(a,b);
printf("G.C.D of %d and %d is %d",a,b,x);
}
int gcd(int a,int b)
{
int r;
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
return a;
}
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: