C# Programming Example: Random Number from 1 to 5

C# TASK:

Create an application that sets a random number from 1 to 5, and asks the user to guess it. Both correct and incorrect guesses should be handled.

SOLUTION:

In this sample, we will show how to generate random numbers within a predetermined range, as well as provide some tips on the optimal way to use a random number generator.

Probably the most important thing that you’ll need to know is that the numbers generated will be pseudo-random, based on a system clock. While you can explicitly supply the same seed value to a pair of random number generators (forcing them to produce identical results), it is generally better to use the default setting which relies on a system clock – as it would provide different values as the time goes on.

But keep in mind that the system clock resolution is finite. Therefore, launching two separate random number generators within a very short amount of time (happens often inside of a loop) most likely will seed them with the same timestamp, resulting in two identical sets of random numbers. In such cases, it is recommended to create a single static instance of a random number generator, and then call it each time you need a random number.

This will be our initial code inside Main:

C# Programming Example

At first glance, this application seems to work fine. However, that is as long as we input numbers from 1 to 5. When the user inputs a number outside of this range, it is still handled (although not in the best way, since the user is not notified about having inputted a wrong number). But right now, the user is also able to input any non-digit (even an empty string, simply by pressing Enter without any extra inputs) which causes the application to throw an exception. Therefore, we need to analyze the data entered by the user first, and query the user to input the correct data (if necessary) before processing it. After applying the necessary changes, we obtain the following result:

C#_Programming_Example

With this, the application reacts correctly to any combination of symbols. This major improvement became available thanks to the conversion of string to int using the TryParse method. As this method returns a boolean value to indicate whether the conversion succeeded, it allows us to cover all non-digit inputs as failed conversion cases (returning “false”).

Hope, our C# programming example explanations were clear and understandable for you. Contact us any time of the day and night to get help with technical assignments of any difficulty level.

Here you can find one more of our C# programming examples.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Customer testimonials

Submit your instructions to the experts without charge.