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

Problem:

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

Theory:

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

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 (wap) to find average 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 average of n numbers

C program to find average of n numbers

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

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

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

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

avg/=argc-1;

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

Output of C program: