I have to write a program where a user trys to pick a number. The code i've written below always exits after 2 guesses abd says the guess was correct even if it's wrong. Can anyone see what i'm doing wrong? Thanks

# include <stdio.h>
# define NUMBER 50

int main(void)
{
	int guess=0, count=0, loop=0;

	printf("Guess> ");
	scanf("%d", &guess);
	while (loop==0)
	{
	if (guess < NUMBER)
	{
		count++;
		printf("Too small - guess again> ");
		scanf("%d", &guess);
	}
	if (guess > NUMBER)
	{
		count++;
		printf("Too big - guess again> ");
		scanf("%d", &guess);
	}
	if (guess==NUMBER)
	{
		loop=1;
		count++;
		printf("Correct. That took you %d guesses.\n", count);
	}
	
	return 0;
	}
}

You should remove your scanf statements from the if {} and move them to under the while loop

Something like this will keep looping until you have the correct number. Or you could restrict the user to a maximum number of guesses.

while (loop==0){
   printf("Guess> ");
   scanf("%d", &guess);

   if (guess < NUMBER){
       ...............
   }
   else if (guess > NUMBER){
       ..................
   }
   else { //guess == NUMBER
      loop = 1;
      .......................
   }
 }

>always exits after 2 guesses abd says the guess was correct even if it's wrong
Not necessarily. If you enter 10, then 70, you get three guesses. By the look of things, the correct message won't print unless the guess really is correct, but you only ever have one iteration of the loop because your return statement is inside the loop.

Compare and contrast:

#include <stdio.h>

#define NUMBER 50

int main ( void )
{
  int count = 1;
  int guess;

  do {
    printf ( "Guess> " );
    fflush ( stdout );
    scanf ( "%d", &guess );

    if ( guess < NUMBER )
      printf ( "Too low\n" );
    else if ( guess > NUMBER )
      printf ( "Too high\n" );
    else
      printf ( "Correct! That took you %d guesses\n", count );
  } while ( count++ < 5 && guess != NUMBER );

  if ( count > 5 )
    printf ( "Sorry, you only get 5 guesses\n" );

  return 0;
}
This question has already been answered. Start a new discussion instead.