Building Your First Project in Visual Basic – Math Calculator – Chapter 3 – Visual Basic

Chapter 3

Build your first project on VB6. – Math Calculator

Includes:

  1. Deciding what the application will do and its working
  2. Starting Visual Basic 6
  3. Designing the User Interface
  4. Programming the Math Calculator
  5. Math Operations

Before doing any project you (programmer) have to collect some ideas, and methods how you are going to make that project complete in a short time period with less bugs and thus obtained output is user friendly. There is a model called SDLC (System Development Life Cycle) which describes the concept of programming or software development in a systematic or step by step model. I will try to describe our first project in concept of SDLC. There are somewhat like seven steps in SDLC in detail but you can also make it yourself in your comfort – shorter or lengthen).

For our first project I am going to build a Math Calculator in VB6 so according to model of SDLC let me complete the project. Please go through to understand the work completely. 

Deciding what the application will do and its working

As we are going to develop a simple math calculator program using Visual Basic. The main objective of the programs becomes to perform some mathematical operations. Here, the end user should be able to enter the numbers and select the operations they want to perform. So, we must provide two things – buttons as we have in real calculators and a display screen. I am designing a simple math calculator with least features; you can also add more features as you once complete this project.

As the user enter or click on the buttons of the calculator, the clicked number are shown in the display screen and the first number is saved to a variable and user is given to click on the operator button, and again enters the second number. Two different number and an operator becomes enough to perform a mathematical operation. And as the user hits equal to button the answer is shown on the display screen.

Like var1 = 99 operator = ‘+’ and var2 = 66 then result = 231

So our objective in detail becomes:

  • Create user interface.
  • Add mathematical operation like addition, subtraction, division and multiplication.
  • Display result in display screen.
  • Handle frequently occurring errors.

If you are thinking these objectives are quite harder for a beginner, don’t worry, it’s not. Programming in Visual Basic makes it a lot easier. Other than C and C++ languages, Visual Basic consists of many controls and components that can be used simply in your program by just drag-and-drop method. This discourages the writing of tons of code for a simpler program. Thus visual basic brings the high degree of programming in your finger tips.

However, don’t misinterpret visual basic with a code less programming. Visual basic is very powerful programming. You can also complete a small program with just writing codes if you need to. Visual Basic is versatile enough to be useful to a broad range of programmers form beginner to seasoned professional.

Starting Visual Basic 6

The first thing you need to do is open Microsoft Visual Basic 6.0. To open Visual Basic in your computer Click on Start > All Programs > Microsoft Visual Basic 6.0 > Microsoft Visual Basic 6.0

When you start VB, you will be given a simple form showing the type of project you would like to select (refer figure 1.1). For this project you just have to select Standard EXE i.e. when highlighted on Standard EXE click on Open. Then you are taken to Visual Basic Integrated Development Environment (IDE). This is your programming workstation where you design your program (refer figure 1.2).Visual Basic IDE presents the empty looking like window containing dots and a title bar with the word Form1. Notice that the shown window is a form where a program is done. An application can have numbers of forms or only one. The project we are doing on Math Calculator has only one form.

Visual Basic Projects

Figure 1.1 Visual Basic Projects

 

Visual Basic Integrated Development Environment (IDE)

Figure 1.2 Visual Basic Integrated Development Environment (IDE)

 

 

Designing the User Interface

The application interface is straightforward, but it takes quite a bit of effort. You must align a number of buttons on the Form and make the calculator look like a hand-held calculator as much as possible. Designing the user interface in an attractive way makes the user happier to use the program time and again. So, not only now but whenever you design a program try making the user interface attractive that suits the purpose where the program is used.

For our example of Math Calculator the user interface includes the set of buttons and a display screen. Now starting to build the first example open a New Project form File menu, name its main Form as MathCalc and the project as Calculator. Now follow these steps:

  • On the property of main Form change Font to your desired Font in our example I have chosen 10 Points Verdana font, this font will be used in every component you use in Form. Or you can leave it to default Font type.
  • To give the calculator’s display add a Label on the Form and resize it at the top of the form. Set its BorderStyle to 1-Fixed Single so that it will have a 3-D look. Change its Name to Display from the Property Window.
  • Its turn to add buttons, select Command button form the toolbar and drag it to the Form. Change its Name to Digits, Caption to ‘0’ and its Index to ‘0’. Resize it to a square button which suits, as you are using the copy of same button throughout the Form by creating the array of buttons.
  • Place the button with Caption and Index ‘0’ to its final position on the Form.

Creating the array of the button may sound strange, but here’s why we do it. We could create 11 buttons and give them different names such as Digit0, Digit1, Digit2 and so on. But then we have to write separate sub routine for Click event of each Command buttons. By creating the array of Command buttons we can write a single sub routine for Click event of all Command buttons.

  • Right-click the button and choose copy from the shortcut menu. Command button is now copied to the Clipboard, and now we can paste it on the Form which is much faster than designing an identical button.
  • Right-click somewhere on the Form and choose paste from the shortcut menu to create the copy of the button which was copied to the clipboard. Visual Basic displays a dialog box with the following message:

You already have a control name ‘Digits’. Do you want to create a control array?

You want to create an array of Command Buttons, so Click on Yes.

  • While creating the array of the command buttons, visual basic gives the same name to all the command buttons in the array and increases the index of the button by one. So our job is to change the Caption of the Command buttons same as their indices.
  • Repeat step 5, 6 and 7 eight more times and change and don’t forget to align them in accordance to the value of their indices.
  • When the buttons of all the numeric digits are all on the Form, place two more buttons, one for the C (Clear) operation and one for Period (.) button. Name them ClearBttn and DotBttn and set their Caption accordingly. Use a larger font size for the Period button to make its Caption easier to read.
  • When all the buttons of first group are on the Form, align them with equal spacing in row and columns (vertical and horizontal spacing) from the Format menu.
  • So, it’s time to place Command buttons for the operations button.

List of their Caption, Operation and Name is shown in table.

Caption

Name

Operation

+

Plus

Addition

-

Minus

Subtraction

*

Times

Multiplication

/

Div

Division

1/x

Over

Value over

+-

PlusMinus

Change Sign

=

Equal

Equals

  • Use the commands on Format menu to align these buttons as shown in figure. The last button you choose to align in the Form is the reference for the change.

 

Form Designed for Calculator

Figure 1.3 Form layout designed for Math Calculator

 

Programming the Math Calculator

So, now after the design of user interface, it’s time to do some internal programming with math application. To program the numeric Command buttons Double-click one of the digit button. And you’ll see the following in the code window.

 

Private Sub Digits_Click(Index As Integer) End Sub

This is the Click event handler for all Command buttons that represents numeric digits. All numeric buttons are given with same name and they are differentiated by their indices. When any of these buttons is clicked by user, Visual Basic generates Digit_Click event and uses the Index argument to report the index of the button that was clicked.

What happens on a hand-held calculator when you press numeric button?

Obviously, the corresponding digit is displayed to the screen of the calculator. Therefore, in our application, same behavior is to be preformed. To emulate this behavior, the following line of the code is written in the Click event of the Digits.

 Display.Caption = Display.Caption + Digits(Index).Caption 

Therefore, this line of code appends the digit clicked to the Calculator’s Display. The need of using concatenation operator is because when user enters a series of number, for example, when user enters 3 and then enters 0, then the display shows 30 and if again user enters 1, the display shows 301.

Writing the single line of code will not make the Math Calculator effective. By writing only the above code will append the then pressed button with the previously captioned numbers in the display of the calculator after one operation is preformed and the result is still on the screen,  this is not how the real hand-held calculator works. Therefore, we need to write code to clear display after one operation is preformed and next number is to be entered for new operation. For that, revise the Digit_Click event handler as follows:

 

Private Sub Digits_Click(Index As Integer)
 If ClearDisplay Then 
Display.Caption = "" 
ClearDisplay = False
 End If 
Display.Caption = Display.Caption + Digits(Index).Caption 
End Sub


The ClearDisplay variable is declared as Boolean in the Declaration part of General and it can take a True or False value. Suppose the user has performed an operation and result is still on the Display label, without if clause the program would continue to append digits to the number already on the display. This is not the way calculator works. In our application ClearDisplay variable will know when to clear the display.

The ClearDisplay variable is set to true when the display contains the result of the operation and value of ClearDisplay is changed in the Event handler of Equal button after an operation. Therefore, in Digits_Click() subroutine if the value of the ClearDisplay is True then it clears the display and again sets the ClearDisplay to False.

Now when user makes mistake and wants to undo an entry. The clear ‘C’ will erase the display. To attach code to C double-click the C button and enter the following code in Click event:

 Private Sub ClearBttn_Click()
 Display.Caption= “ ” 
End Sub

Even a simple calculator should be able to handle fractional numbers. The Period is used to handle fraction numbers, other than digits periods need to appear only once in a numeric value. Once a period is entered, this button mustn’t insert another one. Code for Period button can be written as:

 Private Sub DotBttn_Click()
 If InStr(Display.Caption, ".") Then 
Exit Sub 
Else Display.Caption = Display.Caption + "." 
End If
 End Sub 

Math Operations for Calculator

Let’s take an example, a user enters a first number in the display and hits ‘+’ button, and he enters next number. It means the first number should be stored in a variable ‘+’ button which was operand should be defined and second number again should be entered.

So, let’s start by defining three variables:

  • Operand1 The first number in operation
    • Operator The desired operation
      • Operand2 The second number in operation

      So, our program should store Operand1, read the value of Operand2 and perform the operation indicated by Operator.

      Variable should be defined outside the subroutines in the code window.  To declare the variables outside the subroutine, start at the Declaration part of General (choose them from drop down in the code window) and enter the following declarations:

      Dim Operand1 As Double, Operand2 As Double
      Dim Operator As String Dim ClearDisplay As Boolean
      
      The Click Event Handlers for the Operator Buttons

       

    • For Division Button

       Private Sub Div_Click()
       Operand1 = Val(Display.Caption)
       Operator = "/" Display.Caption = ""
       End Sub 
    • For Minus Button

      Private Sub Minus_Click()
       Operand1 = Val(Display.Caption)
       Operator = "-"
       Display.Caption = ""
       End Sub 

       

    • For Addition Button

      Private Sub Plus_Click()
       Operand1 = Val(Display.Caption)
       Operator = "+"
       Display.Caption = ""
       End Sub 

       

    • For Multiplication Button

      Private Sub Times_Click()
       Operand1 = Val(Display.Caption)
       Operator = "*"
       Display.Caption = ""
       End Sub

      To this extend, when Operator button is clicked, the program stores the value on the display in Opreand1 variable and the operator in the Operator variable. And then clears the display so that user can enter next second number. After second number is entered, user can click the Equals button to calculate the result. Write the following code for Equals button:

       Private Sub Equal_Click()
       Dim result As Double
       Operand2 = Val(Display.Caption)
       If Operator = "+" Then
       result = Operand1 + Operand2
       If Operator = "-" Then
       result = Operand1 - Operand2
       If Operator = "*" Then
       result = Operand1 * Operand2
       If Operator = "/" And Operand2 <> "0" Then
       result = Operand1 / Operand2
       Display.Caption = result
       End Sub

       

    • For +- button enter:
      Private Sub PlusMinus_Click()
      Display.Caption = -Val(Display.Caption)
      End Sub
    • For 1/x button enter:
       Private Sub Over_Click()
       If Val(Display.Caption) <> 0 Then
       Display.Caption = 1 / Val(Display.Caption)
       End Sub 

Now run the application and check it out. It works just like a hand held calculator. So, this is how you have completed you first project in Visual Basic. See more on Event Driven Programming

More Chapters/ Tutorials on Visual Basic 6

Chapter 1 – Introduction to Visual Programming

This Chapter includes more detailed tutorial on Visual Basic and walkthrough

Chapter 3 – Building Your First Project in Visual Basic – Math Calculator

This chapter includes a full tutorial on “Building Math Calculator as First Visual Basic Project”

Chapter 4 – The Visual Basic Development Environment

You’ll know more about the Development Environment of Microsoft Visual Basic IDE.

Chapter 5 – Some fundamental Visual Interface Components

Learn more about fundamental visual interface components and more gui components used in Visual Basic Development Environment.

Chapter 6 – Working with Visual Basic Controls

Working with Visual Basic Controls guides different ways of using various Controls interfaces like textbox, combobox and many more with their various event handler.

Building Your First Project in Visual Basic – Math Calculator was originally posted on April 9, 2012 and Update on November 28, 2014.

 

Leave a Reply to Event Driven Programming And Event Procedure – Visual Basic | The Computer Students Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>