Showing posts with label Recursion. Show all posts
Showing posts with label Recursion. Show all posts

C program to Towers of Hanoi by recursion

Below is C program to Towers of Hanoi by recursion .

Program:

/* Towers of Hanoi by recursion */

#include<stdio.h>
void toh(int,char,char,char);

int main()
{
 int n=3;
 toh(n,'A','B','C');
 return 0;
}

void toh(int n,char a,char b,char c)
{
 if(n==1)
  printf("\nMoved from %c to %c",a,c);
 else
 {
  toh(n-1,a,c,b);
  toh(1,a,' ',c);
  toh(n-1,b,a,c);
 }
}

C program to Decimal to Binary by Recursion

Below is C program to Decimal to Binary by Recursion.

Program:

/* Binary by recursion */

#include<stdio.h>
void binary(long);
int main()
{
 long n;
 printf("Type a value : ");
 scanf("%ld",&n);
 binary(n);
 return 0;
}

void binary(long n)
{
 if(n>1)
  binary(n/2);
 printf("%ld",n%2);
}

C program to GCD by Recursion

Below is C program to Sum of GCD by Recursion .

Program:

/* GCD by recursion */

#include<stdio.h>
int gcd(int,int);

int main()
{
 int a,b;
 printf("Type 2 values to find GCD :\n");
 scanf("%d %d",&a,&b);
 printf("GCD : %d",gcd(a,b));
 return 0;
}

int gcd(int m,int n)
{
 if(n>m) return gcd(n,m);
 if(n==0) return m;
 return gcd(n,m%n);
}

C program to Sum of digit by Recursion

Below is C program to Sum of digit by Recursion .

Program:

/* Sum of digit by recursion */

#include<stdio.h>
int sod(int);

int main()
{
 int i;
 printf(" Type any value : ");
 scanf("%d",&i);
 printf("Sum of digit : %d",sod(i));
 return 0;
}

int sod(int n)
{
 if(n<1)
  return 0;
 return(n%10+sod(n/10));
}


C program to Reverse a Number by Recursion

Below is C program to Reverse a Number by Recursion.

Program:

/* Reverse by Recursion */

#include<stdio.h>
int rev(int,int);

int main()
{
 int a;
 printf("Type a value : ");
 scanf("%d",&a);
 printf("Reverse: %d",rev(a,0));
 return 0;
}

int rev(int i,int r)  
{
 if(i > 0)  
  return rev(i/10,(r*10)+(i%10));  
 return r;  
}


C program to Fibonacci by Recursion

Below is C program to Fibonacci by Recursion .

Program:

/* Fibonacci by Recursion */

#include<stdio.h>
int fib(int);

int main()
{
 printf("Type any value : ");
 printf("\nNth value: %d",fib(getche()-'0'));
 return 0;
}

int fib(int n)
{
 if(n<=1)
  return n;
 return(fib(n-1)+fib(n-2));
}

C program to Power by Recursion

Below is C program to Power by Recursion .

Program:

/* Power by Recursion */

#include<stdio.h>
int pow(int,int);

int main()
{
 int i,j;
 printf("Type two values : \n");
 scanf("%d %d",&i,&j);
 
 printf("i pow j = %d",pow(i,j));
 return 0;
}

int pow(int i,int j)
{
 if(j==1)
  return i;
 return (i*pow(i,j-1));
}

C program to Factorial by Recursion

Below is C program to Factorial by Recursion .

Program:

/* Factorial by Recursion */

#include<stdio.h>
int fact(int);

int main()
{
  int n;
  printf("Type any value : ");
  scanf("%d",&n);
  n=fact(n);
  printf("\nFactorial : %d ",n);
  return 0;
}

int fact(int x)
{
  if(x==1)
    return(x);
  else
   x=x*fact(x-1);
}