﻿ C# exercises and solutions-random number

# C# exercises and solutions-random number

## Random number in C#

### Exercise 1: Write a C# program to allow a user to guess a number( from 1 to 6) that will be randomly generated by computer.

The user is asked to input his/her number. Then the number will be compared with the random number. See the example below:

Enter your number: 2
You lost.
My number is: 4

Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{

class Program
{

static void Main(string[] args)
{

ranguess();

}

public static void ranguess()
{
int yn, rn;
Random rd = new Random(); //create random object

Console.Write("Enter your guess number:");
rn =rd.Next(1,7);//generate random number from 1 t 6
Console.WriteLine(rn);
if (yn == rn)
{
Console.WriteLine("You won.");

}
else
{
Console.WriteLine("You lost.");
Console.WriteLine("My number is {0}.", rn);

}

}
}

}

### Exercise 2: Modify the C# program above in order to have chances to continue or stop guessing.

Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{

class Program
{

static void Main(string[] args)
{

ranguess();

}

public static void ranguess()
{
int yn, rn;
int con=1;
Random rd = new Random(); //create random object
while (con == 1)
{
Console.Write("Enter your guess number:");
rn =rd.Next(1,7);//generate random number from 1 t 6
Console.WriteLine(rn);
if (yn == rn)
{
Console.WriteLine("You won.");

}
else
{
Console.WriteLine("You lost.");
Console.WriteLine("My number is {0}.", rn);

}

Console.Write("Press 1 to continue:");

}

}
}

}

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.