Sum function returns zero

Asked

Viewed 47 times

-1

By the time the input is all ok with the information, but in the output only gives the result 0 and do not know what else to do, already I moved and I reworked the whole code.

The idea is that in a array size 6, the internal sum of these elements occurs. In this case the elements are {1,2,3,4,10,11}.

int simpleArraySum(int ar_count, int ar [6]) {
ar_count = 0;
ar [0]= 1 ;
ar [1]= 2;
ar [2]= 3;
ar [3]= 4;
ar [4]= 10;
ar [5]= 11;
int i ;
int result;

for (i=0; i<6; i++){
    ar_count += ar[i];

};

result = ar_count;

return 0;
}

1 answer

1


This code is confusing and makes no sense. If you do the simple, doing only what is necessary according to the statement, giving more meaningful names to the variables is easier. Nor was it returning a obtained value, it only returned 0, you can’t expect a different result when the code clearly does this. Start s sum, accumulate (and not counting) and return the result, that’s all:

#include <stdio.h>

int simpleArraySum(int array[6]) {
    int soma = 0;
    for (int i = 0; i < 6; i++) soma += array[i];
    return soma;
}

int main(void) {
    printf("%d", simpleArraySum((int[]){1, 2, 3, 4, 10, 11}));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Yeah, it’s cleaner that way, but then in case he doesn’t recognize the vector... The idea I had up there was to declare every composition of the vector exactly because it didn’t read when I declared inside the keys. main.cpp: In Function 'int main()': main.cpp:15:60: error: taking address of Temporary array This was the error that appeared to me when I played the compiler. I just copied, pasted and ran and gave this error. I don’t know why it doesn’t read the vector in keys.

  • If you’re doing something in C because you have one .cpp? You clicked on links and saw working?

  • Hm...I selected wrong when opening Dev-c++, thanks man! It helped a lot :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.