The program is about function making an average. I get an error:
error: expected ';', ',' or ') before numeric constant
within the avg_array() function whenever I build it. Help would be appreciated, thanks!
#include <stdio.h>
#define SIZE 5
// Prototypes
int avg_array (int*, int);
main()
{
int values[SIZE];
int avg;
int i;
printf("Enter 5 numbers please. \n");
for(i=0; i<SIZE; i++)
{
scanf("%d", &values[i]);
}
avg = avg_array(values, SIZE);
printf("\n The avg of the array is %d \n", avg);
getchar();
getchar();
} // end main()
/* Implement avg_array() WHERE THE ERROR PERTAINS */
avg_array(int my_array[], int SIZE)
{
int sum;
int i;
int fxn_average;
for(i=0; i<SIZE; i++)
{
sum = sum + my_array[i];
}
fxn_average = (sum/SIZE);
return (fxn_average);
}
You are using the identifier SIZE
as an argument. This is also a macro that gets converted to 5
by the preprocessor. After the preprocessor applies the macros, it would look like
avg_array (int my_array[], int 5)
Since 5
is a numeric constant instead of an identifier, it generates an error. Change the variable name.
It looks like you also have a function signature missing a return type, which should match the prototype declared above. Try this instead:
int avg_array (int *my_array, int size)
{
int sum = 0;
int i;
for(i=0; i<size; i++)
{
sum = sum + my_array[i];
}
return sum/size;
}
The variable sum
should be initialized to 0. The local variable fxn_average
is not needed because you can use just return sum/size;
at the end instead.
I changed the type of the first argument from int[]
(array of int
) to int *
(pointer to int
) so the function definition matches the prototype given in the question. The function was declared as
int avg_array (int*, int);
These arguments have no identifiers; only their types are specified. This is valid C, but many style guides prescribe against it since naming arguments helps the reader understand meaning or intent. If you are writing a programming interface, for example, all the programmer will likely see is the function prototypes in a header file. It must be clear what the arguments are to write a correct function call. Anyway, adding in identifiers looks like:
int avg_array (int *my_array, int size);
which is the same as in the definition I used above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With