Tutorial: Add math problems to a math quiz WinForms app

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

In this series of four tutorials, you'll build a math quiz. The quiz contains four random math problems that a quiz taker tries to answer within a specified time.

Controls use C# or Visual Basic code. In this second tutorial, you make the quiz challenging by adding code for math problems that are based on random numbers. You also create a method that's named StartTheQuiz() to fill in the problems.

In this second tutorial, you learn how to:

  • Write code to create Random objects to use in math problems.
  • Add an event handler for the start button.
  • Write code to start the quiz.

Prerequisites

This tutorial builds on a previous tutorial, Create a math quiz WinForms app. If you haven't completed that tutorial, go through it first.

Create a random addition problem

  1. In your Visual Studio project, select Windows Forms Designer.

  2. Select the form, Form1.

  3. On the menu bar, select View > Code. Form1.cs or Form1.vb appears, depending on the programming language that you're using, so that you can view the code behind the form.

  4. Create a Random object by adding a new statement near the top of the code.

    public partial class Form1 : Form
    {
        // Create a Random object called randomizer 
        // to generate random numbers.
        Random randomizer = new Random();
    
    Public Class Form1
    
        ' Create a Random object called randomizer 
        ' to generate random numbers.
        Private randomizer As New Random
    

    Important

    Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic code snippet.

    Programming language control for Docs.Microsoft.com

    You can use new statements like this one to create buttons, labels, panels, OpenFileDialogs, ColorDialogs, SoundPlayers, Randoms, and even forms. These items are called objects.

    When you run your program, the form is started. The code behind it creates a Random object and names it randomizer.

    Your quiz needs variables to store the random numbers that it creates for each problem. Before using variables, you declare them, which means listing their names and data types.

  5. Add two integer variables to the form, and name them addend1 and addend2.

    Note

    An integer variable is known as an int in C# or an Integer in Visual Basic. This kind of variable stores a positive or negative number from -2147483648 through 2147483647 and can store only whole numbers, not decimals.

    You use similar syntax to add an integer variable as you did to add the Random object, as the following code shows.

    // Create a Random object called randomizer 
    // to generate random numbers.
    Random randomizer = new Random();
    
    // These integer variables store the numbers 
    // for the addition problem. 
    int addend1;
    int addend2;
    
    ' Create a Random object called randomizer 
    ' to generate random numbers.
    Private randomizer As New Random
    
    ' These integer variables store the numbers 
    ' for the addition problem. 
    Private addend1 As Integer
    Private addend2 As Integer
    
  6. Add a method that's named StartTheQuiz(). This method uses the Random object's Next() method to generate random numbers for the labels. StartTheQuiz() will eventually fill in all the problems and then start the timer, so add this information to the summary comment. The function should look like the following code.

    /// <summary>
    /// Start the quiz by filling in all of the problems
    /// and starting the timer.
    /// </summary>
    public void StartTheQuiz()
    {
        // Fill in the addition problem.
        // Generate two random numbers to add.
        // Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
    
        // Convert the two randomly generated numbers
        // into strings so that they can be displayed
        // in the label controls.
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
    
        // 'sum' is the name of the NumericUpDown control.
        // This step makes sure its value is zero before
        // adding any values to it.
        sum.Value = 0;
    }
    
    ''' <summary>
    ''' Start the quiz by filling in all of the problems
    ''' and starting the timer.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub StartTheQuiz()
        ' Fill in the addition problem.
        ' Generate two random numbers to add.
        ' Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51)
        addend2 = randomizer.Next(51)
    
        ' Convert the two randomly generated numbers
        ' into strings so that they can be displayed
        ' in the label controls.
        plusLeftLabel.Text = addend1.ToString()
        plusRightLabel.Text = addend2.ToString()
    
        ' 'sum' is the name of the NumericUpDown control.
        ' This step makes sure its value is zero before
        ' adding any values to it.
        sum.Value = 0
    End Sub
    

    When you use the Next() method with a Random object, such as when you call randomizer.Next(51), you get a random number that's less than 51, or between 0 and 50. This code calls randomizer.Next(51) so that the two random numbers add up to an answer that's between 0 and 100.

    Take a closer look at these statements.

    plusLeftLabel.Text = addend1.ToString();
    plusRightLabel.Text = addend2.ToString();
    
    ' Convert the two randomly generated numbers
    ' into strings so that they can be displayed
    ' in the label controls.
    plusLeftLabel.Text = addend1.ToString()
    plusRightLabel.Text = addend2.ToString()
    

    These statements set the Text properties of plusLeftLabel and plusRightLabel so that they display the two random numbers. Label controls display values in text format, and in programming, strings hold text. Each integer's ToString() method converts the integer into text that a label can display.

Create random subtraction, multiplication, and division problems

The next step is to declare variables and provide random values for the other math problems.

  1. Add integer variables for the remaining math problems to your form, after the addition problem variables. The code should look like the following sample.

    Public Class Form1
    
        ' Create a Random object called randomizer 
        ' to generate random numbers.
        Private randomizer As New Random
    
        ' These integer variables store the numbers 
        ' for the addition problem. 
        Private addend1 As Integer
        Private addend2 As Integer
    
    
        ' These integer variables store the numbers 
        ' for the subtraction problem. 
        Private minuend As Integer
        Private subtrahend As Integer
    
        ' These integer variables store the numbers 
        ' for the multiplication problem. 
        Private multiplicand As Integer
        Private multiplier As Integer
    
        ' These integer variables store the numbers 
        ' for the division problem. 
        Private dividend As Integer
        Private divisor As Integer
    
    public partial class Form1 : Form
    {
        // Create a Random object called randomizer 
        // to generate random numbers.
        Random randomizer = new Random();
    
        // These integer variables store the numbers 
        // for the addition problem. 
        int addend1;
        int addend2;
    
        // These integer variables store the numbers 
        // for the subtraction problem. 
        int minuend;
        int subtrahend;
    
        // These integer variables store the numbers 
        // for the multiplication problem. 
        int multiplicand;
        int multiplier;
    
        // These integer variables store the numbers 
        // for the division problem. 
        int dividend;
        int divisor;
    
  2. Modify the StartTheQuiz() method by adding the following code, starting with the "Fill in the subtraction problem" comment.

    ''' <summary>
    ''' Start the quiz by filling in all of the problem 
    ''' values and starting the timer. 
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub StartTheQuiz()
    
        ' Fill in the addition problem.
        ' Generate two random numbers to add.
        ' Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51)
        addend2 = randomizer.Next(51)
    
        ' Convert the two randomly generated numbers
        ' into strings so that they can be displayed
        ' in the label controls.
        plusLeftLabel.Text = addend1.ToString()
        plusRightLabel.Text = addend2.ToString()
    
        ' 'sum' is the name of the NumericUpDown control.
        ' This step makes sure its value is zero before
        ' adding any values to it.
        sum.Value = 0
    
        ' Fill in the subtraction problem.
        minuend = randomizer.Next(1, 101)
        subtrahend = randomizer.Next(1, minuend)
        minusLeftLabel.Text = minuend.ToString()
        minusRightLabel.Text = subtrahend.ToString()
        difference.Value = 0
    
        ' Fill in the multiplication problem.
        multiplicand = randomizer.Next(2, 11)
        multiplier = randomizer.Next(2, 11)
        timesLeftLabel.Text = multiplicand.ToString()
        timesRightLabel.Text = multiplier.ToString()
        product.Value = 0
    
        ' Fill in the division problem.
        divisor = randomizer.Next(2, 11)
        Dim temporaryQuotient As Integer = randomizer.Next(2, 11)
        dividend = divisor * temporaryQuotient
        dividedLeftLabel.Text = dividend.ToString()
        dividedRightLabel.Text = divisor.ToString()
        quotient.Value = 0
    
    /// <summary>
    /// Start the quiz by filling in all of the problem 
    /// values and starting the timer. 
    /// </summary>
    public void StartTheQuiz()
    {
        // Fill in the addition problem.
        // Generate two random numbers to add.
        // Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
    
        // Convert the two randomly generated numbers
        // into strings so that they can be displayed
        // in the label controls.
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
    
        // 'sum' is the name of the NumericUpDown control.
        // This step makes sure its value is zero before
        // adding any values to it.
        sum.Value = 0;
    
        // Fill in the subtraction problem.
        minuend = randomizer.Next(1, 101);
        subtrahend = randomizer.Next(1, minuend);
        minusLeftLabel.Text = minuend.ToString();
        minusRightLabel.Text = subtrahend.ToString();
        difference.Value = 0;
    
        // Fill in the multiplication problem.
        multiplicand = randomizer.Next(2, 11);
        multiplier = randomizer.Next(2, 11);
        timesLeftLabel.Text = multiplicand.ToString();
        timesRightLabel.Text = multiplier.ToString();
        product.Value = 0;
    
        // Fill in the division problem.
        divisor = randomizer.Next(2, 11);
        int temporaryQuotient = randomizer.Next(2, 11);
        dividend = divisor * temporaryQuotient;
        dividedLeftLabel.Text = dividend.ToString();
        dividedRightLabel.Text = divisor.ToString();
        quotient.Value = 0;
    

    This code uses the Next() method of the Random class a little differently from how the addition problem does. When you give the Next() method two values, it picks a random number that's greater than or equal to the first value and less than the second one.

    By using the Next() method with two arguments, you can ensure the subtraction problem has a positive answer, the multiplication answer is at most 100, and the division answer isn't a fraction.

Add an event handler to the start button

In this section, you add code to start the quiz when the start button is selected. Code that runs in reaction to an event like a button selection is called an event handler.

  1. In Windows Forms Designer, either double-click the Start the quiz button, or select it and then select Enter. The form's code appears, and a new method is visible.

    These actions add a Click event handler to the start button. When a quiz taker selects this button, the app runs the code that you'll add to this new method.

  2. Add the following two statements so that the event handler starts the quiz.

    private void startButton_Click(object sender, EventArgs e)
    {
        StartTheQuiz();
        startButton.Enabled = false;           
    }
    
    ' Call the StartTheQuiz() method and enable
    ' the Start button. 
    Private Sub startButton_Click() Handles startButton.Click
        StartTheQuiz()
        startButton.Enabled = False
    End Sub
    

    The first statement calls the new StartTheQuiz() method. The second statement sets the Enabled property of the startButton control to false so that the quiz taker can't select the button during a quiz.

Run your app

  1. Save your code.

  2. Run your app, and then select Start the quiz. Random math problems appear, as the following screenshot shows.

    Screenshot that shows random values in all four math problems. The Start the quiz button appears dimmed.

Next steps

Advance to the next tutorial to add a timer to your math quiz and check user answers.