Kenny Tat
Kenny Tat

Reputation: 21

Calculating the mean of an array

#include<stdio.h>
#include<stdlib.h>
double mean(int i, int arr[])
{
    int j, sum = 0;
    for (j = 0; j < i; j++)
    {
        sum = arr[j] + sum;
    }
    return (float)sum/i;
}
int main()
{
    int arr[100] = { NULL };
    int i, n, sum = 0;
    printf("How many numbers would you like to enter?");
    scanf_s("%d", &n);
    while (n > 100 || n < 0)
    {
        printf("Amount of numbers should be less than 0 and more than 100\n");
        scanf_s("%d", &n);
    }
    for (i = 0; i < n; i++)
    {
        scanf_s("%d", &arr[i + 1]);
    }
    printf("%f", mean(i-1, arr[i]));
    system("pause");
}

When I run the code it gives me a read access error. The problem is with the mean() function I created but I don't know what's wrong. Help?

Upvotes: 1

Views: 96

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

When I run the code it gives me a read access error. The problem is with the mean() function

Although the mean() function produces read access error, the actual problem is here:

printf("%f", mean(i-1, arr[i]));

You are not passing an array to your function, but its element (it is one past the end of what was written, too, so even the value that you pass is undefined).

You need to pass i for the length, because your mean() treats it as an exclusive upper limit, and you also need to pass arr for the array:

printf("%f", mean(i, arr));

Indexing problem when reading the data also needs to be fixed - you need to remove + 1:

scanf_s("%d", &arr[i]);
//                 ^

Upvotes: 6

Kajal
Kajal

Reputation: 601

Try this:

#include<stdio.h>
#include<stdlib.h>
double mean(int i, int arr[])
{
    int j, sum = 0;
    for (j = 0; j < i; j++)
    {
        sum = arr[j] + sum;
    }
    return (float)sum/i;
}
int main()
{
    int arr[100] = { 0 };
    int i, n, sum = 0;
    printf("How many numbers would you like to enter?");
    scanf("%d", &n);
    getchar();
    while (n > 100 || n < 0)
    {
        printf("Amount of numbers should be more than 0 and less than 100\n");
        scanf("%d", &n);
        getchar();
    }
    for (i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
        getchar();
    }
    printf("%lf", mean(n, arr));
    getchar();
}

Your call to the mean function was wrong. You have to pass the entire array, not just one element. Change arr[i] to arr.

Other minor modifications are what I did to make it run on my system. If it works for you otherwise, then great.

Upvotes: 2

Related Questions