PROGRAM - 14
a) Write a program to perform the following using recursion
i) To find the factorial of a given integer.
ii) To find the GCD(Greatest Common Divisor) of two given integers.
iii) To solve the towers of Hanoi Problem.
Program to find the factorial of a given integer:
#include<stdio.h>
#include<conio.h>
main()
{
int n, res;
int fact(int);
clrscr();
printf("enter a number:");
scanf("%d",&n);
res=fact(n);
printf("the factorial of %d is %d",n,res);
getch();
}
int fact(int n)
{
int res;
if(n==1)
return 1;
else
{
res=n*fact(n-1);
return res;
}
}
/*
INPUT: enter a number:7
OUTPUT: the factorial of 7 is 5040
*/
Program to find the gcd of two given integers:
#include<stdio.h>
#include<conio.h>
main()
{
int m,n;
void gcd(int,int);
clrscr();
printf("enter the values for m and n");
scanf("%d %d",&m,&n);
gcd(m,n);
getch();
}
void gcd(int m,int n)
{
int a,b,r;
a=m;
b=n;
r=m%n;
while(r!=0)
{
m=n;
n=r;
r=m%n;
}
printf("gcd(%d,%d)=%d",a,b,n);
getch();
}
/*
INPUT: enter the values for m and n 23 41
OUTPUT: gcd(23,41)=1 */
Program to solve the towers of hanoi problem:
#include<stdio.h>
#include<conio.h>
main()
{
int nvalue;
char snvalue='L',invalue='C',dnvalue='R';
void hanoi(int,char,char,char);
clrscr();
printf("enter number of disks:");
scanf("%d",&nvalue);
printf("\ntowers of hanoi problem with %d disks"
,nvalue);
hanoi(nvalue,snvalue,invalue,dnvalue);
getch();
}
void hanoi(int n,char snd,char ind,char dnd)
{
if(n!=0)
{
hanoi(n-1,snd,dnd,ind);
printf("\nmove disk %d from %c to %c \n"
,n,snd,dnd);
hanoi(n-1,ind,snd,dnd);
}
}
/*
INPUT:enter number of disks:3
OUTPUT:
towers of hanoi problem with 3 disks
move disk 1 from L to R
move disk 2 from L to C
move disk 1 from R to C
move disk 3 from L to R
move disk 1 from C to L
move disk 2 from C to R
move disk 1 from L to R
*/
No comments:
Post a Comment