Practical-03
Write a program to find factorial of given no using recursion.
Introduction
In this program, we will learn to write a recursive function to calculate the factorial of a given number.
Algorithm
- Start
- Declare variables number and result.
- Take input from user and store it in number.
- Call the factorial function to calculate the factorial of the given number.
- Print the factorial of the given number.
- End
Code
Practical-03.c
#include<stdio.h>
int factorial(int number); // declare the prototype of factorial function
void main(){
int number;
printf("Enter an integer: "); // prompt user to enter an integer
scanf("%d", &number); // read the input and store in the variable number
int result = factorial(number); // call the factorial function to calculate factorial
printf("The factorial of %d is %d\n", number, result); // print the result
}
int factorial(int number){
if(number == 0) // base case
return 1; // factorial of 0 is 1
else
return number * factorial(number - 1); // recursive call
}
Output
Enter an integer: 5
The factorial of 5 is 120
Explanation
The program first asks the user to enter an integer. Then it calls the factorial function to calculate the factorial of the given number. The factorial function is a recursive function. It calls itself until the base case is reached. The base case is when the number is 0. The factorial of 0 is 1. The factorial function returns the factorial of the given number.