Factorial of a Number using Command Line Argment Program

Problem Statement: Write a C program to calculate the factorial of a non-negative integer N. The factorial of a number N is defined as the product of all integers from 1 up to N. Factorial of 0 is defined to be 1. The number N is a nonnegative integer that will be passed to the program as the first command line parameter. Write the output to stdout formatted as an integer WITHOUT any other additional text. You may assume that the input integer will be such that the output will not exceed the largest possible integer that can be stored in an int type variable.

Also, you can study other Command Line Programming Questions here on our TCS Dashboard.

It is highly advisable to go through Command Line Arguments Post before even looking at the code. Please study this for TCS and come back to this post later.

At the end of the page, there is the video explaining the program on YouTube.

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.

[code language=”cpp”]

 #include <stdio.h> // for printf
#include <stdlib.h> // for function atoi() for converting string into int
// Function to return fact value of n
int fact(int n)
{
 if (n == 0)
 return 1;
 else {
 int ans = 1;
 int i;
 for (i = 1; i <= n; i++) {
 ans = ans * i;
 }
 return ans;
 }
}
// argc tells the number of arguments
// provided+1 +1 for file.exe
// char *argv[] is used to store the
// command line arguments in the string format
int main(int argc, char* argv[])
{
 // means only one argument exist that is file.exe
 if (argc == 1) {
 printf("No command line argument exist Please provide them first \n");
 return 0;
 } else {
 int i, n, ans;
 // actual arguments starts from index 1 to (argc-1)
 for (i = 1; i < argc; i++) {
 // function of stdlib.h to convert string
 // into int using atoi() function
 n = atoi(argv[i]);
 
 // since we got the value of n as usual of
 // input now perform operations
 // on number which you have required
 
 // get ans from function
 ans = fact(n);
 
 // print answer using stdio.h library's printf() function
 printf("%d\n", ans);
 }
 return 0;
 }
}

[/code]

OutPut –

24 if command line argument is 4.

or simple program to write n! is –

[code language=”cpp”]

#include <stdio.h>

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);

}

[/code]

Command Line Programming Video for Factorial of a Number –

Other TCS Coding Questions –

Summary
Review Date
Reviewed Item
Command Line
Author Rating
51star1star1star1star1star

2 comments on “Factorial of a Number using Command Line Argment Program”