Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Tuesday, 10 January 2012

C program to print the Fibonacci series using recursion



#include<stdio.h>
void fib(int);
main()
{
int z;
printf("Enter the limit\n");
scanf("%d",&z);
printf("Fibonacci sequence\n");
fib(z);
}
void fib(int z)
{
static int a,b;
int c;
if(z<2)
{
a=0;
b=1;
}
else
{
fib(z-1);
c=b;
b=a+b;
a=c;
}
printf("\n%d",a);
}




Wednesday, 28 December 2011

C program to find the factorial of a number using recursion



#include<stdio.h>
int fact(int);
main()
{
int n,temp;
printf("Enter a number\n");
scanf("%d",&n);
if(n>=0)
{
temp=fact(n);
printf("Factorial is %d",temp);
}
else
printf("Cannot find the factorial");
}

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



Tuesday, 27 December 2011

C program to find the determinant and inverse of two matrices using recursion



#include<stdio.h>
#include<math.h>
float detrm(float[25][25],float);
void cofact(float[25][25],float);
void trans(float[25][25],float[25][25],float);
main()
{
float a[25][25],k,d;
int i,j;
printf("Enter the order of the matrix\n");
scanf("%f",&k);
printf("Enter the elements of the matrix\n");
for(i=0;i<k;i++)
{
for(j=0;j<k;j++)
{
scanf("%f",&a[i][j]);
}
}
d=detrm(a,k);
printf("Deteminant = %f",d);
if(d==0)
printf("\nMatrix is not inversible\n");
else
cofact(a,k);
}

float detrm(float a[25][25],float k)
{
float s=1,det=0,b[25][25];
int i,j,m,n,c;
if(k==1)
{
return(a[0][0]);
}
else
{
det=0;
for(c=0;c<k;c++)
{
m=0;
n=0;
for(i=0;i<k;i++)
{
for(j=0;j<k;j++)
{
b[i][j]=0;
if(i!=0&&j!=c)
{
b[m][n]=a[i][j];
if(n<(k-2))
n++;
else
{
n=0;
m++;
}
}
}
}
det=det+s*(a[0][c]*detrm(b,k-1));
s=-1*s;
}
}
return(det);
}

void cofact(float num[25][25],float f)
{
float b[25][25],fac[25][25];
int p,q,m,n,i,j;
for(q=0;q<f;q++)
{
for(p=0;p<f;p++)
{
m=0;
n=0;
for(i=0;i<f;i++)
{
for(j=0;j<f;j++)
{
b[i][j]=0;
if(i!=q&&j!=p)
{
b[m][n]=num[i][j];
if(n<(f-2))
n++;
else
{
n=0;
m++;
}
}
}
}
fac[q][p]=pow(-1,q+p)*detrm(b,f-1);
}
}
trans(num,fac,f);
}

void trans(float num[25][25],float fac[25][25],float r)
{
int i,j;
float b[25][25],inv[25][25],d;
for(i=0;i<r;i++)
{
for(j=0;j<r;j++)
{
b[i][j]=fac[j][i];
}
}
d=detrm(num,r);
inv[i][j]=0;
for(i=0;i<r;i++)
{
for(j=0;j<r;j++)
{
inv[i][j]=b[i][j]/d;
}
}
printf("\nThe inverse of the matrix :\n");
for(i=0;i<r;i++)
{
for(j=0;j<r;j++)
{
printf("\t%f",inv[i][j]);
}
printf("\n");
}
}




Monday, 12 December 2011

C program to find the permutation of a given string using recursion



#include<stdio.h>
#include<string.h>

void perm(char * , int , int );
char temp,str[20];
int l;
int main()
{
printf("Enter the string : ");
scanf("%s",str);
printf("The permutation is\n");
l=strlen(str);
perm(str,0,l);
}

void perm(char *str,const int strt, int len)
{
int i,j;
for(i=strt;i<len-1;++i)
for(j=i+1;j<len;++j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
perm(str , i+1 ,len);
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
printf("%s\n",str);
}