Schiele
Schiele

Reputation: 125

Using a function with an array as input in C

I'm trying to write a program which asks the user to insert a series of number to make an array and then, using a function, calculate the sum and the mean of the elements of the array. The problem is that when I use the function in the main the output of sum and mean are both 0. And if I just use arr[n] without & I got other errors, why is that?

Here's the code:

#include <stdio.h>

int sum_and_mean (int arr[], int n);

    int i;
    int n;
    int arr[100];

int main(){

    printf("How many numbers do you want to insert?");
    scanf("%d", &n);

    if((n > 0) && (n <= 20)){
        for(i = 0; i < n; i++){
            printf("Insert a number:");
            scanf("%d", &arr[i]);
        }

        printf("The array is:\n");
        for (i = 0; i < n; i++){
            printf("%d\n", arr[i]);
        }
    }

    else {
        printf("Error: number must be between 0 and 20");
    }

    sum_and_mean(&(arr[n]), n);

    return 0;
}

int sum_and_mean (int arr[], int n){
    double sum = 0;
    double mean;
    for (i = 0; i < n; i++){
        sum += arr[i];
    }
    printf("The sum of the elements is %lf\n", sum);
    mean = sum / n;
    printf("The mean of the elements is %lf", mean);
    return 0;
}

Upvotes: 0

Views: 1507

Answers (2)

Hitokiri
Hitokiri

Reputation: 3689

I see something maybe have to improve in your code (I do not say about using of arr because @Some_programmer_dude explained very clearly).

else {
        printf("Error: number must be between 0 and 20");
    }

    sum_and_mean(&(arr[n]), n);

you should return 0 in else statement because, if you have error, you do not need to call sum_and_mean function.

OT, you define int array, so sum is integer also. You should change double sum to:

int sum;

Thus, for mean value, you can multiply by 1.0 as below if you define int sum:

mean = 1.0 * sum/n

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

The expression &(arr[n]) is a pointer to the n:th element in the array, which is outside of the initialized portion of the array.

You want to pass a pointer to the first element of the array: &arr[0], which can also be expressed as plain and simple arr (arrays naturally decays to pointers to their first element).

Upvotes: 4

Related Questions