Sei sulla pagina 1di 8

IT18111 – PROGRAMMING FOR PROBLEM SOLVING LABORATORY

EX.NO:8
DATE:
C PROGRAMMING USING RECURSION

QUESTION: A) Write a C program to calculate the factorial of given number using


recursion.

AIM:

ALGORITHM:

Roll Number: Page No.:


PROGRAM:
#include<stdio.h>
int fact(int n)
{
int f;
if(n<=1)
return 1;
else
{
f=n*fact(n-1);
return f;
}
}
void main()
{
int n,fac;
printf("Enter the number:");
scanf("%d",&n);
fac=fact(n);
printf("result:%d\n",f);
}

SAMPLE INPUT AND OUTPUT:


[cs19085@cslinux svce]$ ./a.out
Enter the numbers:4
result:8
[cs19085@cslinux svce]$

RESULT:

Roll Number: Page No.:


QUESTION: B) Write a C program to compute sum of first N natural numbers using
recursion.

AIM:

ALGORITHM:

Roll Number: Page No.:


PROGRAM:
#include<stdio.h>
int sum(int n)
{
int f;
if(n==1)
return 1;
else
{
f=n+sum(n-1);
return f;
}
}
void main()
{
int n,f;
printf("Enter the number:");
scanf("%d",&n);
f=sum(n);
printf("Result:%d\n",f);
}
SAMPLE INPUT AND OUTPUT:
[cs19085@cslinux svce]$ ./a.out
Enter the number:5
Result:15
[cs19085@cslinux svce]$

RESULT:

Roll Number: Page No.:


QUESTION: C) Write a C program to find the X^Y using recursion.

AIM:

ALGORITHM:

Roll Number: Page No.:


PROGRAM:
#include<stdio.h>
int p(int x,int n)
{
if(n==0)
return 1;
else if(n==1)
return x;
else
return(x*p(x,n-1));
}
void main()
{
int x,n;
printf("enter the base and power:");
scanf("%d%d",&x,&n);
printf("Result:%d\n",p(x,n));
}
SAMPLE INPUT AND OUTPUT:
[cs19085@cslinux SVCE]$ ./a.out
enter the base and power:5
3
Result:125
[cs19085@cslinux svce]$

RESULT:

Roll Number: Page No.:


QUESTION: D) Write a C program to reverse a given string using recursion.

AIM:

ALGORITHM:

Roll Number: Page No.:


PROGRAM:
#include<stdio.h>
#include<string.h>
void rev(char a[],int l,int l1)
{
char x;
if(l>0)
rev(a,l-1,l1);
x=a[l];
a[l]=a[l1-l];
a[l1-l]=x;
}
void main()
{
int l;
char a[10];
printf("Enter the string:");
scanf("%s",a);
l=strlen(a);
rev(a,l/2-1,l-1);
a[l]='\0';
printf("Result:%s\n",a);
}

SAMPLE INPUT AND OUTPUT:


[cs19085@cslinux svce]$ ./a.out
Enter the string:hello
Result:olleh
[cs19085@cslinux svce]$

RESULT:

Roll Number: Page No.:

Potrebbero piacerti anche