1

Can anyone identify why the line : if(code == rand() && attempt != 3) not executed even I'm entered a correct code that generated by the rand().

#include <stdio.h>
#include <stdlib.h>
#include<time.h>
 
int main(void)
{

    int code, attempt = 0;
    srand(time(0));

    for(int i = 0; i<1; i++)
        printf("Your code is %d ", rand());
    
    do{    
    printf("\nEnter code: ");
    scanf("%d", &code);
    attempt++;
    
    }while ( code != rand() && attempt != 3);
    
    if(code == rand() && attempt != 3)
  {
      printf("\n Correct code");
      printf("\n");
  }
  else
  {
   printf("Incorrect code\n");
  }
    return 0;
}
  • 2
    What would be the point of a random generator if it returned the same number each time? – klutt Apr 08 '21 at 02:43

1 Answers1

0

The rand function is a random number generator. It returns a different number each time you call it.

Call rand once at the start of your program and save the result in a variable. Then check the user's guess against that.

dbush
  • 205,898
  • 23
  • 218
  • 273