1
Reply

guess a number 6 times...using while loop

Kristian Jude

Kristian Jude

Feb 9 2011 10:20 PM
13.9k
I'm pretty new in program C#...i need guidance...

this is what suppose to do...

·         Generate a random number from 1 to 100 inclusive.

·         Input a guess. Use a while loop to check the guess to ensure that it is within the range of 1 to 100, If the guess is outside that range, continue to input guesses until it is within the desired range.  Display an error message in yellow and honk the speaker (use a low frequency) if the guess was outside the range. Invalid guesses will not be counted.

·         Compare a valid guess with the secret number. If the guess was correct, honk the speaker (use a higher frequency) and display the secret number and the number of guesses required in green.

·         If the guess was lower than the secret number, display a message that the guess was too low.

·         If the guess was higher than the secret number, display a message that the guess was too high.

·         Continue to input guesses by using a while loop until the secret number has been guessed, or the number of guesses reaches 6.

·         If the number of guesses reaches 6 and the secret number was not guessed, display a message in yellow indicating that the player has lost the game, and show the secret number

    class Program
   {
        static void Main(string[] args)
        {       
            Console.Title = "ICA14 - Guess the Number";
            Random random = new Random();
            int iGuess = 0;
            int iCount = 0;
            int iRandom = random.Next(1, 100);


           Console.WriteLine("\t\t\tICA14 - Guess the Number");

            Console.WriteLine("\nTry to guess a secret number from 1 to 100 is 6 guesses.");

            Console.Write("\nEnter guess #1: ");
            iGuess = int.Parse(Console.ReadLine());
         

            while (iCount < 5)

            {
               while ((iGuess <= 0) || (iGuess > 100))
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You have entered an invalid guess.");
                    Console.ResetColor();
                    Console.Write("Enter guess #{0}: ", (iCount + 1));
                    iGuess = int.Parse(Console.ReadLine());

                    if (iGuess > iRandom)
                        Console.WriteLine("Your guess was too high");
                    Console.Write("Enter guess #{0}: ", (iCount + 1));
                    iGuess = int.Parse(Console.ReadLine());

                   else if (iGuess < iRandom)
                        Console.WriteLine("Your guess was too low");
                    Console.Write("Enter guess #{0}: ",(iCount + 1));
                   iGuess = int.Parse(Console.ReadLine());  
                }
            }
            Console.WriteLine("Press the <Enter> key to exit:");
            Console.ReadLine();
        }
    }


Answers (1)