Explanation
The program calculates the factorial of a number entered by the user using a recursive function.
Header
The code begins with including the standard input-output header file using #include <stdio.h>.
Function Declaration
The program declares a recursive function factorial to calculate the factorial of a number:
int factorial(int n): Declares the function with an integer parametern.
Function Definition
The program defines the factorial function:
if (n == 0): Defines the base case where the factorial of 0 is 1.return 1;: Returns 1 if the base case is met.return n * factorial(n - 1);: Defines the recursive case where the factorial ofnis equal tonmultiplied by the factorial ofn - 1.
Variable Declaration
The main() function is defined, and a variable is declared:
int n: Variable to hold the number entered by the user.
Program Description
The program prints a description message for the user to understand its functionality.
User Input
The user is prompted to enter a number:
printf("Enter a number: ");: Prompts the user to enter a number.scanf("%d", &n);: Reads the number and stores it inn.
Factorial Calculation
The program calculates the factorial of the number using the factorial function:
int result = factorial(n);: Calls thefactorialfunction withnas an argument and stores the result inresult.
Output Result
The program prints the factorial of the number:
printf("The factorial of %d is %d\n", n, result);: Prints the number and its factorial.
Program End
The program ends with return 0; to indicate successful execution.
Code
/*
* -----------------------------------------------------------
* Logic Building with Computer Programming (CSU1128)
* Instructor: Dr. Pankaj Vaidya | Author: Divya Mohan
*
* This code is a part of the educational initiative by dmj.one
* with aim of empowering and inspiring learners in the field of
* Computer Science and Engineering through the respective courses.
*
* (c) 2022, Divya Mohan for dmj.one. All rights reserved.
* -----------------------------------------------------------
*/
#include <stdio.h>
// Declare a recursive function to calculate the factorial of a number
int factorial(int n)
{
// Define the base case where the factorial of 0 is 1
if (n == 0)
{
return 1;
}
// Define the recursive case where the factorial of n is equal to n multiplied by the factorial of n - 1
return n * factorial(n - 1);
}
int main()
{
printf("\n\n Program to generate factorial of the number entered by the user through function recursion. \n\n");
// Declare a variable to hold the number entered by the user
int n;
// Read the number from the user
printf("Enter a number: ");
scanf("%d", &n);
// Calculate the factorial of the number using the factorial function
int result = factorial(n);
// Print the result
printf("The factorial of %d is %d\n", n, result);
return 0;
}
Output
Program to generate factorial of the number entered by the user through function recursion.
Enter a number: 25
The factorial of 25 is 2076180480