This is a C# Program to perform a number guessing game.
This C# Program Performs a Number Guessing Game.
Here a Simple number guessing game is created.
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):"); int input = Convert.ToInt32(Console.ReadLine()); 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); } } }
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.
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.
- Get Free Certificate of Merit in C# Programming
- Participate in C# Programming Certification Contest
- Become a Top Ranker in C# Programming
- Take C# Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Apply for C# Internship
- Buy Computer Science Books
- Buy C# Books
- Practice MCA MCQs
- Buy MCA Books