Archive for the ‘Recursion’ Category

/* Program to print the Pascal’s triangle recursively */

#include<stdio.h>

int pascal(int,int);
void space(int,int);

main()
{
int num,i,j;
printf(“\nEnter the no. of rows required: “);
scanf(“%d”,&num);
for(i=1;i<=num;i++)
{
space(num-i,3);
for(j=1;j<=i;j++)
{
printf(“%3d”,pascal(i,j));
space(1,3);
}
printf(“\n”);
}
}

int pascal(int row,int column)
{
if(column==0) // The 0th column element is assumed to 0
return 0;
else if(row==1&&column==1)
return 1;
else if(column>row) // assuming the element is zero (no of columns> no of rows)
return 0;
else
return (pascal(row-1,column-1)+pascal(row-1,column));
}

void space(int num,int mul) // for spaces in between elements
{
int i;
num*=mul;
for(i=0;i<num;i++)
printf(” “);
}

Advertisements

/* Program to find square of a number using recursion */

#include<stdio.h>
#include<math.h>

int square(int);

main()
{
int num,sq;
printf(“\nEnter an integer number: “);
scanf(“%d”,&num);
sq=square(abs(num));
printf(“\nSquare: %d\n\n”,sq);
}

int square(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
else
return square(n-1)+2*n-1;
}

/* Program to print fibonacci series using recursion */

#include<stdio.h>

int fibonacci(int);

main()
{
int i,n,fib;
printf(“\nEnter the no. of terms required: “);
scanf(“%d”,&n);
printf(“\nThe fibonacci series is ……….\n”);
for(i=1;i<=n;i++)
printf(“%d  “,fibonacci(i));
printf(“\n”);
}

int fibonacci(int n)
{
if(n==0||n==1)
return 0;
if(n==2)
return 1;
else
return fibonacci(n-1)+fibonacci(n-2);
}

/* Program to find factorial of a number using recursion */

#include<stdio.h>

long int factorial(int);

main()
{
int num;
long int fact;
printf(“\nEnter an integer number: “);
scanf(“%d”,&num);
fact=factorial(num);
printf(“\nFactorial: %ld\n\n”,fact);
}

long int factorial(int n)
{
if(n==0||n==1)
return 1;
else
return (n*factorial(n-1));
}