My interpretation on how to transform the comments into code.
- removed obsolete prototype definition (it is obsolete due to function call order)
- renamed function from
findaverage
to calculate_average
due to what it does
- changed
*int grades[]
to int grades[]
- moved iterator declaration (
int i
) into loop as it is not used outside of the loop
- changed type of
sum
from int
to double
- used
+=
operation instead of sum = sum + ...
, to keep the code short and expressive
- changed type of
average
from int
to double
- added helper function to print input array
- changed output type format, added two digital places and newline to output of average
- add pointer versions of calculate_average to illustrate/clarify differences
The original data are structured as array. Therefore, they should be accessed in array style. Nevertheless, it is possible to process them in pointer style. See also the answers to What is the difference between char array and char pointer in C? for clarification.
calculate_average.c
#include <stdio.h>
double calculate_average(int howmany, int grades[]) {
double sum = 0.0;
for (int i = 0; i < howmany; i++) {
sum += grades[i];
}
return sum / howmany;
}
double calculate_average_pointers(int howmany, int *grades) {
double sum = 0.0;
for (int i = 0; i < howmany; i++) {
// calculate position of next int in memory 'grades + i' and
// retrieve int from it with dereference operator '*'
sum += *(grades + i);
}
return sum / howmany;
}
// working but bad mix of semantics, array as paramter, pointer arithmetic inside
double calculate_average_pointers_2(int howmany, int grades[]) {
double sum = 0.0;
for (int i = 0; i < howmany; i++) {
sum += *(grades + i);
}
return sum / howmany;
}
void print_array(int howmany, int grades[]) {
printf("[");
for (int i = 0; i < howmany; i++) {
char *comma_or_not = i < howmany - 1? "," : "";
printf(" %d%s", grades[i], comma_or_not);
}
printf(" ]\n");
}
int main()
{
const int size = 5;
int grades[5] = {30, 56, 23, 44, 45};
printf("Input: ");
print_array(size, grades);
double average = calculate_average(size, grades);
printf("Average: %.2lf\n", average); // two decimal places
average = calculate_average_pointers(size, grades);
printf("Average (pointers): %.2lf\n", average); // two decimal places
average = calculate_average_pointers_2(size, grades);
printf("Average (pointers 2): %.2lf\n", average); // two decimal places
return 0;
}
$ gcc -Wall calculate_average.c
$ ./a.out
Input: [ 30, 56, 23, 44, 45 ]
Average: 39.60
Average (pointers): 39.60
Average (pointers 2): 39.60
$