tags:

views:

463

answers:

5

Hello,

I am new to C#. I wanted to do a simple program with some type of loops. I wanted my program to loop through the numbers that the user enters and if it is less than a number then write keep guessing,but once they enter the number 25 i wanted it to say Merry Christmas.. Please Help

int number;

do
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
}  while (number < 25);

C# Beginner

+1  A: 
int number;

do
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
} while (number < 25);

if (number == 25)
    Console.WriteLine("Merry Christmas");
Gavin Miller
What if they enter 26? The loop will exit on values over 25 and there is still the issue of what if the user enters nothing?
JB King
It isn't my job to code and debug...
Gavin Miller
+6  A: 

Try the following:

int number = 0;
while (number != 25)
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
    if (number != 25)
        Console.WriteLine("Keep guessing");
    else
        Console.WriteLine("Merry Christmas");
}
Erick B
A: 
int number;

do
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
} while (number != 25);

Console.WriteLine("Merry Christmas");

Would be correct if you want them to be able to enter numbers higher than 25.

mannu
+2  A: 

I'm not sure what your question is, but I've got a couple of comments:

  1. An exception will be thrown if the user enters something that can't be parsed as an int. Fix this by using TryParse.

  2. As written, the loop will exit if the user enters a number greater than 25, such as 26.

Modified code:

int number;
do
{
    Console.WriteLine("Guess a number between 20 through 25");
    int.TryParse(Console.ReadLine(), out number);
} while (number != 25);
k...m
+2  A: 

If you are never going to use the input as a number, it is safer to just leave it a string, expecialy since you are only checking for "25" exactly. Also, adding a way to exit without entering 25 would be nice for the user, like entering a blank line for example.

Here is how I would write it:

    static void x()
    {
        Console.WriteLine("Guess a number between 20 through 25");
        string input = null;
        while(true)
        {
            input = Console.ReadLine();
            if (input == null || input.Length == 0)
                break; // will exit the loop
            if (input != "25")
                Console.WriteLine("Keep guessing");
            else
            {
                Console.WriteLine("Merry Christmas");
                break;
            }
        }
    }
rally25rs