Software Development

  Lecture Notes

Programming Constructs

Introduction

Programming Constructs

Selection Statements

Sequence Statements

Iteration Statements

Examples You May Use in Your Assignment


Introduction

Objectives

This guide will help you to understand: -  

·  the importance of programming constructs

·  how sequence, selection and iteration statements work


Programming Constructs

Programming constructs are basic building blocks that can be used to control computer programs. There are three main programming constructs. They are...

  • Sequence statements
  • Selection statements
  • Iteration statements

These three constructs are extremely important. They can help you control the flow of your program; allowing you to specify how or when parts of your code are executed.


Sequence Statements

A sequence is one of the simplest programming constructs. With a sequence, you have a set of instructions that are executed one after another. For example,

msgbox "This is the first message, it will be displayed first"

msgbox "This is the second message, it will be displayed next "

msgbox "This is the third message, it will be displayed last"

If sequences were the only programming constructs we had, then we would be severely limited in the programs we could produce. For most programs, we need more advanced constructs. For example, it would be useful if we could be selective about which code lines should be executed. It would also be useful if we could repeat certain lines of code.

Well, the more advanced constructs that allow us to do these things are called...

  • selection statements

and

  • Iteration statements

Selection Statements

Selection statements allow us to choose between alternative actions within a program. VB has two distinct selection statements. The IF-Else statement and the Select-Case statement. We shall examine the IF-Else statement. The IF-Else statement allows you to selectively execute parts of your program code, depending on various conditions.

Carry out the activity below to see a simple example:-

~~Activity~~

Activity A

If-Else Example - Ending a Program

Here is an example of an If-Else statement that asks the user if they really want to end the program or not.

  1. Open Visual Basic.
  2. Save the form and project to a new folder called If_Example
  3. Add a command button to your form. Change the button's caption to Exit. Change the button's name to cmdExit. Like my form which is shown below.
  4. Copy the code below into the form's coding window.
  5. Run the program

The code is between the dotted lines below
.....................................................

Private Sub cmdExit_Click()

    Dim Response As Integer

    Response = MsgBox("Exit Program?", vbInformation + vbYesNo, "Title")

    If Response = vbYes Then

        End

    ElseIf Response = vbNo Then

        Me.Refresh

    End If

End Sub

.....................................................

Extension Work:

  1. Change the MsgBox code " Exit Program?" so a different message is displayed to the user.
      
  2. Change the MsgBox title to something better. For example, you could change it from "Title" to "Query Exit "
     
  3. To help you understand the code better, add a breakpoint to the line -- >
     
        Private Sub
    cmdExit_Click()

    Run the program, click the Exit button and and then press F8 to step through the code line by line.


  

Now let's explain the code.

The general syntax of an If-Else statement is:-

If Condition-Is-True Then

Execute the statements here

Else

Execute the statements here instead

End If

Using the example from the first activity; when a message box appears asking the user if they want to end the program, if they click the YES button, then the Response variable is set to a value of vbYes. However, if the user clicks the NO button, then the Response variable is set to the value of vbNo.

The If-Else part of the code checks the value of the Response variable.  

If Response = vbYes Then       'does Response have a value of vbYes

        End   'end the program

ElseIf Response = vbNo Then   'does Response have a value of vbNo

        Me.Refresh   'refresh the form

End If

If the Response variable has a value of vbYes the program ends, but if it has a value of vbNo, the form is refreshed instead.

From this example we can see that selection statements, such as If-Else, allow us to be selective about the lines of code to be executed. We can make sure that only some lines are executed, depending upon the condition we set.

~~Activity~~

Activity B

If-Else Example - Calculator

This example program uses If-Else statements to check which option button is selected, Add, Subtract, Multiply or Divide.

  1. Add the controls shown above to the form you created for Activity A.
  2. Change the names of the controls to:-

    txtFirstNum
    txtFirstNum
    txtAnswer
    optAdd
    optSubtract
    optMultiply
    optDivide
    cmdCalc
    cmdExit

  3. Copy the code given below into the form's coding window.
  4. Run the program

The code is between the dotted lines below
.....................................................

Private Sub cmdCalc_Click()
    Dim firstNum As Double
    Dim secondNum As Double
    Dim answer As Double

    firstNum = txtFirstNum.Text   'get first number from textbox
    secondNum = txtSecondNum.Text   'get second number from textbox

    If optAdd.Value = True Then   'if the Add option button is selected
        answer = firstNum + secondNum
    ElseIf optSubtract.Value = True Then 'if Subtract option button is selected
        answer = firstNum - secondNum
    ElseIf optMultiply.Value = True Then 'if Multiply option button is selected
        answer = firstNum * secondNum
    ElseIf optDivide.Value = True Then   'if Divide option button is selected
        answer = firstNum / secondNum
    Else     'if the user forgot to select an option
        MsgBox "Please choose an option button"
        Exit Sub
    End If

    txtAnswer.Text = answer  'Display the answer in the answer textbox

End Sub

.....................................................

Extension Work:

  1. One problem you will find with the program is that it will crash if the user does not enter any numbers into the two textboxes. Here is some code that helps correct that:-

    Replace the line...

        firstNumber = txtFirstNumber.Text

    with these lines...

    If IsNumeric(txtFirstNum.Text) Then    'if there is a number in the textbox
        firstNum = txtFirstNum.Text       'get the number from the textbox
    Else  'otherwise, inform user to put a number in the textbox, then exit the sub
        MsgBox "Please enter a number into the 'First Number' textbox"
        Exit Sub
    End If

  2. Now that you have been shown how to check that a number has been entered into the first textbox, add code to check that a number has been entered into the second textbox as well.
      
  3. To help you understand the code better, add a breakpoint to the line -- >
     
        Private Sub
    cmdCalc_Click()

    Run the program, click the Calculate button and and then press F8 to step through the code line by line.


 


Iteration Statements

Iteration statements are used to repeat instructions, either a specific number of times, or until a certain condition is reached. Another term used for iteration is looping. VB has a few different iteration statements, such as the Do-While statement and the For-Next statement. We shall examine the For-Next statement.

~~Activity~~

Activity C

For-Next Example - Times Table

This example program uses a For-Next looping statement to display the two times table in a listbox.

  1. Open Visual Basic.
  2. Save the form and project to a new folder called Loop_Example
  3. Add a listbox and a command button to your form as shown above.
  4. Change the names of the controls to:-

    lstTimesTable
    cmdTimesTable

  5. Copy the code given below into the form's coding window.
  6. Run the program

The code is between the dotted lines below
.....................................................

Private Sub cmdTimesTable_Click()

    Dim i As Integer
    Dim lineToDisplay As String
    lstTimesTable.Clear

    For i = 1 To 10
        lineToDisplay = i & " times 2 is " & (i * 2)
        lstTimesTable.AddItem lineToDisplay
    Next

End Sub

.....................................................

Extension Work:

  1. Change the code above to display more than 10 lines of the 2 times table, say 20 lines.
      
  2. Now change the code above to display the 3 times table.
      
  3. To help you understand the code better, add a breakpoint to the line -- >
     
        Private Sub
    cmdTimesTable_Click()

    Run the program, click the cmdTimesTable button and and then press F8 to step through the code line by line.
      
  4. How about adding option buttons so the user can specify the times table they want displayed. Like the form shown below.

  5. To do this, add four option buttons and name them appropriately. for example, optTwo, optThree etc.

    You will need to add If-Else code, similar to the code you used in Activity B. To start you off, find this line ...

        Dim lineToDisplay As String line

    and insert the following code after it

    Add this code after the line -- > Dim lineToDisplay As String
    .....................................................

    Dim multiplier As Integer

    If optTwo.Value = True Then
        multiplier = 2
    End If

    .....................................................

    Now change the line...

            lineToDisplay = i & " times 2 is " & (i * 2)
    to

            lineToDisplay = i & " times " & multiplier & " is " & (i * multiplier)

    This If-Else code only checks to see if the first option button is selected. What if the user selects one of the other option buttons? Add more code to check for this. Look at Activity B again if you don't know how to do it.


Now let's explain the code.

The general syntax of a For-Next statement is:-

For counter = initial value To counter = end value

Execute the statements here

Next

In the first line, you always specify a variable to be used as a counter. You also specify a starting value and an end value for the counter variable.

Now, the loop starts off with this counter variable set to the starting value. The first thing the For-Next loop does is to check to see if the counter variable has reached the end value or not. If it hasn't, it will execute all the statements inside the loop

On reaching the final Next line, the counter is increased in value by 1 and the program returns to the first line again, (the For line).

It checks again to see if the counter variable has reached the end value or not. If it hasn't, it executes the statements inside the loop again and then increases the value of the counter variable.

It will carry on executing the statements inside the loop until the counter variable reaches the end value. Then it will finish with the loop and carry on with the rest of the program.

If we look at the code from Activity C...

For i = 1 To 10
    lineToDisplay = i & " times 2 is " & (i * 2)
    lstTimesTable.AddItem lineToDisplay
Next

The counter variable is called i. It's initial value is 1, and it's end value is 10. This loop will execute 10 times, and each time, the statements inside will execute, displaying 10 lines of the 2 times table.


Examples You May Use in Your Assignment

Here are some coding examples you may use in your assignment to help explain selection and iteration statements. You may keep the code as it is, unless you have ideas of your own, in which case, feel free to make changes.

Selection Example 1

This code asks you for a password. if you enter a correct password it will load the main form, otherwise it ends the program.

.....................................................

Private Sub Form_Load()
    Dim pass As String
    pass = InputBox ("Enter Password Please!")
    If pass = "secret" OR pass = "secret2" Then
        MsgBox " You are clear to enter"
    Else
        MsgBox " Access Denied"
        End
    End If
End Sub

.....................................................

Selection Example 2

This code displays a message in a label. The contents of the message change depending on which day of the week it is.

.....................................................

Private Sub Form_Load()
   If Weekday(Now) = (vbSaturday OR vbSunday) Then
      Label1.Text = "Relax and enjoy your weekend"
   ElseIf Weekday(Now) = vbMonday Then
      Label1.Text = "Get up lazy - It's Monday - Time for work"
   Else
      Label1.Text = "Sadly it's a working day"
   End If
End Sub

.....................................................

Iteration Example

The program shown below sums all the numbers between 1 to 100 and displays each sum in a listbox.

Here is the looping part of the code.

.....................................................

Dim i As Integer
Dim total As Integer
For i = 0 To 100
    total = total + i
    ListBox1.AddItem total
Next

.....................................................

If you do not like any of these examples, then feel free to find some of your own. Just make sure you use simple coding examples, that help you clearly explain the concepts of sequence, selection and iteration statements in your assignment.


Fini
 

 

 

   

  Unit Information

Assessment

Syllabus

Scheme of Work

Notes &Tutorials

Assignments

Quizzes

Books & Things

Links