Error displaying the sum of three arrays read

Asked

Viewed 67 times

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 don’t know why it doesn’t work, I wanted to read three numbers and display, plus the sum, but it doesn’t work, returns the size of the variable "sum".

2 answers

2


Your second for is wrong, try it this way:

#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 notes inline (on the same line and separated by space), you must do as follows:

#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;
}
  • If I want to display the read value in just one row, how do I do it? For example: insert 0 2 3, integers. already tried without the n ??

  • @Chhh you want to display the values informed by the user and then the sum of them?

  • Yes, without typing "ENTER", insert the values with space.

  • @Chhh edited the answer to what you asked for.

  • Thank you, just as I wanted :)

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’re giving values to soma redundantly. In other words, the sum will always be notas[1] + notas [2] + notas[3], you’re rewriting soma in a row; and for that he did not need to be within the.

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);
  • @Renan, no, I really want to add..

  • I forgot the arrays started at 0.

Browser other questions tagged

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