Why is this algorithm in C returning wrong values?

Asked

Viewed 47 times

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;
}

The expected would be type vector AB[0] = vector A[0] + vector B[0] for example but returning different values

  • This is a typo. The missing position in the reading of the two vectors that should be scanf("%d", &vetorA[i]); and scanf("%d", &vetorB[i]); respectively

  • thanks! I didn’t even notice

1 answer

0

Your entry is incorrect. In the first two loops of repetition, 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 standard input stream (at the moment, your keyboard) and recording the result to the vector memory address A, i.e., at the beginning of its vector which corresponds to the vector memory address A[0]. To fix this, use the trick of your counter variable to iterate over the vector:

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

Tip: You’re using an INT variable for each loop, if you use just one, in addition to your code getting thinner and nicer, it’ll be simpler, try declaring the int i variable at the beginning of the program, and using it on all loops (they will never conflict why they execute one at a time, and on account of the declaration for (i = 0; ..., i will always return to 0 when a new loop starts.

Browser other questions tagged

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