SaveMe SaveMe - 28 days ago 16
C Question

Program check number and always give true

Someone can find mistakes? In the last while something is wrong (always pass) but i cannot figure out what... Thanks for advice

/*

This program draws to array 15 integers <0,5>
prints drawn elements
then asks for the number and check whether the number is in array
at the end draws: "OK" when true or "NOPE" when is false
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

#define SIZET 15

int main()
{
int tab[SIZET];
int i=0,choose;
int hit = 0;

srand(time(NULL));
fflush(stdin);

printf("So, what u choose?: ");
scanf("$d",&choose);
for (i=0; i<SIZET; i++)
{
tab[i]=rand()%6;
printf(" %d",tab[i]);
}

printf("\n");
i=0;
while (i<SIZET && tab[i]!=choose)
{
i++;
}

if (i==SIZET)
{
printf("NOPE");
}
else
{
printf("OK!");
}



printf("\n");
system("pause");
return 0;
}


Someone can find mistakes? In the last while something is wrong (always pass) but i cannot figure out what... Thanks for advice

Answer

You had a small typo in it, as described in the comments.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// unused
// #include <stdbool.h>

#define SIZET 15

int main()
{
  int tab[SIZET];
  int i = 0, choose;
  // unused
  // int hit = 0;
  int res;

  srand(time(NULL));

  // No, just no.
  //fflush(stdin);

  // Changed because of intense pressure from the UX department:
  // printf("So, what u choose?: ");
  printf("Please enter a number: ");

  // The indicator for the start of a format term
  // is a '&' (ampersand, ASCII 0x26)
  //scanf("$d", &choose);
  res = scanf("%d", &choose);
  // check return value of scanf() because scanf() can fail
  if(res != 1){
    fprintf(stderr,"scanf() failed, try again\n");
    // There are two macros for the values the OS
    // recognizes as success and failure respectively.
    return EXIT_FAILURE;
  }
  for (i = 0; i < SIZET; i++) {
    tab[i] = rand() % 6;
    printf(" %d", tab[i]);
  }
  // printf() is a bit expensive to print just a newline
  //printf("\n");
  putchar('\n');

  i = 0;
  while (i < SIZET && tab[i] != choose) {
    i++;
  }

  if (i == SIZET) {
    // if you don't need to format any value use puts(),
    // it also adds a newline automatically
    puts("NOPE");
  } else {
    puts("OK!");
  }

  // not available everywhere
  //system("pause");
  return EXIT_SUCCESS;
}

There is more in it but you did not bad so far, you can build upon it.

Comments