Q:

C program to find the sum of N integer numbers using command line arguments

0

C program to find the sum of N integer numbers using command line arguments

In this program, we are going to find the sum of N integer numbers and numbers will be provided through the command line, we can pass any number of integer values (in this example, we are providing 6 integer numbers) and program will find and print the sum of all input numbers.

Sample input

./main  10  20 30 40 50 60

Here, ./main is the program's executable file name, 10 20 30 40 50 and 60 are the input values.

Sample output

arg[ 1]: 10 
arg[ 2]: 20 
arg[ 3]: 30 
arg[ 4]: 40 
arg[ 5]: 50 
arg[ 6]: 60 
SUM of all values: 210

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find the sum of N integer numbers using command line arguments in C

#include <stdio.h>

int main(int argc, char *argv[])
{
	int a,b,sum;
	int i; //for loop counter
	
	if(argc<2)
	{
		printf("please use "prg_name value1 value2 ... "\n");
		return -1;
	}
	
	sum=0;
	for(i=1; i<argc; i++)
	{
		printf("arg[%2d]: %d\n",i,atoi(argv[i]));
		sum += atoi(argv[i]);
	}
	
	printf("SUM of all values: %d\n",sum);
	
	return 0;
}

Output

./main 10 20 30 40 50 60
arg[ 1]: 10 
arg[ 2]: 20 
arg[ 3]: 30 
arg[ 4]: 40 
arg[ 5]: 50 
arg[ 6]: 60 
SUM of all values: 210

What is atoi()?

atoi() is a library function that converts string to integer, when program gets the input from command line, string values transfer in the program, we have to convert them to integers (in this program). atoi() is used to return the integer of the string arguments.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to calculate addition, subtraction, mult... >>
<< C program to find sum of two numbers using command...