12,831,559 members (27,770 online)
Tip/Trick
Add your own
alternative version

#### Stats

16K views
348 downloads
9 bookmarked
Posted 18 Jun 2014

# C#: Random Number Guessing Game

, 18 Jun 2014 CPOL
 Rate this:
Please Sign up or sign in to vote.
A simple C# program to implement a "Random Number Guessing Game"

## Introduction

This article will give you some tips to write a simple "Random Number Guessing Game" using C#. The program generates a 4 digit random number. For each digit, the number is chosen from 1 to 5 and the number can repeat. You have 5 attempts to guess the random number.

For example, if the random number generated is 5241 and Your Guess is 2143 in the first attempt then the program will display a message "Digit(s) in place 3 correct" indicating that the number entered at position 3 is correct.

## Code

```using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
public class Result
{
public int Index { get; set; }
public bool Flag { get; set; }
}

static void Main()
{
Program game = new Program();
game.Run();
}

void Run()
{
// initialize the number of attempts
int numberOfAttempts = 5;

Console.WriteLine("\nWelcome to Random Number Guessing Game.");
Console.WriteLine("\n\nGuess the 4 digit random number XXXX.");
Console.WriteLine("\nFor each digit, the number is chosen from 1 to 5  \nNumbers can repeat.");
Console.WriteLine(string.Format("\nYou have {0} attempts to win the game.", numberOfAttempts));

// Call the method to Generate the Random Number
string randomNumber = GenerateRandomNumber();

for (int i = 1; i <= numberOfAttempts; i++)
{
// Call the method to get the user input
string userInput = GetUserInput(i);

// Get the result - Collection containing the result of all 4 digits
List<Result> result = GetResult(randomNumber, userInput);

// Guess the count of number of digits that are correct
int flagCount = result.Where(f => f.Flag == true).Count();

// Get the place(s)/index of digits that are correct
string digitsCorrect = string.Join(",", result.Where(f => f.Flag == true)
.Select(c => (++c.Index).ToString()));

// check the flag count and display appropriate message
if (flagCount == 4)
{
Console.WriteLine("Random Number:{0} , Your Input:{1}", randomNumber, userInput);
Console.WriteLine("You guess is correct! Game Won..hurray...:)");
break;
}
else if (i == numberOfAttempts)
{
Console.WriteLine("sorry, You missed it! Game Lost..:(");
Console.WriteLine("Random Number is {0}", randomNumber);
}
else
{
digitsCorrect = flagCount == 0 ? "none" : digitsCorrect;
Console.WriteLine(string.Format("Digit(s) in place {0} correct", digitsCorrect));
}
}

Console.ReadLine();
}

public List<Result> GetResult(string randomNumber, string userInput)
{
char[] splitRandomNumber = randomNumber.ToCharArray();
char[] splitUserInput = userInput.ToCharArray();

List<Result> results = new List<Result>();

for (int index = 0; index < randomNumber.Length; index++)
{
Result result = new Result();
result.Index = index;
result.Flag = splitRandomNumber[index] == splitUserInput[index];
results.Add(result);
}

return results;
}

public string GetUserInput(int attempt)
{
int inputNumber;

Console.WriteLine(string.Format("\nGuess the number. Attempt:{0}", attempt));
Console.WriteLine("Input a 4 digit number");

if (int.TryParse(Console.ReadLine(), out inputNumber)
&& inputNumber.ToString().Length == 4)
{
return inputNumber.ToString();
}
else
{
Console.WriteLine("You have entered a invalid input.");
return "0000";
}
}

public string GenerateRandomNumber()
{
Random random = new Random();
string number = string.Empty;
int length = 4;

for (int i = 0; i < length; i++)
{
number += random.Next(1, 6);
}

return number;
}
}
```

Happy Coding!!!!

## License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

## About the Author

 Technical Lead India

 Pro

## Comments and Discussions

 First Prev Next
 My vote of 4 Kaushal Jain21-Jun-14 23:09 Kaushal Jain 21-Jun-14 23:09
 My vote of 5 Volynsky Alex21-Jun-14 1:18 Volynsky Alex 21-Jun-14 1:18
 Re: My vote of 5 John-ph21-Jun-14 1:31 John-ph 21-Jun-14 1:31
 Re: My vote of 5 Volynsky Alex21-Jun-14 1:33 Volynsky Alex 21-Jun-14 1:33
 I did things like this in the first year of studying programming csakii20-Jun-14 12:21 csakii 20-Jun-14 12:21
 Re: I did things like this in the first year of studying programming John-ph21-Jun-14 1:23 John-ph 21-Jun-14 1:23
 Liked a lot...so posting a bit more improved version using StringBuilder, no LINQ etc AnandChavali19-Jun-14 1:49 AnandChavali 19-Jun-14 1:49
 Re: Liked a lot...so posting a bit more improved version using StringBuilder, no LINQ etc John-ph19-Jun-14 2:27 John-ph 19-Jun-14 2:27
 Re: Random Number Guessing Game CodeFrux Technologies18-Jun-14 23:00 CodeFrux Technologies 18-Jun-14 23:00
 Re: Random Number Guessing Game John-ph19-Jun-14 2:27 John-ph 19-Jun-14 2:27
 Code Correction Yugandhar Lakkaraju18-Jun-14 9:28 Yugandhar Lakkaraju 18-Jun-14 9:28
 Re: Code Correction Dewey18-Jun-14 19:05 Dewey 18-Jun-14 19:05
 Re: Code Correction John-ph19-Jun-14 2:27 John-ph 19-Jun-14 2:27
 Last Visit: 31-Dec-99 19:00     Last Update: 30-Mar-17 15:50 Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170326.1 | Last Updated 18 Jun 2014
Article Copyright 2014 by John-ph
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid