What number am I thinking of?
★★☆A simple guessing game for young children asks the child to guess the number the computer has chosen at random. The child keeps guessing until they guess correctly.
Write a program that generates a random number and asks the user to guess the number, outputting whether the guess is correct, too high or too low. The program should also output the number of guesses taken once the number has been guessed correctly.
Remember to add a comment before a subprogram, selection or iteration statement to explain its purpose.
play_guess_the_number that:OK, let's play. How many guesses will you take?.What is the lowest number I can choose? :
1
What is the highest number I can choose? :
10
OK, let's play. How many guesses will you take?
Enter the number I'm thinking of:
5
Your guess is too low.
Enter the number I'm thinking of:
7
You've got it, I chose 7. It took you 2 guesses.
// Guess the number program
using System;
class Submission
{
---
// -------------------------
// Globals
// -------------------------
static Random random_generator = new Random();
// -------------------------
// Subprograms
//--------------------------
// Routine to play the guess the number game
---
static void play_guess_the_number(int min, int max)
{
---
// Initialise variables
int cpu = random_generator.Next(min, max + 1);
int player_guess = 0;
int guess_count = 0;
---
// Continue playing until player wins
while (player_guess != cpu)
{
---
Console.WriteLine("Enter the number I'm thinking of:");
player_guess = Convert.ToInt32(Console.ReadLine());
guess_count = guess_count + 1;
---
// Check if guess is too high or too low
if (player_guess < cpu)
{
---
Console.WriteLine("Your guess is too low.");
---
}
---
else if (player_guess > cpu)
{
---
Console.WriteLine("Your guess is too high.");
---
}
---
}
---
Console.WriteLine($"You've got it, I chose {cpu}. It took you {guess_count} guesses.");
---
}
---
// -------------------------
// Main program
// -------------------------
public static void Main(string[] args)
{
---
Console.WriteLine("What is the lowest number I can choose? :");
int min = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("What is the highest number I can choose? :");
int max = Convert.ToInt32(Console.ReadLine());
---
Console.WriteLine("OK, let's play. How many guesses will you take?");
play_guess_the_number(min, max);
---
}
---
}