Factorial of a Number using Command Line Argument Program

C Programming Language / Command Line Arguments

13378

Program:

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

}

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:

  1. #include <stdio.h>: This line includes the standard input-output library, which provides functions for reading input and displaying output.

  2. 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 the argc and argv parameters. argc represents the number of command-line arguments passed to the program, and argv is an array of character pointers that hold the actual arguments.

  3. 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).

  4. unsigned long long factorial = 1;: This variable factorial is used to store the result of the factorial calculation. The unsigned long long data type is used to ensure that it can handle large factorial values.

  5. n = atol(argv[1]);: The program uses atol (ASCII to long integer) function to convert the first command-line argument (argv[1]) to an integer value, and then stores it in the variable n.

  6. The for loop: This loop iterates from i = 1 to i being less than or equal to n. The loop calculates the factorial of the number n by multiplying factorial with each value of i from 1 to n.

  7. printf("Factorial of %d = %llu", n, factorial);: Finally, the program displays the result of the factorial calculation using the printf function. %d is a placeholder for the integer n, and %llu is a placeholder for the unsigned long long integer factorial.

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.