Problem 46

author
By Supreme2023-03-15
Problem Statement :
Write a program to find factorial of a number using recursion
Code:

#include <stdio.h>

int factorial(int n);

int main() {

//46. Write a program to find factorial of a number using recursion.

printf("\tFactorial");
printf("\n====================================\n\n");

int n;

printf("Enter The Number : ");
scanf("%d",&n);

int result = factorial(n);

printf("\n------------------------------------\n\n");
printf("Factorial Of %d = %d\n", n, result);
printf("\n------------------------------------\n");
return 0;
}

int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

Description :
  • This program defines a factorial function that calculates the factorial of a given number using recursion, and a main function that prompts the user to input a number and calls the factorial function to calculate its factorial. The program includes the header file stdio.h.
  • The program includes the header file stdio.h, which provides input/output functions.
  • The function factorial is defined, which calculates the factorial of an integer n using recursion.
  • The main function is defined, which does the following: a. Prints a header message. b. Prompts the user to input a number n. c. Calls the factorial function, passing in n. d. Prints the result of the factorial calculation to the console.
  • The factorial function calculates the factorial of n using recursion: a. If n is 0, then the function returns 1. b. Otherwise, the function multiplies n by the result of calling factorial(n - 1). This recursive call calculates the factorial of the number one less than n.
  • The main function prompts the user to input a number and calls the factorial function to calculate its factorial. The result is printed to the console.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.