You are on page 1of 224

QBASIC Notes

Algorithms & Psuedocode


CLS, REM, LOCATE, PRINT, END
Problem Solving
• Goal of programming: To solve a problem
or make a process easier.
• Algorithm – An approach to achieving this
goal (How will you do it?)
• Psuedocode – A step by step algorithm
written in English.
Sample Psuedocode
Finding an Average
• Gather up the data elements to be
averaged.
• Add up all the data.
• Divide by the number of elements added.
PRINT Command
• Used to create output to the monitor
– Can print string literals using quotes
• Print “Hello User!”
– Print commands without a semicolon at the end cause
the outflow cursor to move to the next line.
– Semicolon at the end keeps outflow cursor at current
spot
– PRINT with nothing after creates a blank line.
LOCATE command
• General form: LOCATE row, column
• Function: Moves cursor to the row and
column specified.
• There are 25 rows and 80 columns
– Cannot locate row or column 0 (or less)
– Cannot locate row 26+ or column 81+
• Example: LOCATE 13,40 would move
outflow to appx. middle of screen.
REM Statement
• Short for Remark
– Lines not executed by program
– Use for documentation
– Can Use single quote instead ( ‘ )
• At the start of every program
– REM <Your Name>
– REM QBASIC <Hour>
– REM <Program Description>
END Command
• Causes program to stop interpreting.
• Every program should have an END…
make it your first step.
SLEEP
• General Form: SLEEP X
– Where X is an integer (no decimals)
– Pauses processing for roughly X seconds.
• Example: SLEEP 2
– Pauses processing for about 2 seconds
• Very helpful in debugging
CLS Command
• Clears the output screen.
– General form: CLS
• Usually used at the start of a program.
• Often used in the middle somewhere when
a change in screen is needed.
Variables
• Variables are storage spaces assigned a name (by
you) whose value may change during the
program
• Names cannot be reserved words
– Such as END, PRINT…etc
• Names should have MEANING
• Assign variables a value with the LET command
– LET Score = 98
INPUT Command
• Used to obtain a value or text to fill a
variable from the user
– INPUT Score1
• Should use a prompt
– PRINT “What was your first score?”
– INPUT Score1
LET Command
• Allows CPU to assign a value to a variable
based on other values:
– LET x = 15
– LET score = 10 * x
– LET amout.due = (subtotal * tax) + subtotal
– LET whatever = x + y * z
Starter – Enter and Run
CLS
PRINT “Enter your first number”
INPUT num1
PRINT “Enter your second number”
INPUT num2
LET total = num1 + num2
PRINT “The sum is “;
PRINT total
END
QBASIC Notes

Starter, Variables, Arithmetic


Operators
LET, INPUT
Figure out the value on the right side of the = sign first

The value on the right side


X Booty is stored in the variable on
the left side

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

LET age1 = 2011 – birth Calculates age1 and


LET age2 = 2010 – birth Age2 using birth

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

LET subtotal = some math LET subtotal = some math

LET tax = subtotal * Tax.Rate LET tax = subtotal * .06

LET total = subtotal + tax LET total = subtotal + tax

PRINT total PRINT total


QBASIC Notes

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

• Modulus Division – Use MOD


– Result will yield only remainder portion
• Example: 11 MOD 4 = 3 (11 / 4 = 2 REMAINDER 3)
– Integer portion is lost
Quiz 1 Tomorrow
• Follows input/process/output model
• The processing (math) will be easily
understood mathematics
• Don’t forget to have an END
• Use meaningful variable names
• Use “white” space to separate your
program into logical parts
Constants
• Constants do not change throughout the
program
• Often numbers….5, 26.2354, 3.14
• Constants can have names if you declare
them with a let statement
– Ex. LET PI = 3.1459
– Ex. LET BurgerPrice = 1.49
Declaring Constants
• When you have a value that you will need
to use during the program, but it will not
change, declare a constant.
• Declare constants at the TOP of the MAIN
program, below REM’s, but above other
code.
– Sample Next Slide
Sample of Declaring Constants
REM Matt Offenbecker
REM QBASIC 3rd Block
REM Fake Program

LET TaxRate = .06 ‘Will not change as program runs

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

Subroutines, GOSUB, RETURN


Top Down Programming
• When given a program – decide on the
“tasks” involved
• Tasks should be small and focused
• Tasking is the TOP
• After tasks are identified and program is
divided, you will program specific tasks
• The Tasks themselves are the BOTTOM
Subroutines
• Subroutines are like mini-programs that
are programmed after the main program
• Subroutines usually only have one task
– Example: Calculating a GPA
– Example: Greeting the user
• Subroutines start with their name (label)
– NameOfSub: (colon needed after label)
• Subroutines end with RETURN
Sample Subroutine
Intro:‘(Label to start)

PRINT “Hello User”


PRINT “Welcome to this program”;
PRINT “I hope you enjoy it.”

RETURN ‘(End of Sub)


Sample Subroutine
Calculate.GPA: ‘Label to start

LET points = 4.0 + 3.3 + 2.7 + 4.0 + 1.7


LET gpa = points / 5

RETURN ‘End of Sub


Top Down Steps
1. Analyze program to identify steps
2. High level programming with stubs
3. Test / Debug
4. Low level program step 1
– Debug
5. Low level program step 2
– Debug
6. Etc…..
Gosub / Return
• Gosubs call a subroutine and execute that
subroutine
• General Form: GOSUB SubName

• Returns send interpreter back to main


program immediately after the Gosub
• General Form: RETURN
GOSUB and RETURN
• GOSUB is used to call (or use) a
subroutine
GOSUB labelname

• From previous examples


GOSUB SlopeFinder
GOSUB Intro
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 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

String Variables and Functions


LEFT$, RIGHT$, MID$, LEN
String Variables - Text
• String variables are used to store text.
• Represented with a $ after variable name
– VarName$ = “Dog”
– Input Address$
Operations / Functions
Numeric Variables
• Lots of operators available for numeric
variables:
– +, -, *, /, \, MOD, INT, ^
• There are also operators and functions
available for string variables.
String Functions
• Left$ (VarName$, n)
– Returns leftmost n letters of VarName$
– LET this$ = Left$ (Last$, 5)
– this$ would be “OFFEN”
• Len (VarName$)
– Returns length of VarName$
– LET this = LEN (“goat”)
• this would be 4
– LET this = LEN (Last$)
• this would be 11 (for offenbecker)
String Functions
• Mid$(VarName$, S, N)
– Returns n letters of VarName$, starting at letter #s
– LET this$ = Mid$(Last$, 3, 4)
– this$ would be “FENB”
• Right$ (VarName$, N)
– Returns rightmost n letters of VarName$
– LET this$ = Right$(Last$, 5)
– this$ would be “ECKER”
String Expressions
• Concatenating Strings (Piecing together)
– First$ + Last$ appends last to first
• Ex. First$ = “Matt”, Last$ = “Offenbecker”
• LET Name$ = First$ + Last$
• Name$ becomes “MattOffenbecker”
• Name$ = first$ + “ “ + last$
• Name$ becomes “Matt Offenbecker”
Type Mismatches
• Type Mismatch Error – Occurs when you
try to do something to a string variable that
should only be done with numbers or vice
versa
– Example: Let x = name$ + 3
• Trying to add a number to a string
– Example: Let k$ = LEN(name$)
• LEN function returns a number
• Numbers need to be stored in numeric variables
Enter this code, please
CLS

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)

PRINT “Thank You”


END
Looping
• Looping creates code
that is done
repetitively in a
program
• Start a loop with the
DO statement
• End a loop with the
LOOP statement
Looping Example
Finding the Area of a Rectangle
DO ‘start of loop
GOSUB Find.Measurements
GOSUB Calc.Area
GOSUB Show.Results
LOOP ‘end of loop
– Program would loop infinitely and find areas of
rectangles.
– Loops are STRUCTURES – Code inside of structures
should be indented.
• Helps you to see start and end of structure
Controlling Loops
• UNTIL statement- executes looping statement
as long as a condition is false.
• Can be used with the “DO” or the “LOOP”

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)

The code inside the loop keeps repeating


until the variable is less than 10.
Enter this Program
CLS
LET i = 0

DO UNTIL i = 11
LET i = i + 1
PRINT i
LOOP

END
QBASIC Notes

LOOPS for Counting and other uses


Using DO/LOOP for counting
LET i = 0

DO UNTIL i = 11
LET i = i + 1
PRINT i
LOOP

Value of i starts at 0, adds one to itself each loop and


doesn’t loop when value becomes 11
Looping on User Answers
DO
PRINT “Hello”
PRINT “Would you like me to say Hello again”
INPUT redo$
LOOP UNTIL redo$ = “n” OR redo$ = “N” OR….
Combining
LET loops = 0

DO
LET loops = loops + 1
PRINT “Would you like to loop again”
INPUT answer$
LOOP UNTIL answer$ = “n” or answer$ = “no”

PRINT “That was fun…we looped “ loops “times”


Looping Example
• DO
PRINT “Enter the password”;
INPUT pass$
LET tries = tries + 1
• LOOP UNTIL pass$ = “secret” or tries = 3
Looping Example
• DO WHILE (condition)
– GOSUB Find.Measurements
– GOSUB Calc.Area
– GOSUB Show.Results
• LOOP
– Loops as long as condition is true, but might
not ever loop.
QBASIC Notes

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

DO WHILE (guess < 1 OR guess > 10)


PRINT “Must guess between 1 and 10!”
INPUT guess
LOOP
Enter this code
CLS
RANDOMIZE TIMER
PRINT TIMER
LET X=RND
PRINT X
END
QBASIC Notes

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

x becomes a random number where

r = range – how many different possible


numbers x could be
s = starting –the lowest number you
would like to start your range of x’s at
Starter
• Write a program that makes the user enter
a secret word. (The secret word is
warrior).
• The user is made to keep entering words
until the secret word is entered.
• After the user enters the secret word, the
program moves on and tells them how
many attempts it took to enter the word.
Starter
• Write a program that rolls dice (6 sides) –
one for you and one for the computer
• The program should report the values of
your rolls and tell who wins
– You win if your roll is more
– The computer wins if your roll is less
– Tie when both rolls are the same
Starter
CLS
RANDOMIZE TIMER

LET x = INT(RND * 10) + 1

PRINT x
END
QBASIC Notes

Decision Making In Programs


IF, ELSEIF, ELSE
Decision Making in Programs
• Higher level programs are able to make
decisions about what to do based on
information.
• Example:
– Users chooses to move left or right – program
must adjust to this decision
• Decisions can be made with the IF
structure using conditions.
Using a basic IF
IF (condition) THEN
code to execute when condition is
true. Could be many lines of code
or just one
END IF
Notice – Conditional
Code (inside IF) is
indented
Sample
IF (grade >= 9 AND grade <=12) THEN
PRINT “High School”
ENDIF

IF (grade <=8 AND grade >=6) THEN


PRINT “Middle School
ENDIF

IF grade < 6 THEN


PRINT “Elementary School”
ENDIF
IF Structure - General Form
IF (condition1) THEN
Code to be executed when condition is true
More code to be executed
Notice…this code is INDENTED
ELSEIF (condition2) THEN
Code executed if condition1 isn’t true
ELSEIF (condition3) THEN….
Code….you can have many elseif’s
ELSE NO CONDITON NEEDED
Code…
ENDIF
The IF Structure
• IF (condition) THEN statement
– Opens the IF structure. Tests condition(s) for truth and
executes code if condition(s) = true.
• ELSEIF (condition2)
– CAN be used with IF statement. Conditions tested only
when IF condition(s) = false
– You can use many ELSEIF’s
• ELSE (no condition needed)
– CAN be used in structure. ELSE code executes
whenever IF & ELSEIF conditions have not been met.
• ENDIF
– Closes IF structure
Using IF to set a variable
IF age <= 10 THEN
cost.of.movie = 5.00
ELSEIF age > 10 AND age <=17 THEN
cost.of.movie = 7.50
ELSEIF age >=70 THEN
cost.of.movie = 7.50
ELSE
cost.of.move = 10.00
ENDIF

PRINT “Your movie will cost “; cost.of.movie


QBASIC Notes

INPUT$(1)
INPUTing 1 Character

Old Method New Method


PRINT “Enter your PRINT “Enter your
middle initial” middle initial”
INPUT m.i$ LET m.i$ = INPUT$(1)

PRINT “You entered”; PRINT “You entered”;


PRINT m.i$ PRINT m.i$
One character responses
• Typical code:
– PRINT “Enter your choice (U, D, L, R)”
– INPUT choice$
• User must type a letter and then hit ENTER
afterwards.
• New code:
– LET choice$ = INPUT$(1)
• User enters 1 character, stored in choice$
• Does not have to hit ENTER
Using INPUT$(1)
• You CAN use it with numeric menus BUT
– The entry is not NUMERIC, it is TEXT (string)
PRINT “Enter your choice:” PRINT “Enter your choice:”
PRINT “1 = Quit” PRINT “1 = Quit”
PRINT “2 = Don’t Quit” PRINT “2 = Don’t Quit”
INPUT choice LET choice$ = INPUT$(1)

IF (choice = 1) THEN IF (choice$ = “1”) THEN


GOSUB quitter GOSUB quitter
ELSEIF…etc ELSEIF…etc
Stopping Process
• Often, user needs time to read something.
• Current method = SLEEP n
• New method – make the user type
something when done reading:
– PRINT “Press ENTER when complete”
– INPUT blah
Instead of SLEEPing
• Put it at the bottom of the screen:
LOCATE 24, 1
PRINT “Hit ENTER when complete”;
INPUT blah
• Allow them to hit anything
PRINT “Press any key”
LET blah$ = INPUT$(1)
The PRESS ANY KEY method
LOCATE 24, 1
PRINT “Press any key to continue”
LET blah$ = INPUT$(1)
Menus
• Most programs have menus, whether
numeric or graphical.
– Numerical: Pick an options (1, 2, 3…)
– Graphical: Go to FILE and choose EDIT
Comparing Menus
Numeric Menus (QB) GUI Menus (Visual Languages)

Pick a FILE choice:


1 = NEW
2 = OPEN
3 = SAVE
4 = SAVE AS
5 = EDIT
Sample Menu Code
PRINT “Enter your choice:”
PRINT “1 = SAVE”
PRINT “2 = SAVE AS”
INPUT choice

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

The program uses RANDOMIZE TIMER no matter what…It


doesn’t belong in the IF structure
BETTER METHOD
RANDOMIZE TIMER
IF (level = 1) THEN
LET n1 = INT(RND * 10) + 1
LET n2 = INT(RND * 10) + 1
ELSEIF (level = 2) THEN
LET n1 = INT(RND * 100) + 1
LET n2 = INT(RND * 100) + 1
ENDIF
Problems with IF…so far
2. Using MULTIPLE IF statements instead
of ELSE IF
FAULTY METHOD
IF (level = 1) THEN
LET n1 = INT(RND * 10) + 1
LET n2 = INT(RND * 10) + 1
ENDIF

IF (level = 2) THEN
LET n1 = INT(RND * 100) + 1
LET n2 = INT(RND * 100) + 1
ENDIF

The program does 2 separate IF comparisons…it doesn’t need to.


BETTER METHOD
IF (level = 1) THEN
LET n1 = INT(RND * 10) + 1
LET n2 = INT(RND * 10) + 1
ELSEIF (level = 2) THEN
LET n1 = INT(RND * 100) + 1
LET n2 = INT(RND * 100) + 1
ENDIF
Problems with IF…so far
3. Use one IF structure instead of many with
more than one issue relates to the IF.
FAULTY METHOD
IF (operation = 1) THEN
sign$ = “+”
ELSEIF (operation = 2) THEN
sign$ = “-”
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

DATA 11, 22,


DATA 33, 44, 55
Hangman Results
Game # # Votes %Vote
4 42 46.2%
5 17 18.7%
7 13 14.3%
2 12 13.2%
6 4 4.4%
3 3 3.3%
Total 91 100%
STARTER
CLS
INPUT “Your first name:” first$
INPUT “Your last name:” last$
PRINT “Thanks…Check your H: drive.”

OPEN “H:userlog.txt” FOR OUTPUT AS #1


PRINT #1, first$ “ “ last$ “ used the program”;
PRINT #1, “on “ DATE$ “ at “ TIME$
CLOSE #1
END
Using Data Files

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.

• After you’ve finished using the file, you


should CLOSE it.
– CLOSE #n
– This command closes file #n.
The PRINT #1 STATEMENT
• You can PRINT to a data file instead of the
monitor. For example:
– OPEN “H:/mydata.txt” FOR OUTPUT AS #1
– PRINT #1, name$
– CLOSE #1
• Assuming the name$ is “Billy” this
program would send the word “Billy” to
the file mydata.txt on the H: drive
Common Drive References:
• A: = Floppy Disk
• B: = Floppy Disk 2 (rarely used)
• C: = Hard Drive on computer
• D: = CD or DVD Drive
• E: = Flash Drive / Portable
• F: and beyond = More portables or network
drives
• H: Network drive at school
Appending
• When you print to a data file for OUTPUT,
it OVERWRITES any existing data.
• This can be useful, but you often want to
keep existing data and ADD to it.
• This is known as appending (adding data
to the end).
How To Append
• To Append, you must open a data file for
append instead of output.

OPEN “H:/mydata.txt” FOR APPEND AS #1


PRINT #1, new information
CLOSE #1
Use
UseAPPEND
APPENDinstead
instead
of
ofOUTPUT
OUTPUT
Starter
• Write a program that has a “log on” screen
that asks the user their first name, last
name, and the time (first subroutine)
• After entry, the program should create a
text file (.txt) on the H: drive that prints the
following message:
– <First> <Last> logged on at <time>
(second subroutine)
About the Starter
• This program is an example of a program that
uses a log.
• Most programs/websites/networks that require
log in create logs to track user traffic.
• Logs are an important part of network and
program security.
• Logs are essentially just output data files that
grow through time.
– Our log doesn’t grow – it replaces itself – boo!
Using Data Files

APPENDING data files


Using Data Files

Retrieving Data
• Open notepad
• Type your first name
• Save file as name (a text file) on H: drive

Type this program


CLS
OPEN “H:name.txt” FOR INPUT AS #1
INPUT #1, name$
CLOSE #1

PRINT “Hello, “; name$


END
Retrieving Data
• Most programs access data from previous
uses of program Examples:
– Memory card on Video Game system accesses
old information from previous uses of game
– In MS Word, you can open a file you saved
yesterday to edit
• This involves the use of DATA files for
INPUT
A General Top-Down Model
• Program Starts
• Sub1 = Load Data (input from data file(s))
• Sub2 = Title Screen / Directions
• Sub3, 4, 5…etc
– Program does that thing it does
• Sub6 = Un Load Data (output to data file)
• End
General Model
• Programs typically follow these steps:
Program uses
Open a data Pull all DATA data from file,
File for from file to store
in variables maybe it changes
INPUT the data

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

PRINT “Current name = “name$


INPUT “Enter a new name” name$

OPEN “H:namedata.txt” for OUTPUT as #2


WRITE #2, name$
CLOSE #2
OUTPUT using WRITE #n
• PRINT #n command
– Sends information without quotation marks
• Useful for printing hard copy to be viewed by
humans
• WRITE #n command
– Sends information with quotation marks
• Useful for storing electronic data to be read by cpu
Sample Using PRINT #n
QBASIC CODE DATA FILE
OPEN ….. as #1 Bill 41
Job: Programmer
PRINT #1, name$ ; age $ 41000
PRINT #1, “Job: ”;
PRINT #1, job$
Easy
Easytotoview
view––has
has
PRINT #1, “$” salary labels
labelsand
and
formatting
formatting
Sample Using WRITE #n
QBASIC CODE DATA FILE
OPEN ….. as #1 “Bill”, 41
“Programmer”, 41000
WRITE #1, name$ ; age
WRITE #1, job$, salary
Harder
Hardertotoview,
view,but
buteasier
easier
for
forcomputer
computerto toretrieve
retrieve44
pieces
piecesofofinformation
information
Advantages of PRINT #n
• You can print literals
– PRINT #1, “The name is”
• You can print blank lines
– PRINT #1,
• Would print a blank line in the data file
• You can print spaces
– PRINT #1, “ “
• Would print several spaces in your output file
Disadvantage of PRINT #n
• Data files that are PRINTED instead of
WRITTEN are harder to be used as INPUT.
– Assume data file has been printed and the name was
Billy the Kid. Data will appear without quotes
– Assume, you later want to use this file as INPUT to
get the name out of it:
• INPUT #1, name$
• This would read only the first piece of data, which is Billy
Putting it all together
OPEN “H:namedata.txt” for INPUT as #1
INPUT #1, name$
CLOSE #1

PRINT “Current name = “name$


INPUT “Enter a new name” name$

OPEN “H:namedata.txt” for OUTPUT as #2


WRITE #2, name$
CLOSE #2
Chapter 6

Using Data Files for


Auxiliary Storage
Appending Data Files
• Open “Datafile.dat” for OUTPUT as #1
– Output means you erase any existing information and
sending new info to the file
• Great for High Score – Not so good for a database
• Open “Datafile.dat” for APPEND as #1
– Append means to add information to the end.
– Doesn’t erase old information
• Better for Database Program
Searching through Records
• Example: You have a data file full of
people’s names and how much money they
owe.
• Data file may look like this:
Billy, 20
Timmy, 50
Sally, 110
Jenny, 5
Searching Problem
• You want to look for all who owe $100 or
more and print their names:
• You need to keep reading names and
amounts.
• If the amount is $100 or more, you want to
show that name.
Code
OPEN “Debt.dat” for INPUT as #1
DO
INPUT #1, name$, amount
IF amount >= 100 THEN
PRINT name$; “ owes you big”
ENDIF
LOOP
CLOSE #1
Sending Information to Data
files
• Information can be sent to data file with
PRINT #n command for example:
OPEN “H:/myfile.txt” FOR OUTPUT AS #1
PRINT #1, name$
CLOSE #1
– The value stored in name$ (assume Billy the
Kid) would be printed to the data file
(mydata.txt). Would appear as…
Billy the Kid
Testing the end of a Data File
DO WHILE NOT EOF(1)
INPUT #1….etc
LOOP

• Data files have a special mark at the end call the


EOF mark.
• This loop continues as long as the EOF mark at
the end of file #1 has not been seen
QBASIC Notes

Color, ASCII Characters


FOR/NEXT loops
Color Changes
• Output color can be changed
– COLOR n (where n is a number 1 – 31)
• Sample: Color 2
– 2 = Green: Changes output to green
• You can also use a variable:
LET c = 4
COLOR c
PRINT “Hello” (since c is 4 and 4 is red, Hello would be red)
• See text pg. 413, table 10.8 for complete list of colors
CHR$ () Function
• CHR$ () function prints a character from
the ASCII set using an ASCII code number.
– EXAMPLE: PRINT CHR$(155)
• Prints the ¢ sign
– There are 256 different characters
• (numbers 0 – 255)
– See complete list on Pg. 544 of text.
Examples
FOR (i = 1 to 100) STEP 1
PRINT i
NEXT i

FOR (i = 50 to 20) STEP -3


PRINT i
NEXT i
QBasic Notes

Press Any Key Method


Time$, Date$, Timer
Press Any Key Method
• Often, you would like the program to pause until
the user is ready. The user can indicate they are
ready by pressing any key.
• This line of code allows that:
– LET dummy$ = input$(1)
• Often better than using SLEEP because it allows
the user to pick their pace.
• You should typically print a message so the user
knows they are expected to strike a key.
DATE$ Function
• DATE$ = String function which returns
the current date in mm-dd-yyyy format.
• Since a string value is returned, you must
do something with the value:
– PRINT DATE$ ‘Prints date
– LET today$ = DATE$ ‘Stores date
TIME$ function
• TIME$ = String function which returns the
current time in 24-hour format.
– hh:mm:ss
• Since a string value is returned, you must
do something with the value:
– PRINT TIME$ ‘Prints time
– LET now$ = TIME$ ‘Stores time
TIMER
• TIMER is a NUMERIC function which returns
the number of seconds since midnight.
• Options to use value
– RANDOMIZE TIMER ‘seeds rnd # generator
– PRINT TIMER ‘prints value on screen
– LET time1 = timer ‘stores value
– LET time_left = (11*60*60) – TIMER
• Would calculate time left until 11am.
QBASIC Notes

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.

• Think about how your program would work for a whole


week….month…year.
Most of you
enter day1
enter day2
enter day3…etc

total = day1 + day2 + day3…etc

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

i = control variable – increments loop


start = First number for i
finish = Last number
difference = Amount between numbers
Counting / Arrays using Do / Loops
DO
LET c = c + 1
INPUT somearray(c)
LOOP UNTIL c = 5

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>

Type the students name #1 - SMITH


Students Array after Filling
1 SMITH
2
3
4
5
6
7
8
9
10
Printing Arrays
• PRINT student$(1)
– Will print the information held in the student$
array at spot #1

• The QUICK Way


FOR i = 1 to 20 STEP 1
PRINT student$(i)
NEXT i
QBASIC Notes

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)

INDEX # first$ last$ age


1
2
3
4
To fill FIRST value in all arrays
LET first$(1) = “Abe”
LET last$(1) = “Lincoln”
LET age(1) = 128

INDEX # first$ last$ age


Abe Lincoln 128
1
2
3
4
To Fill All Values in All Arrays
FOR i = 1 TO 4
input first$(i)
input last$(i)
input age(i)
NEXT i
***Uses FOR loop to loop 4 times, changing
the value of i each time.
QBASIC Notes

Counters, Accumulators, Max/Min


Counters in Loops
• Counters are variables inside loops and are
used for many programming concepts
– Represented by name of Counter, C, or I
Counter Example

• 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 “The total of all numbers was”; total


Trackers

• Used to keep track of a condition such as


the highest or lowest number in a program
or the number of occurrences of
something.
Tracking the Highest Number
DO WHILE...
PRINT “Enter a number”;
INPUT number
IF (Number > MaxNumber) THEN LET MaxNumber
= Number
END IF
LOOP

PRINT “The highest number was “; MaxNumber


QBASIC Notes

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

Other Print Commands


Other Print Commands
• , Comma acts as tab key and moves output to the next
print zone (5 zones)
– Columns 1 to 14
– 15 – 28
– 29 – 42
– 43 – 56
– 57 – 70
– 71 - 80
– 5 tab stops exist, column 15, 29, 43, 57, 71
• ; Semicolon keeps cursor on same line in same spot
when printing
Space Command
• Used inside print statement to print spaces.
• General Form: SPC(x)
– Where x is the number of spaces to print.

• 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

Starters / Random Slides


Starter 10/14/04
• Create a program that asks the user for their
name, and height (feet and inches). The program
then shows this sentence:

Billy is 70 inches tall.

• Adjust the program with a loop so that it runs 4


times (4 names, 4 heights, 4 outputs)
Starter
• Write a program that uses a LOOP to print
the even numbers from 60 – 300
– Do NOT use a SLEEP
– Print Numbers Horizontally
60 62 64 66 68…………300
Sample
• READ name$, age, height$
• PRINT name$ ; “ is a child on my block”;
• PRINT “He is only “ age “ years old.”;
• PRINT “ but is “ height$ “inches tall.”
• END

• DATA “Willie”, 12, “6ft 3in”


Starter
• Create a program that allows the user to
enter a car name, the miles traveled and
gallons of gas used. The program then
reports the miles per gallon and allows the
user enter more cars until they enter either
0 miles, 0 gallons or a car name of
“QUIT”.
Starter
• Write a program with one subroutine
called math.problem
• The subroutine generates 2 random
numbers between 1 and 10
• It adds the numbers to find the right
answer, but doesn’t tell the user
• It asks the user their answer and tells them
if they are right or wrong.
Starter
• Write a program that lets the user type a
teacher’s last name.
• Next, it sends that last name to a data file
in your H: drive called teachers.dat
• Run the program and make sure it works.
You should be able to open the
teachers.data file and see your teacher
when you are complete.
Starter
• Write a program with 3 subroutines
– Get.Numbers
– Calculate
– Show Results
• The program should ask for two numbers and
divide them, third grade style, reporting the
quotient and remainder
• Hint: You need to use integer division( \ )and
MOD operators.
Sample
Enter the first number 14
Enter the second number 3

In third grade, 14 divided by 3 is:


4R2
(3 goes into 14 four times, with 2 left over)
Starter 10/12/04
• Create a program that shows shows the first 15
perfect squares in the following form:
1*1=1
2*2=4
3*3=9
…etc
• The program should use loop a loop to
accomplish this.
Starter Solution
DO
LET x = x + 1
LET square = x^2 ‘(or x * x)
PRINT x “ * “ x “ = “ square
LOOP UNTIL (x = 10)
Starter
• Write a program that shows your first name
• Then pauses for a second
• Then shows your last name after your first name
• (Show a space between your two names)

• Raise your hand when complete. I’ll check your


starter.
The GOTO command
• General Form
– GOTO label
• Function
– Transfers execution to label – similar to GOSUB, but
does not return back to statement
• Sample:
– GOTO section3
• Would search for section3 label and transfer execution to the
point after that label.
CHAIN command
• General Form
– CHAIN “filespec”
• Function
– Opens and executes another program
• Example:
– CHAIN “H:program3.bas”
• Would cause another program (program3) to open
and execute
• Current program would successfully terminate
ON ERROR command
• General form:
ON ERROR <code>
• Function
– Allows program to do something other than crash
when error occurs.
• Sample:
– ON ERROR GOTO error.message
– Program would search for error.message label and
move execution to that label.
STARTER
• Open your QB Interpreter and write a
program that prints today’s date.
• After that, the program skips a line and tells
what time it is.
• Example:
Today is July 20, 2001

It is currently 10:00pm

You might also like