Hello, I have written this programme to calculate the average of a series of numbers. It works when I do not use functions but doesn't when I use functions. Could someone help me find out why using functions is not correct for this task ?
Thanks in advance for your help.
Code:
CODE WITH FUNCTIONS THAT DOESN'T WORK
//This programme is just a modification of chapter15_exercice3.c such that the task is accomplished using functions
#include<stdio.h>
float average(int n, int numbers[n]) //a function that returns the average of the elements stored in a array
{
int i, sum = 0;
for (i = 0; i < n; i++)
{
sum += numbers[i];
}
return sum / n;
}
main()
{
int n,i;
printf("Please enter the number of numbers you wish to calculate the average\n");
scanf("%d", &n);
int numbers[n];
for (i = 0; i < n; i++)
{
printf("Enter number %d\n",i+1);
scanf("%d", &numbers[i]);
}
printf("Here are the numners that you've enter\nThe average of the following numbers are to be calculated\n");
for (i = 0; i < n; i++) //just to display to the user the numbers that they have entered
{
printf("%d, ", numbers[i]);
}
printf("\n");
printf("The average of the numbers that you've entered is %.2f\n", average(n, numbers[n]));
return 0;
}
Result:
chapter15_exercice3.c: In function ‘main’:
chapter15_exercice3.c:40:1: warning: passing argument 2 of ‘average’ makes pointer from integer without a cast [enabled by default]
printf("The average of the numbers that you've entered is %.2f\n", average(n, numbers[n]));
^
chapter15_exercice3.c:5:7: note: expected ‘int *’ but argument is of type ‘int’
float average(int n, int numbers[n]) //a function that returns the average of the elements stored in a array
^
CODE WITHOUT FUNCTIONS THAT WORKS
Code:
#include<stdio.h>
/*
float average(int n, int numbers[n])
{
int i, sum = 0;
for (i = 0; i < n; i++)
{
sum += numbers[i];
}
return sum / n;
*/
main()
{
int n,i;
printf("Please enter the number of numbers you wish to calculate the average\n");
scanf("%d", &n);
int numbers[n];
for (i = 0; i < n; i++)
{
printf("Enter number %d\n",i+1);
scanf("%d", &numbers[i]);
}
printf("Here are the numners that you've enter\nThe average of the following numbers are to be calculated\n");
for (i = 0; i < n; i++)
{
printf("%d, ", numbers[i]);
}
printf("\n");
int sum = 0;
float average;
for (i = 0; i < n; i++)
{
sum += numbers[i];
}
average = sum / n;
printf("The average of the numbers that you've entered is %.2f\n", average);
return 0;
}
Result:
Please enter the number of numbers you wish to calculate the average
5
Enter number 1
4
Enter number 2
4
Enter number 3
4
Enter number 4
4
Enter number 5
4
Here are the numners that you've enter
The average of the following numbers are to be calculated
4, 4, 4, 4, 4,
The average of the numbers that you've entered is 4.00