C++ Program to sum elements passed through Command Line Arguments [DEVCPP/GCC]

COMMAND LINE ARGUMENTS

Command Line Arguments are optional string type arguments which can be passed to the program by the Operating System when it is launched.

The full declaration of main is

int main( int argc, char *argv[])

Here, argc refers to Argument Count which contains the number of arguments passed to the main function including a parameter as path of the program. argv is an array of character pointers which contains the arguments. The first argument argv[0] contains the path of program.

To pass Command Line Arguments in DevC++, you need to do the following:

C++ Program to sum elements passed through Command Line Arguments
                         

                           C++ Program to sum elements passed through Command Line Arguments

PROGRAM

//Program to sum elements passed through Command Line Arguments

#include <iostream>
#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[])
{
        int i,sum=0;

        cout<<"\nARGUMENT COUNT: "<<argc;
        cout<<"\nARGUMENT VALUES: ";

        for(i=0;i<argc;i++)
        {
                cout<<" "<<argv[i];
                if(i!=0)
                {
                           sum=sum+atoi(argv[i]);
                }
        }

        cout<<"\nSUM OF THE ELEMENTS: "<<sum;

        return 0;
}

OUTPUT

C++ Program to sum elements passed through Command Line Arguments with output

Share this

Related Posts

FIND US ON FACEBOOK!