Write C programs that use both recursive and non-recursive functions
i. To print Fibonacci series.
ii. To solve towers of Hanoi problem.

Program Code:
To print Fibonacci Series using Recursive function
#include<stdio.h>
void fib(int);
void main()
{
int n;
printf("\n enter the limit of the series: ");
scanf("%d",&n);
fib(n);
}
void fib(int n)
{
int x=0,y=1,z,i;
printf("%5d%5d",x,y);
for(i=2;i<n;i++)
{
z=x+y;
printf("%5d",z);
x=y;
y=z;
}
}

Fibonacci Series using Non-Recursive function
#include<stdio.h>
int fibo(int,int);
void main()
{
int n,x,i;
printf("\n enter the no. of terms: ");
scanf("%d",&n);
printf("\n the fibonacci sequence is: ");
for(i=0;i<=n;i++)
{
x=fib(i);
printf("%5d",x);
}
}
int fib(int n)
{
if(n==0 || n==1)
return n;
else
return fib(n-1)+fib(n- 2);
}


Towers of Hanoi problem using Non-Recursive function
#include<stdio.h>
void Hanoinonrecursion(int num,char sndl,char indl,char dndl)
{
char stkn[100],stksndl[100],stkindl[100],stkdndl[100],stkadd[100],temp;
int top,add;
top=NULL;
one:
if(num==1)
{
printf("\n Move top disk from needle %c to needle %c",sndl,dndl);
goto four;
}
two:
top=top+1;
stkn[top]=num;
stksndl[top]=sndl;
stkindl[top]=indl;
stkdndl[top]=dndl;
stkadd[top]=3;
num=num-1;
sndl=sndl;
temp=indl;
indl=dndl;
dndl=temp;
goto one;
three:
printf("\n Move top disk from needle %c to needle %c",sndl,dndl);
top=top+1;
stkn[top]=num;
stksndl[top]=sndl;
stkindl[top]=indl;
stkdndl[top]=dndl;
stkadd[top]=5;
num=num-1;
temp=sndl;
sndl=indl;
indl=temp;
dndl=dndl;
goto one;
four:
if(top==NULL)
return;
num=stkn[top];
sndl=stksndl[top];
indl=stkindl[top];
dndl=stkdndl[top];
add=stkadd[top];
top=top-1;
if(add==3)
goto three;
else if(add==5)
goto four;
}
void main()
{
int no;
printf("Enter the no. of diss to be transferred:");
scanf("%d",&no);
if(no<1)
printf("\n There's nothing to move");
else
printf("\n nonrecursive");
Hanoinonrecursion(no,'A','B','C');
}

To solve Towers of Hanoi problem using Recursive function
#include<stdio.h>
void Hanoirecursion(int num,char ndl1,char ndl2,char ndl3)
{
if(num==1)
{
printf("Move top disk from needle %c to needle %c",ndl1,ndl2);
return;
}
Hanoirecursion(num-1,ndl1,ndl3,ndl2);
printf("Move top dis from needle %c to needlle %c",ndl1,ndl2);
Hanoirecursion(num-1,ndl3,ndl2,ndl1);
}
void main()
{
int no;
printf("Enter the no. of disk to be transferred:");
scanf("%d",&no);
if(no<1)
printf("\n There's nothing to move");
else
printf("\n recursive");
Hanoirecursion(no,'A','B','C');
}
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: