forked from ucsd-cse29/lab3-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaverage.c
30 lines (24 loc) · 806 Bytes
/
average.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>
#include <stdlib.h>
/*
* argc: The length of the argv array below
* argv: Array of strings: argv[0] holds the program name as a string; the remaining indices hold the actual command-line arguments
*/
int main(int argc, char *argv[]) {
int num_args = argc - 1; // argv[0] is program name
if (num_args < 2) {
printf("Error: Please provide at least two numbers.\nUsage: %s <number 1> <number 2> ...\n", argv[0]);
return 1;
}
float sum = 0;
// Loop through each command-line argument to calculate the sum
// First arg starts at argv[1]
int i;
for (i = 1; i < argc; i++) {
sum += atoi(argv[i]);
}
// Calculate the average of all args
float average = sum / 2;
printf("Average: %.2f\n", average);
return 0;
}