﻿ 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:

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

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)
{
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:");

}

}
}

}