You are on page 1of 38

Unit 2

Control Statements
and Functions

Lesson 2.4
Random Numbers
and Built-In
Functions

Objectives:
At the end of the lesson, you should
be able to:
1. describe

the utility of some of


VBs built-in functions:

2. evaluate

expressions that use


these functions; and

3. generate

random numbers.

The generation of random


numbers is too important to be
left to chance. R. Coveyou
-

One of the assets of VB is its ability


to generate random numbers.
Randomness is important in
computer gaming as you may have
experienced. There is nothing
worse than a predictable game AI.
Of course, randomness needs to be
controlled.

A Guessing Game
Let us construct a game wherein
the user tries to guess a number
held by the computer. To help the
user, the computer should prompt
the user to make a lower or a
higher guess if his/her guess is
incorrect. We shall need a form
with a text box named txtGuess
and a command button named
cmdOk, whose code will look
something like this:

Dim Guess As Integer


Dim Remark As String
Const Number As Integer = 39
Private Sub cmdOk_Click()
Remark = 39
Guess = Val(txtGuess.Text)
If Guess > Number Then
Remark = LOWER

ElseIf Guess < Number Then


Remark = HIGHER
Else
Remark = RIGHT
End If
MsgBox Remark, 64, Simon Says
End Sub

continuation

A Guessing Game
You have probably noticed
something else-the MsgBox
statement. The MsgBox
statement produces a pop-up
message box that prompts the
user to click on a command
button (in the message box)
before he/she can continue.

Anatomy of a Message Box


MsgBox message, style, title
The message is that which appears
in the message box (e.g., Your
computer is infected), the title is
what appears in the title bar of the
message box, and style determines
what command button appears and
the icon that appears with the
message. The options are as
follows:

continuation

Anatomy of a Message Box


For the buttons
NAME
VA
D
LU
CONS
E
TANT
vbOk
0
Only

BUTT
ONS
DISPL
AYED
Ok
button
Ok
and
vbOk
Cance
Canc
l
el
button
s

continuation

Anatomy of a Message Box


For the icon
Val
ue
16
32
48

64

Name
d
Icon
s
Const
ant
vbCrit
ical
vbQu
estion
vbExc
lamati
on
vbInf

continuation

Anatomy of a Message Box


For example, you want Yes and
No buttons to appear together
with the critical icon, let style be
the sum of the values (4 + 16) or
20. You may also use the named
constants like so: vbYesNo +
vbCritical.

continuation

Anatomy of a Message Box


Note that you can include in your
code actions that depend on the
command button clicked in the
message box, but that is up to you to
explore.

continuation

Anatomy of a Message Box


Try this on your computer:

Construct the guessing game program


weve just discussed. Verify if it works.

Generating a Random Number


You may have noticed two things went
wrong with our program. One is that as
user can only play this game once (no
sense trying to guess the same number)
and you as the programmer cant play it
at all. (You know the number to be
guessed.) We should find a way to let the
computer pick a number for us a
random number an integer to be more
precise.

continuation

Generating a Random Number


Fortunately, VB has something that can
help a pseudo variable called Rnd. Rnd is
a variable in the sense that it represents
a value, but unlike a real variable, that
value changes each time you refer to it.

continuation

Generating a Random Number


Try this on your computer:

Construct a form with a text box


named txtOutput and a command
button called cmdGenerate. To the
command button, assign the
following code.
Sub cmdGenerate_Click( )
txtOutput.Text = Rnd
End Sub

continuation

Generating a Random Number


Running the program several times, youll
notice that Rnd generates a random number
between 0 and 1. For the guessing game
program, however, we need larger numbers.
Note that Rnd in essence generates
fractions. So if we multiply it by a whole
number, we get parts of that whole number.
For example:
Sub cmdGenerate_Click()
txtOutput.Text = Rnd*10
End Sub

continuation

Generating a Random Number


We can now generate numbers between 0 and
10 but what we really need for the guessing
game program are whole numbers. In comes a
built-in function called Fix. Fix drops the
decimal portion of a number such that
Fix(2.75) = Fix(2.23) = 2.Employing Fix, we
get the following:
Sub cmdGenerate_Click()
txtOutput.Text = Fix(Rnd*10)
End Sub

continuation

Generating a Random Number


Note that we can now generate random
integers from 0 to 9. What if we want
numbers from 1 to 10? The solution is
simple.
Sub cmdGenerate_Click()
txtOutput.Text = Fix(Rnd*10) + 1
End Sub

continuation

Generating a Random Number


Note that, in general, Fix (Rnd*N)
generates random numbers from 0 to (N1) and that Fix (Rnd*N) + 1 generates
numbers from 1 to N.
Before we apply Rnd in the guessing
game program, try running the program
weve just made and generate four
numbers. Stop the program and start it
again. Again, generate four numbers.
What did you notice?

continuation

Generating a Random Number


Unfortunately, it seems that our program
generates the same set of random
numbers. The reason is something called
a random number seed or random seed.
Imagine our computer standing at the
edge of a pool of random numbers. If the
computer were to stand in the same
spot, it would be getting the same set of
numbers. The random seed dictates
where around the pool the computer
should stand.

continuation

Generating a Random Number


The problem is that we need that
random seed to be different every time
we run the program. So, what changes
every time we run the program? Time!

continuation

Generating a Random Number


We need to get the random seed from
the internal clock of the computer. The
statement for that is as follows:
Sub cmdGenerate_Click( )
Randomize Timer
txtOutput.Text = Fix(Rnd*10) + 1
End Sub

An Improved Guessing Game


We are now ready to make the guessing
game program more fun. Suppose we
want the number to be guessed to be
from 1 to 100. Of course this requires
the expression Fix (Rnd*100) + 1. The
problem now is where should we put
this?

continuation

An Improved Guessing Game


Placing it within the cmdOk_click()
subroutine would not be wise. We would
end up generating a new random number
every time we click the command
button. It would take a miracle to make
a correct guess. The generation of the
random number should take place when
the program starts or when the Form
loads. The proper place is, therefore, in
the following subroutine.

continuation

An Improved Guessing Game


Private Sub Form _()
Randomize Timer
Number = Fix(Rnd*100)+1
End Sub
There are two ways to create this. One is
to type simply the code outside the
cmdOk_Click() subroutine. The other
(and easier) way is simply way to double
click the form while in editing mode.

continuation

An Improved Guessing Game


Try this on your computer:

Modify the guessing game program


based on our discussions. Verify if it
works.

Other Built-in Functions


So far weve been introduced to two
of VBs built in functions. These
are Val and Fix. Recall that Val
(String) converts the string in
question into a numeric value and
value and Fix (Number) drops the
decimals of the number in question.
There are more.

Other Built-in Functions


Fun
ctio
n
Ab
s
(N)

Int
(N)

Description

Gets the
absolute
value of N
Ex. Abs(3) =
Abs(-3) = 3
Rounds down
N to the
nearest
integer <=N.
Ex. Int(1.2) =
Int(1) =
Int(1.7) = 1
Int(-1.6) = Int(1.1) = Int(-2) =

continuation

continuation

Other Built-in Functions


Remember that these functions can
be used in conjunction with
arithmetic operators. For example,
consider the quadratic formula that
follows:

continuation

Other Built-in Functions


Of course, we do not have an
operator like so in code we need
two lines:
x1 = (-b + sqr (b^2 4*a*c))/(2*a)
x2 = (-b + sqr (b^2 4*a*c))/(2*a)

continuation

Other Built-in Functions


These are called numeric functions
because they result in numeric
values. VB also offers us several
functions that result in string
values.

Some Built-in String Functions


Fu
nct
ion
LC
as
e
(St
rin
g)

Description

Converts the
strings
characters to
lowercase.
Ex.
LCase(Bob)
= bob
LCase(BOB)
= bob

Lcase(bob)
= bob
UC Converts the

Some Built-in String Functions


Lcase and Ucase are particularly
useful in programs requiring text
input. For example, consider the
Branches of Government program in
Lesson 2.2.

continuation

Some Built-in String Functions


Private Sub cmdOk_Click( )
Branch = txtBranch.Text
Select Case Branch
Case presidential
Ofc = Office of the President
Case judicial
Ofc = Supreme Court
Case legislative
Ofc = Senate and Congress
End Select
txtOfc.Text = Ofc
End Sub

continuation

Some Built-in String Functions


Notice that if you enter JUDICIAL or
Judicial, it will fail to display Supreme
Court. The program is case-sensitive!
To make it case-insensitive, process
the users input to match the option.
In this case Lcase is the key.

continuation

Some Built-in String Functions


Private Sub cmdOk_Click( )
Branch = Lcase (txtBranch.Text)
Select Case Branch
Case presidential
Ofc = Office of the President
Case judicial
Ofc = Supreme Court
Case legislative
Ofc = Senate and Congress
End Select
txtOfc.Text = Ofc
End Sub

continuation

You might also like