There are many times in computer programs that we want to introduce some kind of random behaviour. This could be for randomly generated levels in a game, random motion for some kind of a simulation, or to choose random questions for a quiz program.

Unfortunately, computers can't make truly random choices; everything a computer does is based on calculations. However, computers can generate pseudo-random numbers; numbers that technically follow a pattern, but the pattern is almost impossible to figure out.

To generate a pseudo-random number in Visual Basic, there are two steps:

1. Create a variable of type "Random"

2. Use one of the following commands to generate your random number:

(Assume that rand has been declared as a variable of type “Random”)
rand.Next() – Generate a random integer between 0 and the maximum possible integer value
rand.Next( a ) – Generate a random integer that is >= 0 and < a
rand.Next( a, b ) – Generate a random integer that is >= a and < b
rand.NextDouble() – Generate a random number that is >= 0.0 and < 1.0

For example, the following program simulates rolling a pair of dice:

Dim rand as Random
Dim iDie1, iDie2, iDieTotal as Integer

rand = New Random
iDie1 = rand.Next(1, 7)
iDie2 = rand.Next(1, 7)

iDieTotal = iDie1 + iDie2

Assignment:

Create math quiz program, similar to the following: see image.

Your program should:

  • Generate random math questions. Both the integers and the operation (+, -, *, /) should be random
  • Include both positive and negative integers. Enclose negative values in parentheses
  • Allow the user to answer the question, and keep track of how many answers the user gets correct
  • You must include comments. Generally, every line of code should be preceded by a comment that explains what it is for

Extensions:

  • Include exponents and square roots (all values, including answers, should still be integers)
  • Have multiple difficulty levels; changing levels should allow for larger numbers, as well as more difficult operations (for example, square roots are only included if the difficulty is increased)
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.