Thursday, March 15, 2012

Guess the Number

Program below plays the game of "guess the number" as follow:
The program choose the number to be guessed by selecting an integer at random in the range 1 to 1000.Then the player need to guess the number and if incorrect the program will display the clue either your guessed number is too low or too high until the player guessed the correct number.
[Note: The searching technique employed in this problem is called binary search.]
/*
   title: GuessTheNumber
   author: aeriqusyairi
   date: Jan24 2012
*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int randomNumber(void);

int main(){
   int guess = 0, random = 0;
   char replay = 'y';
   
   while(replay == 'y'){
      system("cls");
                
      random = randomNumber();
   
      printf("I have anumber between 1 and 1000.\nCan you guess my number?\nPlease type your first guess.\n");
   
      while(guess != random){
         scanf("%d", &guess);
      
         if(guess > random)
            printf("Too high. Try again.\n");
         else if(guess < random)
            printf("Too low. Try again.\n");            
      }
   
      printf("Excellent! You guessed the number!\nWould you like to play again (y or n)?\n");
      scanf(" %c", &replay);
   }
   
   system("pause");
   return 0;       
}

int randomNumber(void){
   srand(time(NULL));
   
   return 1 + rand() % 1000;                            
}

No comments:

Post a Comment