Please help with the following question: Question : Write a complete C program (
ID: 664220 • Letter: P
Question
Please help with the following question:
Question : Write a complete C program (main only) that will accept a
command line argument consisting of a word followed by two
integer numbers. The word can be either sum or average. If
the word is sum, the program will print out the sum of the
two integers and if the word is average, it will print out
the average of the two integers with one decimal precision.
Assume that the correct arguments are always supplied and
separated by a single space. For example if the command
line arguments are sum 4 13, the program will print out 17.
If the command line arguments are average 7 4, the program
will print out 5.5.
Many thanks
Explanation / Answer
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
void main(int argc, char *argv[])
{
char operation[10] ; /* can be either sum or average */
int addend, adder;
float sum, avg;
/* argc must be 3 and argv will be sum 4 5 for example or average 4 5 */
clrscr(); /* clear the screen */
if ( argc !=3 ) {
printf(" usage: %s sum integer1 integer2", argv[0]);
printf(" or usage: %s average integer1 integer2", argv[0]); }
/* atoi will convert ascii to integer */
addend = atoi(argv[2]);
adder = atoi(argv[3]);
/* typecast with float to convert int to float*/
sum = addend + adder;
/* look at the operation word and find whether it is sum or average */
if ( strcmp(argv[1],"sum" ) == 0 ) {
/* time to add */
sum = (float)addend + (float)adder; /* this statement is reduntary */
printf(" Sum of %f + %f = %f ", (float)addend, (float)adder, sum);
}
if ( strcmp(argv[1],"average" ) == 0 ) {
/* time to average */
avg = ( sum ) / 2.0;
printf(" Average of %f and %f is %f", (float)addend, (float)adder , avg);
}
} /* end of main */
/* The program is tested, compiled and ran ok in Turbo C Compiler */
/* Sample Run Output / Results */
usage: sumavg.exe sum integer1 integer2
or usage: sumavg.exe average integer1 integer2
sumavg.exe sum 14 25
Sum of 14.0 + 25.0 = 39.0
sumavg.exe average 14 25
Average of 14.0 and 25.0 is 19.5