C Program to Guess a Number

From Deitel C how to program(Making a difference)


This is a carefully sort out source of in c program that plays "guess the number" as follows:

The program chooses the number to be guessed by selecting a random integer in the range 1 to 1000.. The player types a first guess and presses the Enter key.

If the player guess is incorrect, the program displays 'Too high.Try again or Too Low. Try again.

When the user enters the correct answer, displays 'Congratulations. You guessed the number!

We will basically be using the IF Statements to compare user input to determine if it matches the random generated number. So we use the if statement to determine if the number input by the user is correct else the program either prints out too high or too low. 

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

int main(void)
{
    int a=0, b=0;
    int choice;

srand(time(NULL));

    a = 1 + rand() % 1000;

    printf("\tGUESS THE NUMBER\n");
    printf("I have a number between 1-1000\n can you guess my number?\n");
    printf("Please type in your first guess: ");
    scanf("%d", &b);

    if (b== a){
        printf("Congratulations! you guessed the number!\n");

        }

    }else{
        while (b<a){
            printf("Too low! Try again: ");
            scanf("%d", &b);

        }
        while (b > a){
            printf("Too high! Try again: ");
            scanf("%d", &b);
        }
    }
return 0;
}

Note:
The srand(x) function sets the seed of the random number generator algorithm used by the function rand( ). while:   a = + rand() % 1000 generates a number from 1-1000

Comments

Popular posts from this blog

Body Mass Index Calculator In C

Adding two Integers in Java Application

Calculating Product, sum, difference, and quotient of Five Integers