Improper storage in the vector

Asked

Viewed 48 times

0

I’m having trouble solving this algorithm in c. I need the user to type 10 numbers, and check if the number is even or odd. store these numbers in two distinct vectors, one for even numbers and one for odd numbers. However, I am doubtful about what I do with vector spaces in which no user data is stored, as it usually returns junk from memory. It follows the code: '' int main() { int i,num,qtdP,qtdI,odd[max],pairs[max];

qtdP=qtdI=0;


for(i=0;i<10;i++){

    //entrada de dados do usuario
    printf("Digite um numero: ");scanf("%d",&num);

    //verifica se o numero é par ou impar, e armazena no seu devido vetor
    if(num%2==0){

        pares[qtdP]=num;
        qtdP++;
    }else{

        impares[qtdI]=num;
        qtdI++;
    }
}

//imprime os numeros pares
printf("\n\nOs numeros pares sao: ");
for(i=0;i<10;i++){

    printf("%d ",pares[i]);
    qtdP++;
}

//imprime os numeros impares
printf("\nOs numeros impares sao: ");
for(i=0;i<10;i++){

    printf("%d ",impares[i]);
    qtdI++;
}


return 0;

}'''

  • 1

    Simply ignore such positions. Your print loops should not be for(i=0;i<10;i++){ and yes go up qtdP and qtdI.

1 answer

1


You have not declared the variable max used to initialize arrays pares and impares, so I replaced it with 10.

I moved the variables i and num for the scope in which they are used.

And for the program to print only the values of the arrays you must limit the loops by using the variables qtdP and qtdI.

#include <stdio.h>

int main() {
  int qtdP = 0, pares[10];
  int qtdI = 0, impares[10];

  for (int i = 0; i < 10; i++) {
    int num = 0;

    //entrada de dados do usuario
    printf("Digite um numero: ");
    scanf("%d", &num);

    //verifica se o numero é par ou impar, e armazena no seu devido vetor
    if (num % 2 == 0) {
      pares[qtdP] = num;
      qtdP++;
    } else {
      impares[qtdI] = num;
      qtdI++;
    }
  }

  //imprime os numeros pares
  printf("\n\nOs numeros pares sao: ");
  for (int i = 0; i < qtdP; i++) {
    printf("%d ", pares[i]);
  }

  //imprime os numeros impares
  printf("\nOs numeros impares sao: ");
  for (int i = 0; i < qtdI; i++) {
    printf("%d ", impares[i]);
  }

  return 0;
}

Browser other questions tagged

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