0 valutazioniIl 0% ha trovato utile questo documento (0 voti)
34 visualizzazioni8 pagine
This document contains 4 questions asking to write C programs using recursion to:
1) Calculate the factorial of a number
2) Compute the sum of the first N natural numbers
3) Calculate X to the power of Y
4) Reverse a given string
For each question, it provides the aim, algorithm, program code, sample input/output, and space to write the result.
This document contains 4 questions asking to write C programs using recursion to:
1) Calculate the factorial of a number
2) Compute the sum of the first N natural numbers
3) Calculate X to the power of Y
4) Reverse a given string
For each question, it provides the aim, algorithm, program code, sample input/output, and space to write the result.
This document contains 4 questions asking to write C programs using recursion to:
1) Calculate the factorial of a number
2) Compute the sum of the first N natural numbers
3) Calculate X to the power of Y
4) Reverse a given string
For each question, it provides the aim, algorithm, program code, sample input/output, and space to write the result.
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.