QB Notes PDF
QB Notes PDF
to
At the conclusion of this module, students should be able to create their own
Qbasic programs from a list of problem tasks.
Notes:
MODULE OUTLINE T hes e n o te s ar e e s p ec i a l l y
developed to assist teachers and
Syntax and Semantics
students in classroom instruction with
Variable Storage exercises to re-enforce instruction.
Mathematical Expressions
A Problem Resolution Process Students with high language skills
Flow Control and familiarity with computers should
be able to independently complete
Making Comparisons – Conditionals
this tutorial.
Repetitions – the FOR loop
Repetitions – the DO loop
Repetitions – the EXIT condition loop
ANSI Flow Chart The notes make extensive use of flow-chart symbols to describe,
Process
Symbols explain the flow, or sequence of program instructions. Standard
symbols are used, so other people can read your flow chart dia-
Terminator
gram, and you can read other peoples’ diagrams. Stop
Process Program instructions are described through the flow-chart with instructions
grouped into different symbols, and the ‘flow’ or sequence of instructions being
used directed through the use of connecting arrows.
Input /
Output
Terminator. The terminator symbol marks the beginning, or ending of a se-
quence of instructions. This is often used when marking the beginning and end-
Decision ing of the program.
Process. Marks instructions that are processed such as calculations and decla-
Predefined rations. For our purpose, if you cannot figure out which symbol to use, then use
Process
this symbol as a placeholder until you can be more certain which is the better
flow-chart symbol to use. We will use it for when we make mathematical calcu-
Connector lations and declaring variables.
Page Input/Output. Marks instructions to perform data input (bring data into the
Connector
program from outside) or output (send data out from the program). We will use
this when we ask the user for keyboard input and when we display information
to the screen or printer.
Connector. Joins different parts of the chart together. This is used when the
chart gets big and the number of lines may become confusing. The connector cir-
cle is labelled with the label that will identify the ingoing connector.
Page Connector. Joins different pages of a chart. Use the page connector at
the bottom of the page, using the number of the page where the flow chart will
continue as the label. On the top of the connected page, place a page connector
symbol at the top of the flow-chart
CASE STUDY
Correct and Incorrect Use of Flow-chart symbols.
Observe in the sample diagram that the following errors are in the ‘Incorrect’ use
column.
♦ Flow should be from top to bottom, and should not split sideways except
through the use of a decision, or diamond, symbol.
♦ Only a decision can have multiple outgoing connections (arrows).
B
A B
0’s and 1’s mean very little to most human beings, and putting together a correct
sequence of 0001101011 01101011011 is problematic because it is very easy to
make a mistake. A mistake of putting a 1 where a 0 should be is minor to a human
but very important/significant for computers.
PRINT “Hello”
Converter
Language
01001011 01001011
Program INPUT CPU OUTPUT
Instructions
01001011
STORAGE
LANGUAGE RULES
Computer Programming Languages maintain a number of rules that are common
to the regular human language. To be a language it must have rules that prevent
ambiguity, misunderstanding, otherwise computers will behave differently from
each other.
A program in QBasic is entered into the Edit Window, and the programmer tells
QBasic to execute (run) the program instructions by using the command listed at
the status bar, bottom of the screen <F5=Run> or by selecting the Run menu.
The QBasic Development Environment is set into 3 tiled windows. The top win-
dow (usually hidden and only available when you ask for it) is used to display
HELP information. The middle window is the Editing window where program in-
structions are listed, edited. The lower window is the “Immediate” window where
QBasic commands/instructions can be entered for immediate execution.
The output screen, where the program puts out information, is hidden behind the
Integrated Development Environment (IDE) and can be viewed by using the
<F4=Output Screen>.
Start
Output
Stop
The above QBasic program when typed in and executed (by Selecting
<F5=RUN>)
<F5=RUN> will display an output screen as in Screenshot 7.2.
After you “Press any key to continue” you will be back into the Editing window.
To look again at the ‘output’ window, shown in this diagram, use the command
<F4=Output Screen>
SYNTAX CHECKING
Before executing any line of programming, QBasic first checks whether the things
you typed in is valid QBasic language. For many languages, this syntax checking
is generally processed after all the instructions have been listed (program has been
written/coded.)
QBasic has the ability to check each line of programming when the programmer
hits the Enter key. This is easily verifiable (confirmed) by typing in a QBasic
command in lowercase (eg. cls) and watch QBasic change the command to upper-
case (eg. CLS).
Error: CL S
The above is a ‘syntax’ error, or sentence grammar error since QBasic does not
know what to do with a CL and an S. CL (space) S has no meaning on its own,
unlike CLS (no spaces).
The print command needs the “quotation-marks” to know which things are to be
put straight to the screen, and which things to try and find from the computers
RAM (memory). In the above example, where there is no quotation marks, the
program will try to find memory space that have been labelled as:-
Hello, Everyone, I, am, a, QBasic, and Program.
Make sure you are careful with typing and note taking.
PRINT puts onto the screen the text inside the “quotation marks” and then starts a
new line.
There are times when a sentence on the screen looks better if it continues, instead
of starting again on the next line. The “;” semi-colon is used in QBasic to tell the
PRINT command to continue the next PRINT statement on the same line.
When the semi-colon is outside the “quotation marks”, it tells PRINT to continue
the next print instruction on the same line.
QBasic Tutorial – An introduction to Programming © 1997-200 No-Moa Publishers Page 6
Wednesday, February 09, 2000
PRINT USING writes formatted output to the screen or to a file.
Example:
a = 123.4567
PRINT USING "###.##"; a
a$ = "ABCDEFG"
PRINT USING "!"; a$
PRETTY PRINTING
QBasic’s PRINT USING command gives the programmer more control of how to display information on
the screen.
When printing numerical values, QBasic will automatically pick a format to fit as much of the decimal
values as it can. PRINT USING gives the programmer specific control of how many decimal values are
to be printed out, independent of how many decimals are actually available.
Listing
a = 123.4567
PRINT a
PRINT USING "#####.##"; a
PRINT USING "+####.####"; a
PRINT USING "$***"; a
Sample Output
123.4567
123.46
+123.4567
$%123*
Co-efficient
3x 2
Variable
Expanding New Knowledge: Computer programs need space (we will call
memory, RAM) to store information the program wants to manipulate or work on.
age = 11 .
PRINT "I am "; age; "years old." Stop
.
.
BE DESCRIPTIVE
Age - is a good name for a variable, because it is not
already used (reserved) by QBasic and because it describes what should be the
content of the variable. Whenever we look at the variable ‘age’ in our program
QBasic Tutorial – An introduction to Programming © 1997-200 No-Moa Publishers Page 8
Wednesday, February 09, 2000
code it looks like a memory address where a number related to the age of a person
is stored.
rk11 - will work as a variable name because it is not used (reserved) by QBasic
but it means very little to us and can be confusing when we use it.
When you write your programs, think about what the variables will be used for
and try to make the variable’s name describe what the variable contains. This
makes it simpler for you when you need to check your program, and simpler for
your friends when you ask them to help you check your program.
QBasic does not care whether your variable names are upper-case (capital letters),
lower-case (small letters), or a mix of the letters. QBasic will change the lettering
style to what ever you use as the last lettering style.
EXERCISES
List FIVE variables that are valid (we are allowed to use)
List FIVE variables that are not valid (we are not allowed to use)
For example, in the above sample program, if you type the last occurrence of the
age variable to all upper-case AGE, QBasic will change all “age” variables to
upper-case.
The output on the screen will look like the below diagram:
I am 11 years old
But I will grow and soon will be 25
Mixing the use of variables, and the PRINT semi-colon allows us to combine
various bits of information when we display the results to the screen.
Listing 1.5. Printing multiple variables
CLS
year = 1921
day = 14
month = 3
PRINT “The year is”; year
PRINT “The month is”; month
PRINT “The day is”; day
PRINT “-or-”
PRINT “The day is ”;day;”/”;month;”/”;year
Fill in the details below, how will the variables be allocated in the print display
below?
Storage.
The available computing resources; disk-space, RAM space is limited. The lim-
This section as- ited resource, and because computers handle text differently from numbers has
sumes completion led to programming languages defining the use and space used by storage loca-
of other modules tions.
on binary numbers
and their use in
computer storage.
Numbers – are stored as Integer, Long Integer, Single, or Double. Single and
Double are variable data-types that can store ‘whole numbers’ which includes
decimal values. Integers do not have decimal values.
It is a wise programmer who learns to use the appropriate data-type for the pur-
pose they choose their variable, and to select the maximum storage (number of
bytes) required.
QBasic uses the keyword DIM to dimension, set aside the memory location to
store the data being pointed to by
your variable. data-types
INTEGER, LONG, SINGLE, DOUBLE,
DIM variable AS data-type STRING, or a user-defined data-type
The DIM keyword is specified at the beginning of the line, followed by the vari-
able name you choose, the keyword AS and the data-type to be used. For example:
Singles and Double can store numbers which include decimal values. There-
fore, it can also hold integers. This num-
Data Type Minimum Value Maximum Value ber type can hold larger numbers than In-
(byte size) teger and Longs
Single-precision (4 bytes)
Positive 2.802597*10-45 3.402823*1038
DIM numb2a AS SINGLE
DIM numb2b AS DOUBLE
Negative -3.402823*1038 -2.802597*10-45 numb2a = 142
Double-precision (8 bytes) numb2a = 1.0234
Positive 4.940656458412465D-324 1.79769313486231D+308
Negative -1.79769313486231D+308 -4.940656458412465D-324
Numb% = 4
numbers! = 1027.25
brand$ = "Avon Lady"
The above program will create two new string variables name1$ and name2$ to
hold the value given to them above. For example, we are telling the variables to
hold "Freddy Bloggs", and "Freddy Bloggs sister". The following PRINT state-
ments will print out the contents of the variables to screen.
We already know how to use the keyboard to enter data and store it within a vari-
able of your choice. We have already used the following statement.
CLS
Mixing INPUT and OUTPUT, using the ";" semi-colon is a tool for communicat-
ing with the user, formatting the output of our program onto the screen.
CLS
INPUT "Enter a year "; year
INPUT "Enter a day "; day
INPUT "Enter a month "; month
The above program will display something such as the below (using input of 1998,
8, 10 )
By using a comma when entering data, the above INPUT command separates the
information entered into the variable names listed in its list. An example output is
listed below:
USING COMMENTS
As a general rule, the overall program should have comments at the beginning,
telling you what the program does. Each section (function) should also have com-
ments explaining what it does and what values it returns. Any area in your pro-
gram that is difficult to understand, less than obvious should be commented.
Listing . Demonstrates the use of comments
REM
' Author: Samiuela LV Taufa
' Class: Computer Studies 101
' Date: December 11, 1996
'
' Purpose:
' This is program shows user input, and computer output
PRINT "Enter your first and last name separated by a comma"
INPUT "", name$, lname$
PRINT "Hello "; lname$; ", "; name$
Qbasic lines that begin with the REM command are ignored, because REM stands
for ‘remark’. The short-hand for typing in REM is to use the single quote ( ' ).
The simplest example of using the mathematical operators is to use the PRINT
statement such as:
cls
age = 25
PRINT 25 * 42
PRINT age * 42
Qbasic uses a table to distinguish how to represent mathematical symbols into the
programming language. For example, since we cannot type in y = x2 in Qbasic
the mathematical method (looking at the table) is to type in y = x^2 (using the ex-
ponent operator) or we can use y = x * x (using the multiplier operator).
Given the following mathematical formulas, how would you write it in a line of
QBasic programming?
x y z Formula Value ?
4 11 3 z=x^2+y z?
2 1 3 y=2*x+4*z+y y?
y = 4*x^2 + 15*z + 32 y?
Higher levels are calculated before the levels below it. Level 1 (Brackets) have
precedence, or are calculated before Level 2, 3, and 4. Likewise, Level 2 has
higher priority and is calculated before Level 3, and 4.
Operations in the same level (for example Level 3, Multiplication and Division)
can be performed in any order. 2 * 3 / 2 provides the same answer whether the
multiplication is calculated first than the division, or the division is calculated first
before the multiplication.
PROJECT EXERCISE
Write a program to calculate the volume of a circle by using the following for-
mula, and values:
V = πr2h
π = 3.141593
r = 10
h = 11
Circumference: C = 2πr
Area: A = πr2
Ask questions if you are not sure you understand the problem. Ask questions to
your teacher, your friends, the person who has the problem.
A good summary of the intended solution should be put into the documentation of
your program.
Sample Output
For a circle with radius _________
The Area is ____
The Circumference is _____
• We know from our previous exercises, how to convert the mathematical for-
mula into the QBasic Statement
Problems not easily resolved with a simple mathematical calculation may require
you to think through differing sequences of calculations, instead of a single for-
mula.
The logic of a program, often called the algorithm, is the sequence of instructions
required to create the solution, answer, to the problem.
Although it may seem difficult to determine the logic or the sequence to solving a
problem, it often is simplified by starting the thinking process instead of worrying
about whether it can be done or not.
Attempt 2.
• Get the value for radius from somewhere (lets get it from the user)
Circumf for the Circumference C, may contain decimal values so we use either a
SINGLE or DOUBLE.
Start (a) Area for the Area A, may contain decimal values so we use ei-
ther a SINGLE or DOUBLE. and
PI for the value of π, may contain decimal values so we use ei-
(b) Declare Cir-
Declare Variables. cumf, Area, PI,
ther a SINGLE or DOUBLE.
Define Known radius. We are
Values
also define PI to radius will be used for the value of the radius which we will
be 3.147 ask from the user, may contain decimal values so we use either
a SINGLE or DOUBLE.
Get unknown
values from
(c) radius 4TH. DRAFT THE COMPUTER PROGRAM
user
Although some people may think their programming skills are
cool enough that they are now ready to create the program on
Calculate Area
the computer, it is always good practice to draft your program
(d) Area, Circumf
& on paper, and to test the logic implementation by paper-
Circumference
execution of your program.
For our exercise: We know that the only value that changes is radius so it is a
good idea to calculate on paper (or using your calculator) a few values for radius
and then compare this with the program result.
COLOR 9
' (c) Get Required data from user
PRINT “This program calculates the Area and Circumference of a Circle”
INPUT “What is the radius of the circle”; radius
' (e) Send the results to the screen for the user
COLOR 2
PRINT "For a Circle of radius"; radius;
PRINT "and using a value for PI as"; PI
PRINT "The calculated Circumference is"; Circumf
PRINT "The calculated Area is"; Area
'
' (f) Stop
12 .................. ..................
14 .................. ..................
15 .................. ..................
22 .................. ..................
45 .................. ..................
Fig. Program
with a Branch Fig. Program
with a Loop
Yes Yes
Decision Decision
No No
♦ “yes,” we ‘branch’ to the red process complete that exercise, skip the blue box
and continue the program.
♦ “no,” we ‘branch’ to the blue process complete that exercise, skip the red box
and continue the program
Loops, iterations. In our flow-chart diagram when we reach the decision two
things can happen, either our decision results in a “yes,” or a “no”.
Enough problems require our programs to make decisions about different things to
do that it is not sufficient to solve problems using simple mathematical formulas.
Preamble
Before we can discussion decision making processes (keywords and methods used
by QBasic to make comparisons) we need to first of all understand how
comparisons are made. The following section is a discussion of how comparisons
are made in computer programming.
Linking the comparison again with our flow-chart diagrams, one line of code will
a%=1: b%=2: c%=3
Our decision, condition, is if a% < c%, “yes” then we will branch and complete
the red, while if the decision is “no” then we will complete the blue branch. A
general term for the diamond, or decision, is that it is a condition. Depending on
the ‘condition’ different parts of the program will be processed.
IF IF condition THEN
THEN
is a% < c% stuff in red
ELSE
ELSE stuff in blue
ENDIF
ENDIF
If we stick the IF, THEN, ELSE into the diagram. We have
Fig. is a% < c% ? the IF marking our decision. THEN is what happens when the
decision results in a “yes” and ELSE is what happens when
the decision results in a “yes”. ENDIF marks where things go back to the normal
sequence of program instructions.
Using the above structure (template) we now have a program code that will look
something like the following:
PROGRAM EXERCISE
IF a% < c% THEN
stuff in red
ELSE
stuff in blue
ENDIF
Using the above example, and the template, write the program code for the other
six decision examples, such as c% >= a% + b%.
COMPARING COMPARISONS
When a problem requires using more than one relationship, it becomes difficult to
keep track of what is happening to the code when the problem requires checking
multiple relationships. Comparing comparisons evaluates more than one
relationship, as one comparison, and makes a decision whether it is a yes or a no.
F F F F T F
Continuing the previous example:
The Logical Condition Comparisons F T
The Logical Condition
The Table: Logical Condition Comparison Comparisons
summarises the above discussion when comparing two
separate test expressions, expression1 and expression2
a%=1: b%=2: c%=3
PROGRAM SAMPLE
Translating the a% < c% AND c% >= a% + b% sample into Qbasic programming
code, we refer to the template (outline).
IF condition THEN
stuff in red
ELSE
stuff in blue
ENDIF
PROGRAM EXERCISE
Using the above example, and the template, write the program code for the other
six decision examples, such as c% >= a% + b% OR c% < a.
IF
IF condition1 THEN THEN statement
conditio n
[statementblock-1] block-1
[ELSEIF condition2 THEN
[statementblock-2]]... ELSE
[ELSE statement
[statementblock-n]] block- n
END IF ENDIF
Fig. The IF statement
Instructor
Notes: First the condition1 is evaluated. If it is true, the statements contained in the state-
It is helpful in this mentblock-1 are executed. After that is executed, then the program continues after
section to 'mark' the END IF line. If not, the statements contained in the ELSEIF block are evalu-
for students the
statement blocks ated, executed.
surrounding the
IF statement. Both the ELSEIF and ELSE statements are optional, and either both can be absent
or both can be in the program.
A simple example
We can set up a target, and ask for the sales. When the sales meets or exceeds
the target then we are happy, but when the sales are below the target this is not a
good thing.
Determine the Purpose.
Stated above.
What are the Required Data. IF
♦ Target Sales THEN
Sales >= “W e are
♦ Canteen Sales
Targe t Happy”
Determine the Logic.
♦ When sales meets or exceeds target, we
are happy.
Draft the Computer Program. ENDIF
Fig. IF statement sample
Test & Re-test.
When sales exceeds or meets the target we want to give a bonus, but when the
sales are below the target we want to not give a bonus.
Determine the Purpose.
Stated above.
What are the Required Data.
♦ Target Sales
♦ Canteen Sales
♦ Bonus Amounts
PROGRAM EXERCISE
Create a flow-chart of the suggested solution as described above.
♦ Canteen Sales
♦ Bonus Structure
PROGRAM EXERCISE
Create a flow-chart of the suggested solution incorporating the mathematical rep-
resentation described above.
Bonus 1000 No
Sales >= 1.5 *
Target
Yes
Bonus 500 No
Sales >=
Target
Yes
SELECT CASE allows you to write program code that is easier to interpret/read
and therefore easier to correct, de-bug. The SELECT CASE provides a better pro-
gram structure for multiple decisions/alternatives. Select
TestExpression
Yes
In this example, the SELECT CASE testexpression 1 M onday
No
uses the variable dayNumber to determine which Yes
2 Tuesday
CASE statement will be executed by the SELECT No
CASE. 3
Yes
W e dn es d ay
No
Yes
The SELECT CASE checks the testexpression which 4 Thursday
No
Yes
What if there is no match? If there is no match, then ? W hat ?
In Class Exercise
1. Draw a flow-chart of the Select Case program
2. Run a desk-check using the values 3 and then 8 and write down what the ex-
pected result is going to be.
Summary
The SELECT CASE checks the testexpression then the program scans the list of
"expressionlists" until it finds one that matches that value. The program then
jumps to the statement block in that CASE.
If there is no match then the program goes to the end of the SELECT CASE block
and continues with the next program statement.
In Class Exercise
1. What is the variable used as the testexpression
4. What number does the user have to enter to get the message about Prefect ?
Group Exercise
1. Draw a flow-chart of the select case to place into the variable mth$ the actual
month name (eg. January, February) if we input the value of the month into the
variable mth_numb%
In Class Exercise
1. Draw a flow-chart of the select case to display a message related to the input the
value of the student Form in the variable stForm%
Individual Exercise
1. Draw a flow-chart of the select case to place into the variable status$ the actual
student status (ie. Freshman if 1st year student, Sophomore if 2nd year student,
Junior if 3rd year student, Senior if 4th year student) if we input the value for the
student year into the variable stud_year%
Select
stForm
Yes
>=5 Senior
No
Yes
2 - 4 Develop'
No
Yes
1 Babe
End Select
'
' Another look at the IF3 program us-
ing SELECT CASE
Select Case
' canteenSales
CLS
INPUT "Target "; target
INPUT "Sales "; canteenSales “Excellent”
> 2 * target
bonus = 1000
SELECT CASE canteenSales
CASE IS >= 2 * target > 1.5 * “Fine”
performance$ = "Excellent" target bonus = 500
bonus = 1000
CASE IS >= 1.5 * target “Satisfactory”
performance$ = "Fine" >= target bonus = 100
bonus = 500
CASE IS >= target
performance$ = "Satisfactory" “Unsatisfactory”
ELSE
bonus = 0
bonus = 100
CASE ELSE
performance$ = "Unsatisfactory"
bonus = 0 End Select
PRINT "You are FIRED!!"
END SELECT
The above sample shows how much easier it is to follow the program flow in a se-
lect statement over the IF THEN ELSE when more than two relation comparisons
have to be used.
FOR i = 1 TO 10 i=1
PRINT “This is the “; i; “time ...”
NEXT i
repetition. Predetermined: If before the loop starts we know exactly how often
the loop will be repeated, then we can say that loop has a ‘predetermined’ repeti-
tion.
We do not know what these QBasic colours look like, and we could write 0 to 15
COLOR different lines of code for each color, but lets see if we can use the new loop struc-
For those who
wish to know tures.
more about the
COLOR
statement, more 1 We need to go through the numbers 0 through to 15 so we can use a
information is FOR counter = 0 to 15.
available in the
Qbasic help 2 Let us use ncolor as the counter variable
screens.
Loop Process
Yes
ncolor >
15 ?
Listing
CLS No
FOR ncolor = 0 TO 15 COLOR
COLOR ncolor
PRINT "Color "; ncolor; "looks like this" color
NEXT ncolor looks
ncolor =
ncolor + 1
ncolor values is the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15}
st
♦ The 1 time through the repetition; 0 is put into i because it is the 1st num-
ber in the list.
nd
♦ The second time through the loop; 1 is put into i because it is the 2 number in
the list, etc.
♦ This continues until the last number from the list is QBasic’s Colors
used. Black ......................... 0
Blue ........................... 1
Inside the Loop. Green ........................ 2
Each program statement is executed from the beginning of Cyan.......................... 3
the loop to the end. Red............................ 4
Magenta .................... 5
Brown ........................ 6
White ......................... 7
Grey .......................... 8
Light Blue .................. 9
Output Light Green ............. 10
Light Cyan ............... 11
Color 0 looks like this Light Red................. 12
Color 1 looks like this Light Magenta ......... 13
Color 2 looks like this Yellow...................... 14
… Very Bright White .... 15
Color 15 looks like this
♦ .. increment
loop
♦ Add n to sum
calculations
Extending the 1st two flow-charts, we get a flow chart similar to the one on the left.
Get n
1. We need to get the number n we want to work with. Let us get this from the user.
2. We set the current sum to 0 (zero) since we haven’t started counting.
Sum = 0 3. We set up the loop (using our previous chart)
- Check if we still have a valid number to add ?
- add the loop counter to sum
No
i <= n - increment, add 1, to the loop counter
4. Print out our calculated sum
Yes
sum = sum
+i
i=i+1
Note:
Print For improved student learning; It is im-
sum portant that this OUTPUT exercise be
completed together on the board with
students.
In Class Exercise
1. As in the previous Loop examples, write down the set and values for the loop
counter when the user enters 5 for n.
2. Write down what you analyse will be the output for the above program when
the user enters 7 for n.
Teaching Note:
To verify students have understood this structure it is suggested that at least two more examples (of simply the loop structure) be dis-
cussed and reviewed during class time.
Two samples of source is provided here. It is suggested that one example as completed together on the board, and the 2nd, 3rd be at-
tempted by the students under guidance from fellow students and from the teacher.
The condition for repeating the loop is usually dependent on data being manipu-
lated within the loop.
DO
Exit-condition loop
[statementblock]
LOOP [{WHILE | UNTIL} condition]
The DO LOOPs are control structures that let you repeat statements in a similar
fashion to the for loop. The DO LOOPs are best used when you do not know how
many times a loop should be processed (another term
for it is indeterminate loops, or conditional loops.)
Entry Condition loops evaluate the condition before it executes the instruc-
Inside the Loop tions inside the loop. Evaluating at the beginning (or top) means that if the
condition is not met the instructions inside may never be executed.
Yes Exit Condition loops evaluate the condition after it executes the instructions inside
Condition the loop. This means that the instructions in the loop will be executed at least
once.
No
QBasic Tutorial – An introduction to Programming © 1997-200 No-Moa Publishers Page 40
Wednesday, February 09, 2000
CASE STUDY. CALCULATING THE POWERS Logic Review as Flow
We would like a program to list all the resulting powers Chart
of an integer that is less than 1,000 (the maximum result-
Keep No
ing power).
Going?
Yes
For example: Calculate
20=2, 21=2; 22=4, 23=8, 24=16, 25=32, 26=64, Power
2 =128, 28=256, 29=512
7
Print Out
Power
Determine the Purpose.
Stated above.
What are the Required Data.
♦ n the integer Required Data ?
♦ maximum power to keep the program from
max ?
‘overflowing’ we will set it to 1,000
i
♦ Power is calculated as n when i goes from 0 to infinite
0
♦ n = 1 by definition of powers (indices)
Get number
Determine the Logic.
♦ Use variable Power to store the value of the calculated
♦ We cannot use the FOR loop, because we do not know Power = n^i
how many repetitions are required before we go into
Print Out
the loop. Power
♦ We do have a condition for exiting the loop (when
Power = 1
i=1
max ?
Power No
<= max?
Get number Yes
Power = n^i
A
Print Out
Power
i=i+1
COLOR 10, 1
CLS
PRINT "This program prints all powers <"; MaxPower; "of an Integer."
INPUT "Enter an Integer"; n
Learning Notes:
DO WHILE Power < MaxPower
PRINT Power; Demonstrate using n=2; the provided sample, and n=4
Power = Power * n to let the students think through the mathematics and
LOOP the looping condition.
In Class Exercise
1. Write down what the program output will be if the user enters 5 for n.
2. Write down what the program output will be if the user enters 10 for n.
3. Write down what the program output will be if the user enters 20 for n.
♦ Calculate F (Fahrenheit)
♦ celStep to hold how many Celsius up we move before calculating the next Fahr-
enheit.
♦ Celsius we will increment in whole numbers, so we use the INTEGER type
COLOR 14, 7
CLS
PRINT "This program prints a table of Celsius and Fahrenheit temperatures"
Celsius = minCel
• Celsius is –10 and maxCel is 30. The condition is true so enter the loop
♦ Calculate Fahren. Fahren is now 14
♦ Print the value of Celsius and Fahren to the screen
♦ Calculate Celsius = Celsius + celStep; Celsius is now –5
♦ We hit the end of the loop, so we go back to the beginning
Group Exercise
1. Draw a more detailed flow-chart of the above program.
In Class Exercise
1. Write down what the program output will be if celStep were 10 instead of 5.
2. Write down what the program output will be if celStep is 5 and maxCel is 10.
♦ Deposit Amount
♦ Length of Deposit
PRINT "So you want to put some money aside for retirement, hmmmm."
INPUT "How much money do you need to retire"; goal
INPUT "How much money will you contribute every year"; payment
INPUT "Interest rate in % (eg. use 7.5 for 7.5%)"; interest
In Class Exercise
1. Using the previous Code Review; Desk-Checks, perform your own Code Re-
view on how the program will process the program using the following sample
data:
goal = 50,000
interest = 5.0%
payment = 5,000
There are several reasons why computer scientists consider an entry condition
loop superior. One is the general principle that it is better to look before you leap
(or loop) than after. A second point is that a program is easier to read if the loop
test is found at the beginning of the loop.
Finally, in many uses, it is important that the loop be skipped entirely if the test is
not initially met.
No
Power <= 1,000
By rearranging the logic used in our earlier en- PRINT stuff
Yes try-condition loop we now have an exit-
condition loop performing the same calcula-
tion. This will only work properly if the user modify condition
PRINT stuff variables
had entered an n > 0.
Yes
nguesses = 1 nguesses = 0
PRINT "Guess #:"; nguesses;
INPUT guess
DO WHILE guess <> numb AND guess <> 0 DO
nguesses = nguesses + 1 nguesses = nguesses + 1
PRINT "Guess #:"; nguesses; PRINT "Guess #:"; nguesses;
INPUT guess INPUT guess
LOOP LOOP UNTIL guess = numb OR guess = 0
There are very legitimate times when an exit-condition loop makes more sense
than rewriting your logic (algorithm) to fit the entry-condition loop. The above
PRINT "Press Esc to exit..."; PRINT "Press Esc to exit...";
'{stuff to be done before checking the
“Esc” has been pressed}
DO WHILE INKEY$ <> CHR$(27) DO
' {stuff to do} ' {stuff to do}
LOOP LOOP UNTIL INKEY$ = CHR$(27)
exit-condition loop requires fewer instructions than the entry condition loop.
The entry-condition loop shown above indicates that for some algorithms an entry-
condition loop can get complicated trying to duplicate code better implemented as
an exit-condition loop.
DO
' player guesses the number
LOOP UNTIL {player quits –or– guess is correct} No
Right or Quit ?
Yes
A common use of the exit-condition loop is for monitoring input
where a specific value is desired.
COLOR 10, 1
CLS
LOCATE 25, 1
PRINT "Press Yes or No to continue (Y/N)" LOCATE moves the cursor to a
specified position on the screen.
DO
A$ = INKEY$ LOCATE [row%] [,column%]
LOCATE 12, 25
PRINT "You entered "; A$ ■ row% and column% The
number of the row and column
LOOP UNTIL A$ = "Y" OR A$ = "N" to which the cursor moves.
Exit-Condition Menus
An example of where exit-condition loops are more appropriate than entry-
condition loops are programs with “menu” choices from which the program user
selects a program operation. The menu for a statistics program might look as fol-
lows.
1. Compute an average
2. Compute a standard deviation
3. Find the median
4. Find the smallest and largest value
5. Plot the data
Putting together a sample of just the above menu, without the actual work that is
to be done with the user selection would look something similar to the following
sample code.
Group Exercise
1. Draw a flow-chart of the above code program flow.
In Class Exercise
1. Using the previous Code Reviews as an example, describe what the program
above will do when the user enters the following data samples:
DO
INPUT "Enter your choice (0 through 5) "; a%
' Use SELECT CASE or IF to check the user
' input, and do the work that has been requested
LOOP UNTIL a% = 0
1, 3, 4, 2, 0, 5, 3
Select Yes
guess
Yes
> secret Too Big
No Yes
Do The Work
Expanded < secret Too Small
No
Yes
ELSE Just Right
End Select
RANDOMIZE [seed%]
RND[(n#)]
n# A value that sets how RND generates the next random number:
n# RND returns
Less than 0 The same number for any n#
Greater than 0 (or omitted) The next random number
0 The last number generated
Example:
RANDOMIZE TIMER
x% = INT(RND * 6) + 1
y% = INT(RND * 6) + 1
PRINT "Roll of two dice: die 1 ="; x%; "and die 2 ="; y%
REVIEW EXERCISES.
1. Draw a detailed flow-chart diagram of the above exit-condition program.
Hint: Combine the separate flow-charts we have reviewed for each of the separate
items.
2. The Number Guessing game limits the guessing between 1 and 100. Which
variables will you modify to let the program to ask the user to provide the smallest
number and the biggest number.
3. The Number Guessing game does not provide a way for the user to continue
playing the game, without having to restart the program. Draw a flow-chart indi-
cating the changes you would make to allow the user to select to play another
game.
Hint: Finish Question 1, and this part is much easier.
♦
' Program:
'
' Author:
' Class:
'
' Purpose:
' This is a guessing game program to highlight the use of flow control
' where the user tries to guess a secret number
'
' (a) Start
' Declare variables
CONST maxNumb = 100 ' The biggest number
CONST minNumb = 1 ' The smallest number
the program.
DIM nguesses AS INTEGER ' The number of guesses
DIM quitNumb AS INTEGER ' The number the user can use to Quit
number
' Explain the game
secret
Pick a
'
CLS
PRINT "Number Guessing Game : Charley Alpha"
PRINT "I have picked a secret number between and including";
person using it
game so the
understands
PRINT minNumb; "and"; maxNumb
Explain the
PRINT "How many times will it take you to guess the number?"
PRINT "If you want to give-up at any time, just enter"; quitNumb
nguesses = 0
DO
nguesses = nguesses + 1 Loop, waiting for the user to guess
PRINT "Guess #:"; nguesses;
PRINT
IF guess = numb THEN
the user to play again,
PRINT "Congratulations"
A little incentive for
2. There are two types of variables. List, describe and give an example for each of these two types
3. There are many ways of assigning data to a variable. Using an example, describe the ways of storing
a value in a variable
4. Comment lines are very common in programs. Give a reason why comment lines are included in
programs
5. There are two ways of writing comments on a program. Identify each method
6. For each of the following reserved words, Describe its purpose and write down a simple example
a) PRINT
b) DATA
c) CLS
d) END