Professional Documents
Culture Documents
QBASIC Notes: Algorithms & Psuedocode CLS, Rem, Locate, Print, End
QBASIC Notes: Algorithms & Psuedocode CLS, Rem, Locate, Print, End
11
14
6 18
20
6 LET X = 11
LET Booty = 6
LET X = Booty
LET Booty = X * 3
LET Booty = Booty + 2
LET X = Booty - X
Arithmetic Operators
• Follows PEMDAS
– Parenthesis ( ), 6 * (Score1 – 10)
– Exponents ^ 8^2 = 82
– Multiplication *
– Division / or \ or MOD (later)
– Addition +
– Subtraction -
Putting it Together
PRINT “What year were you born?” PROMPT
INPUT birth User types number
PRINT “If you’ve already had your birthday this year, you're”;
PRINT age1; Prints age1 number
PRINT “ years old. Otherwise, you’re only “;
PRINT age2; Prints age2 number Prints string
Literals
END
(inside quotes)
Why Constants Are Used
Method 1 – With Constants Method 2 - Without
LET Tax.Rate = 0.06
Division, Constants
Division – 3 Types
• Decimal Division – Uses /
– Result will yield decimal number if there is a
remainder.
• Example: 11 / 4 = 2.75
• Integer Division = Uses \
– Result will yield only the integer portion.
• Example: 11 \ 4 = 2 (4 goes into 11 two times)
– Remainder is lost
GOSUB…
END
Starter
• Write a program that asks the user for two
numbers and shows an addition problem
that shows the numbers and their sum:
• Sample:
User is prompted and enters 6 and 3
6+3=9
Your Quiz - Psuedocode
• START the program
• Get information about class sizes
• Calculate statistics about classes
• Show information on the screen
• END the program
QBASIC Notes
URN
ons
GOSUB Print.Output
RET
ti
Calcula
RETURN
Title Print.Output
U B
RETUR
S
GOSUB N
GO
Directions
User.Input
Directions Calculations
GOSUB RETURN
User.Input
Start END
GOSUB Title RETURN
Main
URN
ons
GOSUB Print.Output
RET
ti
Calcula
RETURN
Title Print.Output
U B
RETUR
S
GOSUB N
GO
Directions
User.Input
Directions Calculations
GOSUB
RETUR
N
Forgot Return!
User.Input
Starter
• Write a short program that asks the user
which row and column they would like to
print in. Then, the program clears the
screen and prints something at that spot.
QBASIC Notes
LET counter = 0
DO
LET counter = counter + 1
PRINT counter
LOOP UNTIL counter > 9
END
QBASIC Notes
LOOPS
Analyze the following program
CLS
DO
PRINT “Enter your grade (9-12)”
INPUT grade
LOOP UNTIL (grade > 9 AND grade < 12)
DO
CODE here
LOOP UNTIL (condition)
CONDITIONS
• Conditions typically COMPARE two values
to see if they are (>, <, =, <=, >=, <>) each
other
– Ex: x = 5, x > 11, j < m, hours <= 60
• The result of a condition will either be true
or false
• Two complete conditions can be joined with
AND or OR
Compound Condition
• When you want two conditions to be
considered, it is compound.
• Example…a number must be between 0 and 50
– Number must be more than 0
– Number must be less than 50
• Compound condition
Number > 0 AND Number < 50
Wrong: Number > 0 and < 50
Data VALIDATION
DO
PRINT “Enter a number less than 10”
INPUT number
LOOP UNTIL (number < 10)
DO UNTIL i = 11
LET i = i + 1
PRINT i
LOOP
END
QBASIC Notes
DO UNTIL i = 11
LET i = i + 1
PRINT i
LOOP
DO
LET loops = loops + 1
PRINT “Would you like to loop again”
INPUT answer$
LOOP UNTIL answer$ = “n” or answer$ = “no”
Conditions
Starter
• Write a program that asks the
user to enter their grade and
ensures that they enter a valid
number (12 or less)
• After the user enters their grade.
The program uses a loop to show
which grades they have passed.
CONDITIONS
• Used to control LOOP and IF structures
– DO WHILE (x > 0)
• Keeps looping as long as x>0.
• Simple Condition – only one truth value
• Either true or false
– Other common conditions
• DO UNTIL (value <= 0)
• DO WHILE (answer$ = “yes”)
• IF (x <> 0)
Conditions
• Used to determine whether to execute or not.
• Should always evaluate to true (1) or false (0)
– Examples:
• ( J = 20)
• ( J > 5)
• Conditions should contain at least one variable
that may change the truth value of the condition.
– Without variables, conditions are always true or
always false. These are useless conditions.
• Consider….LOOP UNTIL (5 = 11)
Simple Conditions
• Simple conditions have only one condition
that evaluates to true or false using
comparison operators:
= equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
<> less than or greater than (not equal to)
Compound Conditions
• Used when you need to evaluate more than
one condition.
• Using a compound condition means
joining more than one condition with:
– AND
• LOOP UNTIL (x = 0 AND y > 5)
– OR
• DO WHILE (x = 0 OR y > 5)
AND and OR
• AND - All conditions must be true in
order for compound condition to be true
– IF ( k < 6 AND j < 5)
• OR - Only one condition must be true in
order for compound condition to be true
– LOOP UNTIL (K < 5 OR answer$ = “N”)
AND / OR
• When joining conditions, a complete
condition must be present on both sides
of the AND/OR
– Wrong: IF (j < 10 AND > 5)
• complete condition on left, but not right
• QB doesn’t know that you refer to j on the right
side.
– Correct: IF (j < 10 AND j > 5)
• complete conditions on both sides
Faulty Compound Conditions
• ALL CONDITIONS MUST BE
COMPLETE CONDITIONS
– Will Work
• ELSEIF (answer$ = “Yes” OR answer$ = “yes”)
– Will NOT Work
• ELSEIF (value = 5 OR 6)
– Incomplete condition on right side of OR
– Change to: (value = 5 OR value = 6)
• End Notes
Faulty Conditions
• Find the mistake:
– ( J = J)
– (J > 0 AND J < 0)
– ( 2 < 5)
– ( K > 5 AND K < 10 )
– (Y < 10 OR Y > 9)
Verifying User entries
PRINT “Guess a number between 1 and 10”
INPUT guess
Random Numbers
Random Numbers
• Random numbers are used in games to
generate artificial intelligence and random
events.
• Example: LET x = RND
– RND command generates random number
between 0 (inclusive) and 1 (non-inclusive)
and value is stored in variable x.
Some Possible Random
Numbers
RND
0
.11
.2501
.685
.99999
More On Random Numbers
• Random numbers are generated through a long
series of math operations on a starting number
known as the SEED.
• Unless the seed is changed, the seed (first
number) is 0 and random numbers will always be
the same
• SEED is changed with RANDOMIZE
– Example: Randomize 5
• Changes Random SEED to 5. You’ll get a different set of
random numbers (but still between 0 and 1).
Random Numbers
• The computer clock can be used as a seed
– Clock accessed through TIMER
– RANDOMIZE TIMER
• Uses clock to produce truly random numbers
• Use RANDOMIZE TIMER once (and only
once) with all programs using random #s
Manipulating Ranges
• LET x = RND : Gives x a value between 0 and 1
• Method: Multiply by the number of different
numbers you want:
– LET x = RND * 23
– Would yield numbers between 0 and 23
• Method: Truncate decimals with the INT
function.
– LET x = INT(RND * 23)
Some Possible Random
Numbers
RND RND * 23 INT (RND * 23)
0 0 0
.11 2.53 2
.2501 5.7523 5
.685 15.755 15
.99999 22.99977 22
Manipulating Ranges
• Method: Add the lowest number you want
to see:
– LET x = INT(RND * 23) + 10
• Would give 23 different possible numbers, the
lowest being 10.
• Possibilities: 10, 11, 12...etc...32
Some Possible Random
Numbers
RND RND * 23 INT(RND * 23) INT(RND * 23) +
10
0 0 0 10
.11 2.53 2 12
.2501 5.7523 5 15
.685 15.755 15 25
.99999 22.99977 22 32
Random Number: General Form
LET x = INT(RND * r) + s
PRINT x
END
QBASIC Notes
INPUT$(1)
INPUTing 1 Character
IF (choice = 1) THEN
….do something
ELSEIF (choice = 2) THEN
….do something else
Entering Words
• Suggestion: Do NOT allow the user to enter
WORDS when their answer affects program
flow:
– Most common example: YES / NO
• Instead– use menu (1 = YES, 2 = NO)
• Reason – programmer cannot predict what
user will enter (YES, Yes, yes, y, Y, yep,
sure dude…etc)
Problems with IF…so far
1. If your program does it regardless, it
doesn’t belong in the IF
FAULTY METHOD
IF (level = 1) THEN
RANDOMIZE TIMER
LET n1 = INT(RND * 10) + 1
LET n2 = INT(RND * 10) + 1
ELSEIF (level = 2) THEN
RANDOMIZE TIMER
LET n1 = INT(RND * 100) + 1
LET n2 = INT(RND * 100) + 1
ENDIF
IF (level = 2) THEN
LET n1 = INT(RND * 100) + 1
LET n2 = INT(RND * 100) + 1
ENDIF
IF (operation = 1) THEN
correct.answer = n1 + n2
ELSEIF (operation = 2) THEN
correct.answer = n1 – n2
ENDIF
Two separate things happen, related to the same condition.
BETTER METHOD
IF (operation = 1) THEN
sign$ = “+”
correct.answer = n1 + n2
ELSEIF (operation = 2) THEN
sign$ = “-”
correct.answer = n1 – n2
ENDIF
QBASIC Notes
Read / Data
Storing Data in Variables
• So far, you have TWO methods of
storing data in variables:
1. Use a LET command:
LET answer = x + y
Good for constants and calculations
2. Use the INPUT command:
PRINT “Enter your answer”;
INPUT answer
Good for user interaction
Third Method – READ/DATA
• The READ statement attempts to fill a
variable, just like the INPUT statement
does.
– INPUT draws data from the keyboard
– READ draws data from a DATA statement
(at the end of the program)
Read / Data Statements
• Examples:
– READ wage
– READ name$, age, height
• DATA statement must exist at the end of
program to fill read
Sample
Using INPUT Using READ/DATA
PRINT “enter n1” READ n1
INPUT n1 READ n2
PRINT “enter n2”
INPUT n2 LET n3 = n1 + n2
LET n3 = n1 + n2 PRINT “The sum is “; n3
PRINT “The sum is “;
n3 DATA 3, 5
RESTORE
• When using READ, variables are filled with
DATA in order…
– READ x, y, z
– DATA 11, 13
– DATA 55, 17, 23
• x = 11, y = 13, z = 55. Next READ statement
would use the value 17.
• The RESTORE statement begins READING the
first element again.
RESTORE EXAMPLE
W = 11 Y = 33
READ w, x, y X = 22
RESTORE
READ z
Z = 11
Alternate Output
Opening Files, Closing Files,
OUTPUT
Input / Process / Output Model
INPUT
information flows Process
into program
1 = INPUT (from
keyboard)
OUTPUT
2 = READ (from
information flows
within program)
out of program
3=?
1 = PRINT (to
monitor)
2=?
Alternate Output
• Thus far, all output goes to the monitor using the
PRINT command
• Output is stored in RAM
– CPU releases RAM after program ends or when power is
lost
– Very temporary
• cannot print output
• cannot save output
• Good programs need output that can be saved and / or
printed.
• Solution is to send output to data files
What are data files?
• Data files store information in a file that
can be retrieved later by another program.
• The file extension determines which
program the CPU tries to retrieve with
– Example: MS Word files = .doc or .docx
• The file “blah.doc” contains information
that will be retrieved using MS Word
Creating Data files - OPEN
• A program can create a data file to store
information.
• OPEN “filename/path” for OUTPUT as #n
n is a number
Opens this data Information will that will serve
file for use (or OVERWRITE any as a
creates it if it existing “nickname”
doesn’t exist yet) information as during within
output the program
Sending Information to a Data
file
• PRINT sends information to the monitor
• PRINT #n sends information to file #n
where n is the file number
– Example:
• PRINT #6, “Hello”
• Prints the word Hello in file #6
Filenames / Paths
• When opening a file, you must know the
filename and path:
• OPEN “H:/projects/datafiles/blah.txt”
for…
Reference letter
folder inside of
for network
folder
drive
actual file
Folder inside
name and
of drive
extension
Common Extensions
Extension Program
.DOC or .DOCX MS Word
.XLS or .XLSX MS Excel
.PPT or .PPTX MS Powerpoint
.TXT Text – Notepad
.HTM or .HTML Web Page – Internet
Explorer
Closing Files
• After you’ve opened a file, you can print to
the file.
Retrieving Data
• Open notepad
• Type your first name
• Save file as name (a text file) on H: drive
Same d ata
to
File b ack T
d ata TPU
d
Sen as OU
Data file holds file
(new?) data to use
next time
Creating a Data File
• Data files can be created in two ways:
– Programmer can create the data file
• Use Notepad, save file as filename.ext
– EXT = Extension
– Programs can create the data file
• Data files for OUTPUT
• Data files for APPEND
Opening a Data file for INPUT
• Before you can use data stored in a file,
you must first tell your program to open
the file. General form:
– OPEN “H:filename.ext” for INPUT as #1
• INPUT is a mode to retrieve information
Getting Data from the file
• After file is opened, you can retrieve data
from the file using INPUT #n statement:
– INPUT #1, name$
• Would look into data file #1 pull the first piece of
information, and store it in the variable name$
• Data file #1 is should have a name stored in it.
• Close data file after information is
retrieved
Programs Adjusting Data Files
• Many times, the program will adjust the data file.
• For instance, you may want to change the name
stored in the data file.
– Open the data file
– Get the name
– Close the data file Sub 1
– Find out the new name (user input)
– Open the data file for output Sub 2
– Write the new data to the file
– Close the data file
Sub 3
Putting it all together
OPEN “H:namedata.txt” for INPUT as #1
INPUT #1, name$
CLOSE #1
Arrays
Starter
• Assume you run a lemonade stand and you want to keep
track of how many glasses of lemonade you sell for 5 days in
a row.
• Write a program that allows you to enter sales for each day.
Then, the program creates a report (on screen) that repeats
sales each day and adds total sales for the time frame.
print day1
print day2…etc
print total
An Adaptable Solution
open a data file
do
enter a number, store it in data file
loop 5x
close data file
re-open same file
do
pull number from data file, add it, print it
loop 5x
print total
Problem with Lemonaide
Program
• In this program, you had to create 5
variables for 5 days. What if there were 30
days?
• That’s 30 variables – ugh!
• This problem is often solved using
ARRAYS.
What is an array?
• An array is a data storage structure.
– Like a variable, it stores information.
• Variables hold one value, arrays can hold
many – it has compartments.
Storage Need
• Assume you want to store the NAME of
each student in this class. With variables,
you would need about 25 variables. You
would probably name them with a
numbering system
. . . etc
student1$ student2$ student3$ student4$
Using Arrays
• With an array, you could create one array
that has 25 storage units.
Arrays – One Variable Name
with a stack of storage spots
1
2
3
4
5
6
7
8, 9, 10…etc
Declaring An Array
• You must first declare that an array will
exist.
– DIM <array name – with $ for text> (size)
– DIM sales(5)
• Creates an Array of 5 spots for storing sales figures
– DIM student$(20)
• Creates an Array named student$ with 20 storage
spots for string variables.
Numeric Array for Sales
1
2
3
4
5
Filling an Array
• To fill storage spots in an array, you must
use the array name and the spot (index).
Example:
– LET sales(1) = 12
– LET sales(2) = 8
– LET sales(3) = 30
– LET sales(4) = 15
– LET sales(5) = 19
Sales Array after Filling
1 12
2 8
3 30
4 15
5 19
FOR/NEXT LOOPS
General Form
FOR (i = start TO finish) STEP difference
code to execute
NEXT i
LET c = 0
DO
LET c = c + 1
PRINT somearray(c)
LOOP UNTIL c = 5
Filling an Array the Quick Way
FOR i = 1 to 20 STEP 1
Print “Type the students name #” ; i
INPUT student$(i)
NEXT i
<run>
Parallel Arrays
Parallel Arrays
• Definition: Two or more different arrays where the data is related
between each array.
• Relationship exists because data has same INDEX in different Array.
Assume 3 Arrays are Declared:
DIM first$(4)
DIM last$(4)
DIM age(4)
• Let I = 0
• Print “How many times would you like to
loop?”
• Input loops
• DO
– LET I = I + 1
– Print “Looping in the “ I “ loop.”
• LOOP WHILE ( I < loops )
Accumulators
• Accumulators – Update a value each time
something is done.
• Example: Every time a person moves in
moving program, it adds one to a variable
– LET Moves = Moves + 1
Counters vs. Running Totals
• Counters: Update a • Running Totals:
value by one each Update a value by a
time: variable each time:
– LET C = C + 1 – LET A = A + V
Sample Running Total
DO
PRINT “Enter a number.”
INPUT number
LET total = total + number
LOOP UNTIL ...
PRINT USING
PRINT USING
• Statement used to adjust format of output.
• GENERAL FORM:
– PRINT USING “The value is $###.##”; var
– Would print variable (var) according to format inside
of quotes.
• Example: LET money = 98.0672
• PRINT USING “Your cash is $###.##”; money
Press Any Key to Continue
• Sometimes, you want your screen to pause
until the user hits a key.
Code
PRINT “Press Any Key to Continue”
LET dummy$ = input$(1)
Print Using
• Prints Using can be used to format output
of numeric variables.
• In the past
– LET cash = 5 / 2
– PRINT cash ‘would show 2.5
• Alternative
– PRINT USING “##.##”; cash
• Would print cash value with 2 decimals
QBASIC Notes – Ch4
• Example
– Print Name$ ; SPC(4) ; Age
TAB Command
• Used inside the PRINT statement to move
the cursor to a specific column
– PRINT TAB(40); “Hello”
• Moves output to column 40 and prints string literal
• Can be used with variable value instead of
constant
– PRINT TAB(x) ;k
• Moves output to column x and prints value of k
QBASIC Notes
It is currently 10:00pm