# Number Guessing Game in C#

«
»

This is a C# Program to perform a number guessing game.

Problem Description

This C# Program Performs a Number Guessing Game.

Problem Solution

Here a Simple number guessing game is created.

Program/Source Code

Here is source code of the C# Program to Perform a Number Guessing Game. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

```/*
* C# Program to Perform a Number Guessing Game
*/
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
while (true)
{
int randno = Newnum(1, 101);
int count = 1;
while (true)
{
Console.Write("Enter a number between 1 and 100(0 to quit):");
if (input == 0)
return;
else if (input < randno)
{
Console.WriteLine("Low, try again.");
++count;
continue;
}
else if (input > randno)
{
Console.WriteLine("High, try again.");
++count;
continue;
}
else
{
Console.WriteLine("You guessed it! The number was {0}!",
randno);
Console.WriteLine("It took you {0} {1}.\n", count,
count == 1 ? "try" : "tries");
break;
}
}
}

}
static int Newnum(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
}
}```
Program Explanation

In this C# program, we are reading a number between 1 and 100, using ‘input’ variable. Nested if else condition statement is used to check the value of ‘input’ variable is equal to 0, if the condition is true then execute if condition statement.

Otherwise, if the condition is false then execute the elseif statement. Check the condition that the value of ‘input’ variable is greater than the value of ‘randno’ variable. If the condition is true then execute the statement and print the statement as the value is low try again. Decrement the value of ‘count’ variable.

Otherwise, if the condition is false then execute another elseif statement. Check the value of ‘input’ variable is greater than the value of ‘randno’ variable. If the condition is true then execute the elseif statement.

Print the statement as the value is high try again and decrement the value of ‘count’ variable. Otherwise if the condition is false then execute the else statement and print the guessed number.

Runtime Test Cases
```
Enter a number between 1 and 100(0 to quit) : 56
Low,try again.
Enter a number between 1 and 100(0 to quit): 67
high,try again.
Enter a number between 1 and 100(0 to quit): 59
You guessed it! The number was 59
It took you 2 tries!!!```

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs. 