Sunday, November 16, 2008

recursion-1

Write a recursive C program for
a] Searching an element on a given list of integers using binary search method.

#include"stdio.h" /*PREPROCESSOR DIRECTIVES*/
#include"conio.h"
int binary_search(int,int a[],int,int); /*FUNCTION PROTOTYPE*/
void main() /*MAIN FUNCTION*/
{
int item,i,n,pos; /*VARIABLE DECLARATION*/
int *a;
clrscr();
printf("\n Enter the no. of elements:\n");
scanf("%d",&n);
a=(int *)malloc(sizeof(int) *n);
printf("\nEnter the elements:\n");
for(i=0;i< pos="binary_search(item,a,0,n-1);" pos="="">high)
return-1;
mid=(low+high)/2;
if(item==a[mid])
return mid;
else
{
if(item< style="font-weight: bold;">

b] Solving the tower of Hanoi problem.

#include"stdio.h"
#include"conio.h"
void towers(int,char,char,char);
int count=0;
main()
{
int n;
clrscr();
printf("\n Enter the no of disks:");
scanf("%d",&n);
towers(n,'a','c','b');
printf("\nTotal no of moves required is %d",count);
getch();
}

void towers(int n,char frompeg,char topeg,char temppeg)
{
if(n==1)
{
printf("Move disk 1 from peg %c to peg %c\n",frompeg,topeg);
count++;
return;
}
towers(n-1,frompeg,temppeg,topeg);
count++;
printf("Move disk 1 from peg %c to peg %c\n",frompeg,topeg);
towers(n-1,temppeg,topeg,frompeg);
}

No comments:

Post a Comment