Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: trying a simple project

Tags:

c#

while-loop

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


2 Answers

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");
}
like image 119
Erick B Avatar answered Jun 28 '26 06:06

Erick B


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);
like image 40
k...m Avatar answered Jun 28 '26 07:06

k...m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!