Factorial is defined for a positive integer, n, as the product of all the integers from 1 to n.
Factorial of n is denoted by .
For ex: 5!=5x4x3x2x1.
To write a C program that calculates the factorial of a given integer, we will make use of for loops. We will start the loop at i=n(Integer whose factorial is required). Decrement i at every iteration by 1 until we reach i=1.
Inside the loop, we will perform the multiplications required for finding the factorial.
The C program to find the factorial of a given number(positive integer) is shown below:
PROGRAM:
/*************************** ********FACTORIAL********** 2017 (c) Manas Sharma - https://bragitoff.com **************************/ #include<stdio.h> /*The following function takes an int and returns it's factorial NOTE: WE ARE USING DOUBLE AS THE RETURN TYPE TO ACCOMODATE LARGE FACTORIALS*/ double factorial(int n){ int i; double fact=1; for(i=n;i>=1;i--){ fact=fact*i; } return fact; } main(){ int n; printf("Enter a number whose factorial you want:\n"); scanf("%d",&n); printf("\nThe factorial of %d is %lf.\n\n",n,factorial(n)); }
Output:
Ph.D. researcher at Friedrich-Schiller University Jena, Germany. I’m a physicist specializing in computational material science. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT, and Machine Learning related apps and software from time to time. Can code in most of the popular languages. I like to share my knowledge in Physics and applications using this Blog and a YouTube channel.