Vector sum problem in C

Asked

Viewed 1,169 times

4

Vector sum problem, I’m trying to put the sum of the vectors directly into loop, but he is not doing the sum of all but duplicating the last vector, I tested the same code in Portugol and it worked perfectly, what would be the problem in C.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int apols[5],i,apolsTotal;

    for (i = 1; i <= 5; i++) 
    {
        printf("Digite a sua nota da apol %d\n",i);
        scanf("%d",&apols[i]);
        apolsTotal = apolsTotal + apols[i];
        //aqui esta o problema ele ta somando o ultimo valor com ele mesmo 
        //no caso apols[5] + apols[5]
    }

    /*apolsTotal = (apols[1] + apols[2] + apols[3] + apols[4] + apols[5])
    formula que funciona mas, não tao pratica*/
    printf("Total: %d\n",apolsTotal);
    return 0;
}
  • Failed to initialize total with 0

3 answers

3


There are two problems with the code. The first is that the totalization variable is not being initialized, so it takes a random number already existing in memory. In C always has to take care of everything in memory. The second is that it is going from 1 to 5 when in fact the vector starts with the index 0, the last element (the fifth in this case) being the 4.

#include <stdio.h>

int main() {
    int apols[5] ,apolsTotal = 0;
    for (int i = 0; i < 5; i++){
        printf("Digite a sua nota da apol %d\n", i + 1);
        scanf("%d", &apols[i]);
        apolsTotal += apols[i];
    }
    printf("Total: %d\n", apolsTotal);
}

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

2

In C the initial position of a vector is 0 and the last position is n-1, n being the set size for the vector.

Therefore, the error of your code is trying to insert at position 5, and that position the language does not recognize. And the other mistake is to start by inserting at position 1, and so you are missing to insert at position 0. I made the changes and now it works!!

#include <stdio.h>
#include <stdlib.h>

int main() {
    int apols[5],i,apolsTotal;
    for (i = 0; i < 5; i++){
        printf("Digite a sua nota da apol %d\n", i);
        scanf("%d", &apols[i]);
        apolsTotal = apolsTotal + apols[i];
    }
    printf("Total: %d\n", apolsTotal);
    return 0;
}

0

The vector/array in C starts in 0; then you need your accountant loop also start in 0, since it is used as vector index:

for (i = 0; i < 5; i++) 
{
    printf("Digite a sua nota da apol %d\n",i);
    scanf("%d",&apols[i]);
    apolsTotal = apolsTotal + apols[i];
}

Browser other questions tagged

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