Saturday, 7 September 2013

SOME SIMPLE PROGRAMS USING RECURSION



Develop recursive programs for the following questions:
Question # 1
Display the following series using recursion:
1, 2, 3, 4, 5, 6, 7, 8……20
/***********************************************************************************/
#include<stdio.h>
#include<conio.h>
void print(int);
int main()
{
                print(20);
                getch();
                return 0;
}

void print(int n)
{
                if(n==0)
                                return;
                print(n-1);
                printf("%d\t",n);
}
/***********************************************************************************/



Question # 2
Display the following series using recursion:
20 , 19 , 18 , 17 , 16 …. 2 , 1
/***********************************************************************************/
#include<stdio.h>
#include<conio.h>
void print(int);
int main()
{
                print(20);
                getch();
                return 0;
}

void print(int n)
{
                if(n==0)
                                return;
                printf("%d\t",n);
                print(n-1);
}
/***********************************************************************************/




Question # 3
Calculate the factorial of a given number using recursion.
/***********************************************************************************/
#include<stdio.h>
#include<conio.h>
long factorial(int);
int main()
{
                int num;
                clrscr();
                printf("Enter the number : ");
                scanf("%d",&num);
                printf("%ld",factorial(num));
                getch();
                return 0;
}

long factorial(int n)
{
                long fact;
                if(n==0)
                                return 1;

                fact=factorial(n-1)*n;
                return fact;
}
/***********************************************************************************/

No comments:

Post a Comment