Error displaying the sum of three read arrays

2
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, notas[5];
    int soma = 0;
    for(i=0; i<3; i++)  {
        printf("Digite os tres numeros:\n");
        scanf("%d", &notas[i]);
    }
    for(i=0; i<3; i++) {
        soma = soma + notas[i];
        soma = notas[1] + notas [2] + notas[3];
        printf("Valor: %d\n", soma);

    }
    return 0;
}

I do not know why it does not work, I wanted to read three numbers and display, plus the sum, but it does not work, returns the size of the "sum" variable.

    
asked by anonymous 18.05.2015 / 22:49

2 answers

2

Your second for is wrong, try the following:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, notas[5];
    int soma = 0;
    for(i=0; i<3; i++)  {
        printf("Digite os tres numeros:\n");
        scanf("%d", &notas[i]);
    }
    for(i=0; i<3; i++) {
        soma = soma + notas[i];
    }
    printf("Valor: %d\n", soma);
    return 0;
}

To read the 3 inline notes (on the same line and separated by space), you must do the following:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, notas[5];
    int soma = 0;
    printf("Digite os tres numeros: ");
    scanf("%d%d%d", &notas[0], &notas[1], &notas[2]);
    for(i=0; i<3; i++) {
        soma = soma + notas[i];
    }
    printf("Valor: %d\n", soma);
    return 0;
}
    
18.05.2015 / 22:52
2

When you have

for(i=0; i<3; i++) {
    soma = soma + notas[i];
    soma = notas[1] + notas [2] + notas[3];
    printf("Valor: %d\n", soma);
}

You are giving values to soma redundantly. In other words, the sum will always be notas[1] + notas [2] + notas[3] , you are rewriting soma in consecutive lines; and for this it did not even need to be within the for loop.

If you want to show the sum as the loop runs you should only use:

for(i=0; i<3; i++) {
    soma = soma + notas[i];
    printf("Valor: %d\n", soma);
}

If you want to show only the final sum you can use:

for(i=0; i<3; i++) {
    soma = soma + notas[i];
}
printf("Valor: %d\n", soma);
    
18.05.2015 / 22:53