C Program - Factorial of a Number using Command Line Argument
C Programming Language Command Line Arguments (Article) Command Line Arguments (Program)
12369Program:
#include int main (int argc, char *argv[]) { int n, i; unsigned long long factorial = 1; n = atol (argv[1]); for (i = 1; i <= n; ++i) { factorial *= i; } printf ("Factorial of %d = %llu", n, factorial); }
Output:
// give 4 as input in your cmd 4 Factorial of 4 = 24
Explanation:
This C program calculates the factorial of a given integer number using the command-line argument. Let's break down the code step by step:
-
#include <stdio.h>
: This line includes the standard input-output library, which provides functions for reading input and displaying output. -
int main(int argc, char *argv[])
: This is the main function of the program, which is the entry point of execution. The program accepts command-line arguments through theargc
andargv
parameters.argc
represents the number of command-line arguments passed to the program, andargv
is an array of character pointers that hold the actual arguments. -
int n, i;
: These are integer variables used to store the input number (n
) whose factorial we want to calculate and the loop counter variable (i
). -
unsigned long long factorial = 1;
: This variablefactorial
is used to store the result of the factorial calculation. Theunsigned long long
data type is used to ensure that it can handle large factorial values. -
n = atol(argv[1]);
: The program usesatol
(ASCII to long integer) function to convert the first command-line argument (argv[1]
) to an integer value, and then stores it in the variablen
. -
The
for
loop: This loop iterates fromi = 1
toi
being less than or equal ton
. The loop calculates the factorial of the numbern
by multiplyingfactorial
with each value ofi
from 1 ton
. -
printf("Factorial of %d = %llu", n, factorial);
: Finally, the program displays the result of the factorial calculation using theprintf
function.%d
is a placeholder for the integern
, and%llu
is a placeholder for theunsigned long long
integerfactorial
.
Example:
If the argument is 4, the value of N is 4. So, 4 factorial is 1*2*3*4 = 24. Output: 24 The code below takes care of negative numbers but at the end of the page there is easier code which though doesn't take negative numbers in consideration.
This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.