Design a function to finding factorial of given number in c
Design a Function to Find the Factorial of a Given Number in C
In C, factorial of a number is the product of all positive integers from 1
to the number itself. For example, the factorial of 5
(written as 5!) is 1 x 2 x 3 x 4 x 5 = 120.
To design a function to find the factorial of a given number, you can follow these steps:
- Declare a function that takes an integer as an argument and returns an integer as a result.
- Inside the function, declare a variable to hold the factorial and initialize it to
1
. - Use a loop to iterate from
1
to the given number and multiply the factorial variable with the loop counter in each iteration. - After the loop is completed, return the factorial variable.
C code that implements the above steps:
#include<stdio.h>
int factorial(int num) {
int fact = 1;
int i;
for (i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d.\n", num, factorial(num));
return 0;
}
The output of the given C code is as follows:
Enter a number: 5
Factorial of 5 is 120.
This is because the factorial of a number is the product of all the positive integers less than or equal to that number. So, the factorial of 5
is 1 * 2 * 3 * 4 * 5
, which is 120.
When the user enters 5
at the prompt, the program calls the factorial()
function with the argument 5
. The factorial()
function calculates the factorial of 5
and returns the value 120.
The main function then prints the value 120
to the console.
Further Reading:
Calculating Factorials: A Program to Find Factorial of a Number
Design a function to finding factorial of given number in c
Design a recursive Function For Finding The Factorial of given Number in c
Enroll Now:
[ C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"
Contact Us:
- For any inquiries, please email us at [info@electro4u.net].
- Follow us on insta [ electro4u_offical_ ] for updates and tips.
Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!