Why is this algorithm in C returning erroneous values?

0
#include <stdio.h>
#include <stdlib.h>
/*
Desenvolva um algoritmo que leia 2 vetores de 10 elementos inteiros cada.
Em seguida, calcule a soma desses vetores, guarde o resultado em um
terceiro vetor e escreva o resultado
*/
int main(void)
{
  int vetorA[10];
  int vetorB[10];
  int vetorAB[10];

  for (int i = 0; i < 10; i++) {
     printf("Digite um valor vetorA[%d]:",i);
     scanf("%d", &vetorA);
  }
  printf("\n");

  for (int j = 0; j < 10; j++) {
    printf("Digite um valor vetorB[%d]:",j);
    scanf("%d", &vetorB);
  }
  printf("\n");

  for (int k = 0; k < 10; k++) {
    vetorAB[k] = vetorA[k] + vetorB[k];
  }

  for (int z = 0; z < 10; z++) {
     printf("%d\n",vetorAB[z]);
  }
  printf("\n");

  system("PAUSE");
  return 0;
}

Expected would be vector type AB [0] = vectorA [0] + vectorB [0] for example but it is returning different values

    
asked by anonymous 10.11.2018 / 21:28

1 answer

0

Your input is incorrect. In the first two repeating loops, you're reading vector A and B, respectively, something like this:

for (i = 0; i < 10; i++)
    scanf("%d", &vetorA);

Your scanf is receiving an integer from the input stream (currently its keyboard) and writing the result to the memory address of vectorA, ie at the beginning of its vector that corresponds to the memory address of vector A [0 ]. To fix this, use your counter variable's artifice to iterate over the vector:

for (i = 0; i < 10; i++)
    scanf("%d", &vetorA[i]);

Tip: you are using an INT variable for each loop, if you only use one, and your code gets leaner and beautiful, it will be simpler, try declaring the variable int i at the beginning of the program, and use it in all ties (they will never conflict because they execute one at a time, and because of the for (i = 0; ... statement, i will always return to 0 when a new loop starts.)

    
11.11.2018 / 17:33