LESSON 9 Visual Basic Accumulators & Counters

advertisement
LESSON 9
Visual Basic
Accumulators & Counters
Accumulators
An Accumulator is a variable used for the purpose of storing the accumulated grand total of a group of
numbers.
Think of a number
What is the total of all numbers (TALLY) so far?
First
Second
Third
Number
5
7
20
Tally
5
12
32
Open a new Visual Basic Project. Change the name property of the form to frmNumbers. Use your
thinking skills to complete the following practice:
1.
Write a simple program that will accept an integer between 1 and 100 from the user. Provide an
INPUT BOX to collect the data.
Algorithm:
Step 1. Declare a variable to hold the value of the number input by the user
Step 2. Get input from the user
Syntax:
Dim Num as Integer
Num = InputBox "Enter A Number Between 1 and 100: "
2.
Now add a counted loop to allow the collection of ten integers.
3.
Add a line of code that will ACCUMULATE the grand total of all ten integers. (Should this line of
code be written inside or outside of the loop?)
4.
Add a line of code that will calculate the average of the 10 numbers. (Should this line of code be
written inside or outside of the loop?)
5.
Output results. (Should this line of code be written inside or outside of the loop?)
Algorithm:
6.
Step 1. Declare variables to hold the value of the number input by the user, and
the result of the Sum calculation
Step 2. Get input from the user
Step 3. Add the value of the number input to the current value of the Sum
variable, using the Sum variable to store the result
Step 4. Output resulting Accumulated Total (the Sum variable)
Save this project as Numbers and leave it open for the next practice exercise.
Counters
A Counter is a variable that is used to hold the number of times an event has occurred. For example, we
know that we could write a Conditional Loop to continue events until a specified condition becomes true.
E.g.
Dim Password As String
Do Until Password = "abracadabra"
'convert input to lowercase letters then store in variable Password
Password = Lcase(InputBox "Please Enter Password:")
Loop
Perhaps we should COUNT the number of attempts the user makes at entering the correct password, in
order to set a limit on guesses. This is a good security procedure. Let's limit our user to four guesses.
DPCDSB
Computer Science TIK2O1
Page - 1 -
LESSON 9
E.g.
Visual Basic
Accumulators & Counters
Dim Password As String, Attempts As Integer
Do Until Password = "abracadabra" or Attempts = 4
'convert input to lowercase letters then store in variable Password
Password = Lcase(InputBox "Please Enter Password:")
'Add one to the counter
Attempts = Attempts + 1
Loop
Create a program to enter a variety of student marks. The program is to determine the letter grade
(A’s, B’s, C’s, D’s, and F’s) and keep a running total for the Marks.
Create the form, as seen below (to the right), and label each empty label box to the right of each letter
using the corresponding letter. Such as: lblCountA, lblCountB, etc.
Double Click on the Enter Marks button and enter the following text:
‘Declare Counters
Dim CountA, CountB, CountC as integer
Dim CountD, CountF As Integer
Dim Mark as Integer
' Initizial the counters to zero
CountA = 0
CountB = 0
CountC = 0
CountD = 0
CountF = 0
'Input Marks for a class size of 21
For i = 1 To 21
'enter Marks and count each letter grade
txtMark = InputBox("Enter Mark Percentage", i)
Mark = Val(txtMark)
If Mark >= 80 Then
CountA = CountA + 1
ElseIf Mark >= 70 Then
CountB = CountB + 1
ElseIf Mark >= 60 Then
CountC = CountC + 1
ElseIf Mark >= 50 Then
CountD = CountD + 1
Else
CountF = CountF + 1
End If
Next I
'Display the tallies for each letter grade
lblCountA = CountA
lblCountB = CountB
lblCountC = CountC
lblCountD = CountD
lblCountF = CountF
DPCDSB
Computer Science TIK2O1
Page - 2 -
LESSON 9
Visual Basic
Accumulators & Counters
The use of graphic images will add interest to your Visual Basic programs. All pictures and images are
composed of simpler elements called graphics. Graphics are shapes like dots, lines, and circles. In this
lesson, we'll explore the fundamental graphic shapes.
When plotting graphics on the form (or other object), we must specify where we want the graphic to be
drawn. Recall that Visual Basic objects (forms and other objects) are measured in twips.
How many twips is your Visual Basic screen?
upper left corner of form is coordinate (0,0)
upper left corner of active object will be displayed here
size of this form
(x=12000 twips & y=9000 twips)
Visual Basic offers many methods (commands) that will automatically produce a graphic once you give
certain specifications like size, position, and even colour of the graphic. Let's look at just a few of these
methods:
METHOD
SYNTAX
Pset
Pset (x, y), (color)
Line
Line (x1, y1) - (x2, y2)
Line
Line (x1, y1) - (x2, y2), B
Circle
Circle (x, y), radius
DESCRIPTION
Displays a single pixel (dot). (Color specification is
optional.)
Draws a line on a form or other object. Also used to draw
rectangles. Lines are plotted from x,y starting position to
x,y ending position, which determines length.
Draws a square BOX on a form or other object.
Boxes are plotted from top left corner to bottom right
corner.
Draws a circle on a form or other object. Also used to
draw ellipses, arcs and sectors. Circles are plotted from
its centre and size is determined by radius specified.
Refer to the following table when you need an integer to specify Colour of any graphic (for example, when
generating random colours):
TABLE OF QBCOLOR VALUES
0
1
2
3
4
5
6
7
DPCDSB
Black
Blue
Green
Cyan
Red
Magenta
Yellow
White
8
9
10
11
12
13
14
15
Grey
Light Blue
Light Green
Light Cyan
Light Red
Light Magenta
Light Yellow
Bright White
Computer Science TIK2O1
Page - 3 -
LESSON 9
Visual Basic
Accumulators & Counters
Syntax: QBColor(6)
You can also refer to any of these colours as vbBlack, vbRed, etc.
1.
Your entire screen is made of tiny dots called pixels. Let’s display just one of those dots at
position x = 500, y = 500 twips.
Add these lines of code to a command button in your current project:
'change background colour of form to black
Form1.BackColor = 0
'display the pixel at the given position in colour bright white
PSet (500, 500), QBColor(1)
2.
Let's make this pixel program a little more interesting. Add a counted loop to repeat the following
steps 500 times (loop should start after changing background color of the form):
Step 1. Generate a random number for the x coordinate
(check your form for maximum number of twips)
Step 2. Generate a random number for the y coordinate
(check your form for maximum number of twips)
Step 3. Generate a random number for the color of the pixel (between 1 and 15)
Step 4. Display a pixel at random coordinates with random color
Create a command button which will randomly set 100 pixels with 15 random colours
Private Sub RandomPixels_Click()
Dim x, y, colours As Integer
For i = 1 To 100
Randomize
x = Int(Rnd * 1000)
y = Int(Rnd * 1000)
colours = Int(Rnd * 15)
PSet (x, y), QBColor(colours)
Next i
End Sub
3.
Increase the number of pixels displayed to 5000.
4.
Increase the area to fill the entire screen.
DPCDSB
Computer Science TIK2O1
Page - 4 -
LESSON 9
Visual Basic
Accumulators & Counters
Create a Random Number Guessing Game:
‘Declare Vars in General
Dim X, Answer As Integer
Display Start button &
Get a random integer
between 1 and 100
Private Sub cmdStart_Click()
cmdStart.Visible = False
TxtGuess.Visible = True
X = Int(Rnd * 100) + 1
End Sub
Stop game when the
ESC key is pressed
Check when Enter key is
pressed
Check for the correct
guess
Check for the higher
HINT
Check for the lower
HINT
Show answer
DPCDSB
Private Sub cmdStart_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyEscape Then
End
End If
End Sub
Private Sub TxtGuess_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyEscape Then
End
End If
If KeyCode = vbKeyReturn Then
Answer = (TxtGuess)
If Answer = X Then
lblAnswer = "Correct"
TxtGuess = ""
cmdStart.Visible = True
TxtGuess.Visible = False
ElseIf Answer < X Then
lblAnswer = "Higher"
TxtGuess = ""
ElseIf Answer > X Then
lblAnswer = "Lower"
TxtGuess = ""
End If
ElseIf KeyCode = vbKeyS Then
lblAnswer = X
End If
End Sub
Computer Science TIK2O1
Page - 5 -
LESSON 9
Visual Basic
Accumulators & Counters
Assignment
1. Create a program which will allow the user enter ten numbers. The program is to count how many
numbers were above 50. Hint: You will need to incorporate a Selection (If…then) statement.
2. Draw diagonal line from top left corner to bottom right corner of the screen and another diagonal line
from bottom left corner to top right corner of the screen, forming a large "X".
3. Draw a red circle in the approximate centre of the screen.
‘HINT
FillColor = vbRed
FillStyle = 0
'plot circle of size 1000 twips radius
Circle (4800, 3500), 1000, vbRed
4. Move a graphic shape across the screen from left to right.
5. Make the graphic shape bounce back and forth across the screen three times.
6. Bounce a graphic character around the screen in a bow tie formation.
7. Create a computer version of the dice game, “Rounders.” Create a computer game of chance. An
introductory screen will appear, offering the player options to read rules of the game, play the game,
or exit the game.

If the player clicks a button to read the rules, a new form is displayed explaining the game. The
player may then choose to either play the game or exit.

If the player clicks a button to play the game, the game board form is displayed where the player can
choose to play, read the rules, or exit. Add two pictures of Die and display the roll of the Die as a
graphical component. Six different images are to be made in the C++ program using the Icon creator

Here's how to play the game of "Rounders: " When the player clicks the PLAY button, a random
number is generated by the computer, simulating the roll of two dice. This dice roll will result in one of
the following combinations: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12. There are 11 rounds in the game, one for
each combination. The object of the first round is to roll a 2. If the player does this, 2 points will be
awarded. No points are won or lost if the desired number was not rolled. The object of round 2 is to
roll a 3 for 3 points; 4 in round 3; 5 in round 4, etc. until the player gets to round 11, the final round,
where the object is to roll a 12. The game ends after the 11th round, when the final score will be
displayed."
8. Research the rules of the dice game Yahtzee. Allow the user to Roll the Dice and then choose which
Die they would like to roll again for the best possible score.
DPCDSB
Computer Science TIK2O1
Page - 6 -
LESSON 9
Visual Basic
Accumulators & Counters
Program Rubric
Criteria
Level 1
Knowledge/Understanding
Uses graphics
- demonstrates
commands
limited ability to
SP3.08I
use graphics
commands
Thinking/Inquiry
Uses graphics with
program constructs
correctly
SPV.04I
SP3.06I, SP3.07I
Communication
Completes internal
documentation and
follows defined
standards
SPV.03I
SP3.09I
Validates program
results
SPV.03I, SP3.11I
Follows descriptive
naming conventions
SP3.03I
Application
Can apply skills to
challenge tasks
SPV.04I
SP3.08I
Level 2
Level 3
Level 4
- demonstrates
some ability to
use graphics
commands
- demonstrates
considerable
ability to use
graphics
commands
- demonstrates
strong ability to
use graphics
commands; adds
enhancements
beyond
requirements
- demonstrates
limited ability to
use repetition and
selection in
conjunction with
graphics
- demonstrates
some ability to use
repetition and
selection in
conjunction with
graphics
- demonstrates
considerable
ability to use
repetition and
selection in
conjunction with
graphics
- demonstrates
strong ability to
use repetition
and selection in
conjunction with
graphics
- limited use of
documentation and
following of local
standards
- some use of
documentation and
following of local
standards
- most program
components are
documented to
local standards
- all program
components
documented to
local standards
- program
produces few
correct results
- program
produces some
correct results
- most run
situations provide
correct results
- rarely uses
descriptive naming
conventions
- some variable
names are not
descriptive
- one or two
variables names
are not descriptive
- all test runs of
the program
produce correct
results
- always uses
descriptive
variable names
- able to master
one or two of the
challenges
- able to master
three of the
challenges
- able to master
four or five of the
challenges
- able to master
all items in the
graphics
challenge and
adds further
enhancements
Note: A student whose achievement is below level 1 (50%) has not met the expectations for this
assignment or activity.
DPCDSB
Computer Science TIK2O1
Page - 7 -
Download