Problem with sum in vector in C

3

Problem with sum of vectors, I'm trying to put the sum of the vectors directly in the loop , but it is not doing the sum of all, but duplicating the last vector, I tested the same code in Portugol and 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;
}
    
asked by anonymous 03.10.2018 / 15:43

3 answers

2

You have two problems with your code. The first is that the totalizing variable is not being initialized, so it takes a random number already in memory. In C you always have 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 index 0, the last element (the fifth in this case) being 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);
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
03.10.2018 / 16:03
2

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

So the error in your code is trying to insert in position 5, and that position the language does not recognize. And the other error is to start inserting by position 1, and so you are missing from insert in 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;
}
    
03.10.2018 / 15:59
0

The vector / array in C starts at 0 ; then you need your loop counter to also start at 0 , since it is used as the 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];
}
    
03.10.2018 / 15:59