Looping in a validation within a matrix

Asked

Viewed 34 times

1

Well, I need to validate typed numbers so that my matrix matriz[5][3] accept only odd numbers, for this I used inside the loops for one do{ }while to have another number typed in case it was reported as a pair, however the program loops displaying the message of the if even when the entered value is correct.

#include <stdio.h>
#include <string.h>

main()
{
int matriz[5][3];
int l, c;

printf ("\t Preencha a Matriz\n");

for (l=0; l<5; l++)
{
    for (c=0; c<3; c++)
    {
        printf ("\n * \n");
        printf (" Linha [%d] | Coluna [%d] \n", l+1, c+1);
        scanf ("%d", matriz[l][c]);
        do{
            printf ("\n * \n");
            if (matriz[l][c] %2 == 0)
            {
                printf ("\n Numero invalido! Informe outro");
            }
        }while(matriz[l][c] %2 == 0);
    }
}

for (l=0; l<5; l++)
{
    for (c=0; c<3; c++)
    {
        printf ("\n %d", matriz[l][c]);
    }
}
}

1 answer

1


Failed to redo data input when number is not odd.

for (l = 0; l < 5; l++)
{
  for (c = 0; c < 3; c++)
  {
    printf("\n * \n");
    printf(" Linha [%d] | Coluna [%d] \n", l+1, c+1);
    scanf("%d", &matriz[l][c]); // <--- faltava &
    do {
      printf ("\n * \n");
      if ((matriz[l][c] % 2) == 0)
      {
        printf("\n Numero invalido! Informe outro");
        scanf("%d", &matriz[l][c]); // <=========== faltando
      }
    } while (matriz[l][c] %2 == 0);
  }
}

Simplest logic:

for (l = 0; l < 5; l++)
{
  for (c = 0; c < 3; c++)
  {
    printf("\n * \n");
    printf(" Linha [%d] | Coluna [%d] \n", l+1, c+1);
    for (;;)
    {
      scanf("%d", &matriz[l][c]);
      if (matriz[l][c] & 1)
        break;
      printf("\n Numero invalido! Informe outro");
    }
  }
}

More robust data entry:

int n;
char buf[10];

for (l = 0; l < 5; l++)
{
  for (c = 0; c < 3; c++)
  {
    printf("\n * \n");
    printf(" Linha [%d] | Coluna [%d] \n", l+1, c+1);
    for (;;)
    {
      fgets(buf, 10, stdin); // ignorando erro quando digitado ^D/^Z
      n = sscanf(buf, "%d", &matriz[l][c]);
      if (n == 1 && (matriz[l][c] & 1))
        break;
      printf("\n Numero invalido! Informe outro");
    }
  }
}

Browser other questions tagged

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