C Program to Find Sum of N Numbers using Command Line Arguments

Problem:

Write a c program to find sum of n numbers. Write a C program to find sum of n numbers using command line arguments.

Theory:

Two parameters argc and argv[] are used in main() function. Command line arguments are passed to the main() function when the program is invoked.

argc stores the count of total arguments. argv[] is array of pointers of the type char which points to the arguments passed while executing the program. All the arguments passed are stored as strings.

The first command line argument is always the executable program file name which can be accessed by using index 0. In Linux it is ./a.out by default.

Algorithm to find sum of n numbers using command line arguments

  1. Accept n numbers from command line
  2. Convert the strings into integers using atoi() function.
  3. Sum up the numbers starting from index 1 to value of argc.
  4. Divide the sum by argc-1.
  5. Print the sum of n numbers

C program to find sum of n numbers

/* Aim: Write a C program to accept n integers as command line arguments and find sum */

#include<stdio.h>
#include<stdlib.h>

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

	if(argc<=1)
	{
	printf("\n Enter appropriate number of arguments to calculate sum  \n \n");
	exit(0);
	}
	else
	{
		for(i=1;i<argc;i++)
		{
			sum+=atoi(argv[i]);
		}
	}


	printf("\n Sum of all command line arguments is %d \n \n",sum); 
}

Output of C program:

$ ./a.out 2 4 2 1 1 Sum of all command line arguments is 10

Comments