Programming for Computing 07 - 08

Chapter: if - decisions

Module Admin   Contents, Index   Schedule  
1: Intro to VB    2: First Program and Projects    3: Variables, assignment, Strings    4: Type Conversion, InputBox, Constants    5:Built-in Functions    6: If - decisions    7: Loops - while, for    Example - find smallest    8: Scopes: local, global    9: Writing Procedures.Parameters, Functions   
10: Objects    11: Design    12: Testing    13: Graphics    14: Controls and events    15: Listboxes    16: Arrays    17: Files    18: The Command Line   

Appendices(links etc)   Additional Lectures    Tutorials (not in printed notes)     Selected solutions (not in printed notes)     Assignments    Additions and Errata   

new

The  schedule page has info on what we will do each week.

Why do we do this...

The IF instruction exists many times in any program - you can't write software without it.

 


Section 6.0

Introduction

We use the IF statement to make a choice/selection.

Problem: input a mark - classify it as pass (40 or above ) or fail. Solution:

Private Sub Button1_Click(etc... )
dim mark as integer
mark = CInt(inputBox("Enter your mark"))

If mark >= 40 Then
    MessageBox.Show("pass")
Else
    MessageBox.Show("fail")
End If
MessageBox.Show("done")
End Sub
Look at the 'if' template:
If some condition  Then
    done when true
Else
    done when false
End If
We 'indent' parts of this by (e.g.) 4 spaces. (VB will do this for you. It will aslo give you an End If automatically.)

The If, Else endif MUST be vertically aligned (VB will do this)

The parts that we indent are the parts between if...Else, and Else...End If

VB does the code layout for you. BUT if you are using another system or language that does not do it for you, it is worth the trouble to do it by hand. We do this to make the code readable. It is worth spending a short time on code layout to prevent 2 hours of debugging later.

Now the detail.  


Section 6.1

Conditions

Here are the VB comparison operators:
	=		equal to
	<>		not equal to

	>		greater than
	<		less than

	<=		less than or equal to
	>=		greater than or equal to
They are called 'relational operators'.

We can also combine several conditions using logical operators:

		And
		Or
		Not
Brackets (...) may also be used to group conditions.

Let's look at some conditions in isolation, prior to using them in 'if' statements.

	dim n as integer, m as integer' declare for examples 
	dim x as integer, y as single

	m = 1
	n = 2
	x = 3.67
	y = 0.0
We can now use these variables in conditions, e.g:
	 n < 3             'is true
	 m = 1            'is true
	 x >= 4.0          'is false

	(n < 3) And  (m = 1)       'is true
	(n < 3) Or (m = 1)         'is true
	(n < 3) And (x >= 4.0)      'is false
	(n < 3) Or (x >= 4.0)       'is true
	Not(m = 1)                'is false
These examples illustrate that and-or-not work like boolean operators in maths i.e.
  • when we 'or' a series of expressions together, we only need one to be true to make the whole expression true
  • when we 'and' a series of expressions together, each one must be true to make the whole expression true.
    You get your driving license if you pass the theory AND the practical. or:
    license is true if theory is true AND practical is true.

    What if we used OR in the above?

 


Section 6.2

IF in detail

'classify a mark as pass or fail
Private Sub Button1_Click(etc...)
dim mark as integer
mark = CInt(inputBox("Enter your mark"))

If mark >= 40 Then
    MessageBox.Show("pass" )               ' true block
Else
    MessageBox.Show("fail" )                'false block
End If
MessageBox.Show("done" )                   'done in every case
End Sub
Here is the IF as a picture
[if1.jpg]
pic of an if endif

Points:

  • When the condition is true (e.g. mark is 45) the 'true block' is done.
  • When the condition is false, (e.g mark is 23) the 'false block' is done.
  • Whichever block is done, the paths join at the endif, and the program continues downwards. Thus, the 'done' message happens for every mark.
  • With an if/Else, either the true block or the false block is done. The can never BOTH be done. They cannot both be skipped. ONE of them gets done!!!!!
  • 'Else' means 'otherwise'
  • Take care with conditions - what if we put mark>40, or put mark >39 ?
  • The true/false blocks are indented, and can contain a number of statements, as in
    If c=3 Then
        MessageBox.Show("hello")
        y=5
        n=7
    Else
        ... etc
    
  • We talk about the 'flow of control' moving as a program executes. This is the path that the yellow marker takes as you use the F8 key to step through.
 


Section 6.3

If ... Else If ... Else - multiple choice.

The if/Else only had two outcomes. Often we need more..

Problem: classify a mark. As above, but 70 or above gets a distinction.

Private Sub Button1_Click(etc...)
dim mark as integer
mark = CInt(inputBox("Enter your mark"))

If mark >= 70 Then
    MessageBox.Show("distinction")
Else If mark >= 40 Then
    MessageBox.Show("pass")
Else
    MessageBox.Show("fail")
End If

MessageBox.Show("done")
End Sub
The general form is
If ? Then               ' ? means   any condition
    code
Else If ? Then
    code
Else If ? Then 
    code
Else If ? Then
    code
Else
    code
End If
We can have as many Else-If's as we need. The final Else is optional, but useful in most cases.

Again, only one of the choices is done. And one of them must be done. The final Else block catches any cases that do not match an if.

Look at this code:

If mark >= 70 Then
    MessageBox.Show("distinction")
Else If mark >= 40 Then
    MessageBox.Show("pass")
Else
    MessageBox.Show("fail")
End If
Imagine the mark is 88. The order of the conditions is crucial. The tests are performed top to bottom. If we re-wrote it as:
If mark >= 40 Then
    MessageBox.Show("pass")
Else If mark >= 70 Then
    MessageBox.Show("distinction")
Else
    MessageBox.Show("fail")
End If
then the 88 is above 40, and 'pass' is displayed - wrong!

We will look at some variations on this problem. Here is another solution, using 'and'

'better - order of IF's does not matter
If (mark >= 70) And (mark<=100) Then
    MessageBox.Show("distinction")
Else If (mark >= 40) And (mark<=69)  Then
    MessageBox.Show("pass")
Else If (mark>=0) And (mark<=39) Then
    MessageBox.Show("fail")
End If
Here, we could put the if's in any order. We don't need an else, as we specify each condition exactly.

What if we wanted to detect impossible marks, such as -33, or 231 ? We can use else as a 'catch-all', as in:

'and with else
If (mark >= 70) And (mark<=100) Then
    MessageBox.Show("distinction")
Else If (mark >= 40) And (mark<=69)  Then
    MessageBox.Show("pass")
Else If (mark>=0) And (mark<=39) Then
    MessageBox.Show("fail")
Else
    MessageBox.Show("Impossible mark")
End If
Which is best depends on the particular program - but if the data being tested in an IF could possibly be incorrect(e.g. unvalidated), an else is worthwhile.  


Section 6.4

The If - End If: Omitting 'else' ?

Sometimes, we only have one option - or, to re-phrase, we have two options, but the second one requires no special action. Example:
'process a car insurance query
age = CInt(inputBox("Enter your age"))
If age>=65 Then
    MessageBox.Show("Look on our Website for low car insurance")
End If

name = CInt(inputBox("Enter your name"))    ' done in every case
When age is < 65, no special action is needed.  


Section 6.5

Using Else

For beginners, it is tempting to regard 'else' as an optional extra. Consider a program which inputs a number, rejecting it if negative or processing it in some way if positive. We could code it as:
n = CInt( inputBox ("age"))
If n<0 Then
    MessageBox.Show("Error! ")
end if

' now process it  
If n>=0 Then
    '... process it, e.g
    x = n+1

End if
It is clearer to put:
n = CInt(inputBox("age"))
If (n<0)
    MessageBox.Show("Error!")
Else
    x = n+1
End if
Look at the marks code without Else:
mark= CInt(inputBox("mark is "))
If mark >= 70 Then
    MessageBox.Show("distinction")
End If
If mark >= 40 Then
    MessageBox.Show("pass")
End If
If mark<40 Then
    MessageBox.Show("fail")
End If
Is is wrong. What is displayed when mark is: 77? 44? 22? If you can't tell, run the code with F8.  


Section 6.6

If Problems

Using message and input boxes:

1. Write a program which reads in a 'double' number and displays the square of it. (IF is not needed yet)

2. As Q1, but add an IF: a warning message should be displayed if the number is less than 0, and the number should NOT be squared in this case.

3. Write a program to read in the dimensions of a rectangle and display its area. An error message should be shown and the area should not be calculated if any dimension is negative.

4. Write a program to read in two integers via input boxes, and to show them in 2 message boxes, the smallest first.

5. Read in 3 numbers, display the largest in a message box.

6. Extend the marking example (pass, fail, distinction) to add another category: merit (60 to 69). Test your program with a range of data.

7. Area of shapes. Write a program which inputs a string (either "square", "triangle" or "rectangle" - anything else is wrong). Depending on the shape, ask the user to enter the dimensions you need to be able to calculate the area. Display the area.

8. Input 4 numbers representing the x/y coordinates of the top left and bottom right of a rectangle. Determine if a given point is within the rectangle. (BTW this is how a computer finds out which widow your mouse is in when you click it)

 


Section 6.7

Nested if

The problem of male/female retirement. Assume males retire at 65, females at 60. We need to determine if a person should be retired:
'un-nested
age = CInt(inputBox("age is:"))
gender = inputBox("m or f")
If (age>=65) and (gender="m") Then
    code
Else If (age>=60) and (gender="f") Then
    code
Else
    code.. not retired
End If
Another way is to 'nest' an if inside an if, as in:
'nested
If gender = "m" Then
    If age >=65 Then
        code - male , retired
    End If
Else                ' must be f
    If age > 60 Then
        code - f, retired
    End If
End If
Note the indenting, and that each if needs a matching endif.

Which approach is a style thing. Often, the nested solution is harder to read.

Some languages (Java, C++) do not have an elseIF, which can complicate coding.  


Section 6.8

Boolean Type

Sometimes, our variable might only need two states - e.g. married or not, empty or not, correct or not. We could use an integer, treating e.g. 1 as true, 0 as false, but an integer is too 'wide'. Consider:
    Dim married as integer
    married = 1
    ... some code...
    If married = 11 Then
     ....
The 11 came from a sticky key! Note that VB could not spot the error, because 0, 1, 11 ... are all integers.

Is in most languages, there is a true/false data type, called boolean (named after George Boole, who invented an arithmetic of logic). We can declare variables of this type, then can only assign true or false to them, as in:

    dim married as boolean, retired  as boolean

    married = true
    retired = false
    married = 456      ' should not compile
    ... code...
    If married Then
     etc
Note that we don't need to say:
  If married = true Then...
The shorter form is considered better style.

Motto : if your variable only has two states, make it boolean!

Key Points

Don't avoid 'Else' and 'Else If' - you need them sometimes.

Remember to put the 'Then' on the same line as the 'if'

Module Admin   Contents, Index