Saturday, 15 June 2013

Guess The Random Number Game

One of the first programs i wrote and liked.

The computer generates a random number using the system clock to seed itself. Then asks you to guess it.
You get six tries. Every time you enter a guess it tells you if the number was too high, too low or if it is correct.

This was based on a program for the same game in C For Dummies. The way I try to solve this is enter half of the number range I have. First 50 (middle of 1 to 100), if it is too low enter 75 (Middle between 50 and 100). If 50 is too high enter 25 (Middle between 1 and 50), etc.

Here's the program:

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

int number;
void time_seed(void);
int random(int range);
main()
{
time_seed();
number=random(100)+1;
system("cls");
printf("I'm thinking of a number between and including 1 to 100.\nCan you guess the number in 6 tries?\n");
int a;
for(a=0;a<6;a++)
{
char b[20];
int input;
printf("Enter guess number %i: ",a+1);
input=atoi(gets(b));

if(input<1)
{
printf("Between and including 1 and 100 please!\n");
}
else if(input>100)
{
printf("Between and including 1 and 100 please!\n");
}
if(input<number)
{
printf("Too low!\n");
}
else if(input>number)
{
printf("Too high!\n");
}
else if(input==number)
{
printf("That's Correct! Cookie for you!");
system("pause >nul");
exit(0);
}

}
printf("Sorry! The number was %i! Better luck next time.",number);
system("pause >nul");
}

int random(int range)
{
int y;
y=rand()%range;
return(y);
}

void time_seed(void)
{
srand((unsigned)time(NULL));
}

1 comment:

  1. So this how number game works. Very interesting..
    --
    12BET Number Game

    ReplyDelete