简体   繁体   中英

Find the sum of numbers in an array C

I have researched for over an hour on this topic and I had no luck so I decided to go ahead and ask this question here. I have been figuring out how find the sum of 10 different numbers from the array after I type numbers on program. For example, it asks you to type 10 different numbers and they would be all added up after they are typed out in an array. Here is the code. The top part is function. The bottom part is from main(). Any helps would be heavily appreciated.

void addNum(int z[])
{
    int sum = 0;
    int i;

    //scanf("%d", &z[i]);

    sum = sum + z[i];

    printf("\nThe sum of numbers you entered is %d.\n", sum);
}

...........

int z[10];
int i;
int num = 0;

printf("Please enter 10 different numbers: \n");

for(i = 0; i < 10; i++)
{
    z[i] = num;
    scanf("%d", &num);
}

printf("\nThe numbers you entered were: ");

for (i = 1; i <= 10; i++)
{
    printf("%d ", z[i]);
}
printf("\n");

//scanf("%d", z[i]);

addNum(z[i]);

You should do the adding in your function

void addNum(int z[], int sizeOfArray)
{
int sum = 0;

//scanf("%d", &z[i]);
for(int i = 0; i < sizeOfArray; i++){
   sum += z[i];
}
printf("\nThe sum of numbers you entered is %d.\n", sum);
}

Pass in the array in the main with the array size

addNum(z,10);

In your code use pass by reference and not pass by value.

When you call "addNum(z[i])" , i is 11 and what you are passing is z[11] which will be garbage at first place but you are passing only value of one variable which is not what you wanted.

What you want to pass is the address of the array either "z" or "&z[0]" . Along with the size of array, so the function knows how many member variables in array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM