Several new features have been added to the board, check the Announcements for more details!

How to Create a Random Number Generator (Part 2)

Here you can learn how to do many things on the computer or a programming environment.
User avatar

Topic Author
Board Moderators
Board Moderators
Posts: 546
Joined: 11 Aug 2011, 19:02
Tech Knowledge: Advanced
Location: Maryland

How to Create a Random Number Generator (Part 2)

Postby AVenger » 23 Apr 2012, 02:11

This [b]How To[/b] will expand on the [url=]Random Number Generator we created in the last [b]How To[/b][/url]. If you don't want to follow the entire how to so you can catch up with the code, here is the finished code:
[spoiler][code]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

* @author: Tyler Candee (AVenger)
* @date: April 17, 2012
* @title: Random Number Generator 1
* @description: This program asks the user for a number and then generates
* a random number from 1 to the number specified.
* @class-list: Main(string[] args)

namespace RandomNumberGenerator_1
class Program
static void Main(string[] args)
string number = ""; // declares a variable for the inputed number
int num = 0; // declares a variable for the converted number
int randomNum = 0; // declares a variable for the randomly generated number

Console.WriteLine("Enter the maximum number you would like this generator to generate up to:");
Console.Write("> ");
number = Console.ReadLine(); // stores what the user inputs into the 'number' variable

num = Convert.ToInt32(number); // converts the data in the 'number' variable to an integer

Random ran = new Random(); // creates a new instance of the 'Random' class

randomNum = ran.Next(1, num); // generates a random number between 1 and 'num'

Console.WriteLine("Your random number is: {0}", randomNum); // prints the results to the console
Console.ReadLine(); // waits for the user to press 'Enter' and then exits
Now that we are all caught up, we can continue to expand the program. We are going to complicate the generating algorithm so that it will generate three random numbers and then randomly pick one of those numbers. We are also going to add another method to do all of this in so we don't just have to use the "Main" method.

Step 1: So the first step is to create the second method: the "Generate" method. Move down to the end of the "Main" method, right after the curly bracket ( { } ). Hit "Enter" twice and enter the following code.
[code]private static int Generate(int num)

This is the method declaration. Let's go through it. The first word is "private" and is there to help the computer know what part of the program can use the code in the method. Since it is private, only the immediate class ("RandomNumberGenerator_2") can use the code inside the brackets. If it was public, any class inside the project could use the code. It is not particularly needed if you have a small project like ours, but it is good coding practice for when bigger programs come your way.
The second word "static" helps you so that you won't have to make a separate instance of the method before you use it. When we wrote "Random ran = new Random()", that was creating a new instance of the class "Random." If we are using a method in a small program, we shouldn't need to create a new instance of the method before we use it. We'll get to using the method we create soon.
The letters "int" replace the "void" in the "Main" method declaration. "void" means that the method won't return anything if called upon. "int" means that the method will return an integer value when called on.
Finally, "Generate(int num)" is the name of the method ("Generate") and what the method needs from the call. When we call this method, we could type "int number = Generate(10)" and that would send "10" to the method, execute the method, then return the results to "number."

Step 2: Let's do that now. Edit your "Main" method and change this line
[code]Random ran = new Random(); // creates a new instance of the 'Random' class

randomNum = ran.Next(1, num); // generates a random number between 1 and 'num'[/code]
to this
[code]randomNum = Generate(num); // generates a random number between 1 and 'num'[/code]
You will get an error that "Generate does not return any values." We will fix that soon.

Step 4: Now we need to create some variables inside our new method. Go inside the "Generate" method and copy this code.
[code]int returnNum = 0, randomNum = 0;
int[] randomArr = new int[3];[/code]
This just creates two new integers named "returnNum" (used for the return number when we are done) and "randomNum" (used to store a random number). Also, we create an integer array named "randomArr" and initialize it to 3 indexes. This means that we can store up to three different values in this array. When we use the array, we would use it like this:
This would print out what is contained in the first index. The computer begins counting at 0 and not 1. So when using an array, the first value is held at the index 0, the second value is held at the index 1, and so on.

Step 5: Next, we can create a new instance of the "Random" class again since we deleted our old one.
[code]Random ran = new Random();[/code]

Step 6: The next step is to fill the array with 3 random numbers that do not exceed the number specified. To do this, we create a simple "for" loop. A loop is a block of code that continues executing until a certain condition is meant. A "for" loop is probably one of the hardest ones to understand (took me half a year to finally master), so I will try to go slow with it. First, paste this code under the last line we entered.
[code]for (int i = 0; i < 3; i++)

Let's take a look at what we just typed. First the word "for." This is the name of the loop we are using and so it goes first. If we where using a "while" loop, "while" would be the first word, followed by parenthesis just like this one.
Inside the parenthesis, the first set of code is "int i = 0." This creates a new variable inside the "for" loop. This variable is used as a counter in this case, but can also be changed inside the loop.
The next set of code is "i < 3." This is the condition we were talking about earlier. As long as "i" is less then 3, the loop will run. Once "i" becomes 3 or any number greater than 3, the loop ends.
Finally, the last set of code is "i++." This is what will happen every time the loop iterates (runs through). After the loop goes through once, it will increase "i" by one. That's what the "++" after the "i" was: adding one to the current value. If we used "i--", that would subtract one from "i" each iteration.
So let's look at it all together. We first set "i" equal to 0; then say that as long as "i" is less than 3, then we can run the loop; and after each iteration, "i" will be increased 1.

Step 7: But we need some code inside the loop so that the array is filled with random numbers. Add this code inside the brackets of the "for" loop.
[code]randomArr[i] = ran.Next(1, num);[/code]
If you remember from the last how to, "ran.Next(1, num)" will generate a random number from 1 to the number specified by the user. But let's look at the code before that. "randomArr[i]" was the array name we declared earlier. We use the square brackets ( [ ] ) this time with the "i" between them. If you remember when we printed out the first index of the array when we created the array ("randomArr[0]"), we used the number 0. In this case, we use the variable "i" which contains a number. The value of "i" is determined on where the loop is at the time the code is entered. If the loop just started, then "i" is 0 like we said in the "for" loop declaration ("(int i = 0; i < 3; i++)"). If the loop is iterated once, then "i" is "i" + 1 ("i++") which would equal 1. "randomArr[0]" and "randomArr[1]" are two different parts of the array and can hold two different values.
So in the end, what the loop does is it goes through each index in the array and fills it with a random number.
Something fancy you can do with your "for" loop in this case is take out the curly brackets. If there is only one line of code in the "for" loop, you can exclude the brackets and indent the one line of code so the computer knows that this is the only line of code to execute.

Step 8: Now we need to randomly pick one of those three generated values. This is where the variable "randomNum" comes in that we declared before. Put this code under the "for" loop we just created.
[code]randomNum = ran.Next(1, 3);[/code]
We already know what this code will do for us. So let's move on to the next step.

Step 9: In this step, we will create a "switch" block that will select which random number we will return. A "switch" block is an alternative to an "if else" block. In an "if else" block, we would basically say:
[quote]If randomNum is equal to 1 then return randomArr[0]
Else if randomNum is equal to 2 then return randomArr[1]
Else if randomNum is equal to 3 then return randomArr[2][/quote]
But an easier way of doing this is with a "switch" block. In a "switch" block we would use "cases" instead. Put this code in your program.
[code]switch (randomNum)
case 1:
returnNum = randomArr[0];
case 2:
returnNum = randomArr[1];
case 3:
returnNum = randomArr[2];
returnNum = 0;
What this does is creates a block off the value of "randomNum." In the first case ("case 1:"), we would make "returnNum" equal to the first index of the "randomArr" array. This continues on until we reach the "default" case where "returnNum" equals 0. This is basically a fail-safe for the program. If "randomNum" some how happens to be initialized to a number other than 1, 2, or 3, then this case would execute.
Under each statement, there is the word "break." This word is important in a switch block. If we were to skip this word, the computer would continue onto the next case. So for instance, if we took out the "break" between case 3 and the default case, the computer would execute case 3 (making "returnNum" equal to "randomArr[2]"), then execute the default case also (making "returnNum" equal to 0), and then break. In the end, "returnNum" would equal 0 because the last time it was changed was in the default case. Make sure you include the "break" so that the computer won't do something you don't want it to do.

Step 10: Now that we have which random number to return, we should return that number so that it can be printed onto the screen. Put this code just below the end of the "switch" block.
[code]return returnNum;[/code]

And that is it. The computer will now generate three different random numbers between 1 and the number specified by the user and then randomly pick a number to return to the user. It looks exactly the same for the user; but for us, the code is quite different.

User avatar

Cpt. Blackbeard
Site Owner
Site Owner
Posts: 704
Joined: 08 Jan 2012, 23:37
Tech Knowledge: Intermidiate
Location: U.S.A.

Re: How to Create a Random Number Generator (Part 2)

Postby Cpt. Blackbeard » 23 Apr 2012, 13:51

Great Article Avenger, thanks for sharing.

Return to “How-tos”

Who is online

Users browsing this forum: No registered users and 1 guest