Explanation
The program calculates and prints the factorial of a number entered by the user.
Header
The code begins with including the standard input-output header file using #include <stdio.h>
.
Variable Declaration
The main()
function is defined, and three variables are declared:
long int d
: Stores the number entered by the user.long int m
: Used as a loop counter.long int j
: Initialized to 1 and used to store the factorial result.
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 up to 25 for which they want to calculate the factorial. The input is read using scanf("%ld", &d);
.
Factorial Calculation
The program calculates the factorial of the entered number using a for
loop:
for (m = 1; m <= d; m++)
: Loops through each number from 1 tod
.j *= m;
: Multipliesj
by the current value ofm
and stores the result inj
.
Output Result
The program prints the factorial of the entered number stored in j
.
Program End
The program ends with printf("\n\n");
to print a new line and 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>
int main()
{
long int d, m, j = 1;
printf("\n\n Program to print the factorial of the number entered by the user. Example 3 = 3 x 2 x 1 = 3 \n\n");
printf("Enter a number till 25 for which you want to print its factorial (Example: 21) - and press enter: ");
scanf("%ld", &d);
printf("\n Factorial of the entered number %ld is: ", d);
for (m = 1; m <= d; m++)
{
j *= m;
}
printf(" %ld", j);
printf("\n\n");
return 0;
}
Output
Program to print the factorial of the number entered by the user. Example 3 = 3 x 2 x 1 = 3
Enter a number till 25 for which you want to print its factorial (Example: 21) - and press enter:
6
Factorial of the entered number 6 is: 720