C Program to Pass Command Line Arguments

C




// Program to demonstrate Command line arguments in C
#include <stdio.h>
#include <stdlib.h>
  
int main(int argc, char* argv[])
{
    // code to calculate the sum of n numbers passed to CLA
    int i, sum = 0;
  
    // iterating the loop till the the number of
    // command-line arguments passed to the program
    // starting from index 1
    for (i = 1; i < argc; i++) {
        sum = sum + atoi(argv[i]);
    }
    printf("Sum of %d numbers is : %d\n", argc - 1, sum);
    
    return 0;
}


Command Line Instruction

// assume that the file name is solution
./solution 10 20 30 40 50

Output

SUM of 5 numbers is: 150

Note: The command line arguments are separated by space so if you want to pass a space-separated string as a command line argument, then enclose them inside the “”.

To know more, refer to the article – Command Line Arguments in C


How to Write a Command Line Program in C?

In C, we can provide arguments to a program while running it from the command line interface. These arguments are called command-line arguments. In this article, we will learn how to write a command line program in C.

Similar Reads

How to Write a Command Line Program in C?

Command line arguments are passed to the main() function. For that purpose, the main function should have the following signature:...

C Program to Pass Command Line Arguments

C // Program to demonstrate Command line arguments in C #include #include    int main(int argc, char* argv[]) {     // code to calculate the sum of n numbers passed to CLA     int i, sum = 0;        // iterating the loop till the the number of     // command-line arguments passed to the program     // starting from index 1     for (i = 1; i < argc; i++) {         sum = sum + atoi(argv[i]);     }     printf("Sum of %d numbers is : %d\n", argc - 1, sum);          return 0; }...