The correct ways to use rand() in selection structure

49 views Asked by At

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

There are 1 answers

4
dbush On

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.