Developer community
0 votes
63 views
asked by Guru (24.6k points) 31 57 92 | 63 views

2 Answers

0 votes

#include<stdio.h>

#include<conio.h>

void main()

{

int n,i,fact=1;

clrscr();

printf(“enter the number\n”);

scanf(“%d”,&n);

for(i=n;i>=1;i--)

{

fact=fact*i;

}

printf(“the factorial of given number is %d”,fact);

getch();

}

Output:

enter the number

5

the factorial of given number is 120 

answered by Guru (39.1k points) 10 23 38
0 votes
Recursion: A function is called 'recursive' if a statement within the body of a function calls the same

function. It is also called 'circular definition'. Recursion is thus a process of defining something in terms of itself. Program: To calculate the factorial value using recursion.

#include <stdio.h>

int fact(int n);

int main() {

int x, i;

printf("Enter a value for x: \n");

scanf("%d", &x);

i = fact(x);

printf("\nFactorial of %d is %d", x, i);

return 0;

} int fact(int n) {

/* n=0 indicates a terminating condition */

if (n <= 0) {

return (1);

} else {

/* function calling itself */

return (n * fact(n - 1));

/*n*fact(n-1) is a recursive expression */

}

}

Output:

Enter a value for x:

4

Factorial of 4 is 24

Explanation:

fact(n) = n * fact(n-1)

If n=4

fact(4) = 4 * fact(3) there is a call to fact(3)

fact(3) = 3 * fact(2)

fact(2) = 2 * fact(1)

fact(1) = 1 * fact(0)

fact(0) = 1

fact(1) = 1 * 1 = 1

fact(2) = 2 * 1 = 2

fact(3) = 3 * 2 = 6

Thus fact(4) = 4 * 6 = 24

Terminating condition(n <= 0 here;) is a must for a recursive program. Otherwise the program enters
into an infinite loop.
answered by Expert (13.2k points) 29 44 62

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+1 vote
3 answers
asked by Smita Advisor (7.1k points) 11 23 42 | 3.2k views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

3,754 questions
4,046 answers
117 comments
10,709 users