Home » Software development
Category Archives: Software development
03 QBasic Tutorial Decisions and loops
Learning Objectives
THIS SECTION IS BEING UPDATED… NOV 2015
At the end of this tutorial you will know:
How to use Loops eg conditional (pre-check, post-check), fixed to repeat actions
How to use conditional statements and logical operators to make decisions
Selection: Where you choose to do something or not!
If there is something you might want to do depending on a situation or condition use IF/ENDIF.
If there are one out of two actions you might want to do depending on a situation or condition us IF/ELSE/ENDIF
IF condition1 THEN [statementblock-1] END IF
IF condition1 THEN [statementblock-1] [ELSE] [statementblock-2]] END IF
IF condition1 THEN [statementblock-1] [ELSEIF condition2 THEN [statementblock-2]]... [ELSE] [statementblock-n]] END IF
condition1 Any expression that can be evaluated as
condition2 true (nonzero) or false (zero).
statementblock – One or more statements on one or more lines of basic.
Conditions
Examples
DIM strName as STRING CLS PRINT "Who is a clever clogs? "; INPUT strName IF strName <> “Michael” THEN PRINT strName “ is a thickie” ENDIF PRINT “Michael is clever” END
Test the program with this data
Input: Michael
Expected output:Michael is clever
Input: Peter Bob Bill Michael MICHAEL, michael, M TOM DAVE
Expected output: is a thickie ( Peter, Bob, Bill, Michael, MICHAEL, etc) Michael is clever
Using ALL the test data above and change strName <> “Michael” to:
- strName <= “Michael” strName >= “Michael”
- strName > “Michael”
- strName < “Michael”
- strName = “Michael”
- strName = “michael”
- lcase$(strName) = “michael”
- lcase$(strName) = “Michael”
- ucase$(strName) = “michael”
- ucase$(strName) = “MICHAEL”
Make a note of what happened here, you will be asked in class what occurred.
Program Code – Type it in
DIM strName as STRING
CLS
PRINT “Who is a clever clogs? “;
INPUT strName
IF strName <> “Michael” THEN
PRINT strName “ is a thickie”
ELSE
PRINT “Michael is clever”
ENDIF
END
Test the program with this data
Input: Michael
Expected out put:
Michael is clever
Input: Peter Bob Bill Michael MICHAEL, michael, M TOM DAVE
Expected output:
is a thickie ( Peter, Bob, Bill, Michael, MICHAEL, etc)
Michael is clever
Using ALL the test data above and change strName <> “Michael” to:
strName <= “Michael” strName >= “Michael”
strName > “Michael”
strName < “Michael”
strName = “Michael”
strName = “michael”
lcase$(strName) = “michael”
lcase$(strName) = “Michael”
ucase$(strName) = “michael”
ucase$(strName) = “MICHAEL”
Make a note of what happened here, you will be asked in class what occurred.
CASE
Executes one of several statement blocks depending on the value of an
expression.
SELECT CASE testexpression
CASE expressionlist1
[statementblock-1]
[CASE expressionlist2
[statementblock-2]]…
[CASE ELSE
[statementblock-n]]
END SELECT
■ testexpression Any numeric or string expression.
■ expressionlist1 One or more expressions to match testexpression.
■ expressionlist2 The IS keyword must precede any relational operators in an expression.
■ statementblocks One or more basic statements on one or more lines
‘Program: A simple menu
‘Author Michael Fabbro
‘Date 7 December 2003
DIM strCommand AS STRING
DIM intStartLine AS INTEGER
CLS
LET IntStartLine = 0
LOCATE 2, 25: Print “Concrete Calc Main Menu”
LOCATE intStartLine + 6, 15: Print “[B]lock”
LOCATE intStartLine + 8, 15: Print “[C]ylinder”
LOCATE intStartLine + 10, 15: Print “[P]yramid”
LOCATE intStartLine + 12, 15: Print “Enter B,C,P”
LOCATE intStartLine + 12, 30: INPUT strCommand
‘convert to uppercase
strCommand = UCase$(strCommand)
Select Case strCommand
Case Is = “B”
PRINT “You want a block”
Case Is = “C”
PRINT “You want a Cylinder”
Case Is = “P”
PRINT “You want a Pyramid”
Case Else
PRINT “Don’t know that option”
PRINT “Try again”
End Select
END
Test the program with this data
B “You want a block”, C You want a Cylinder”, P “You want a Pyramid”
Z W “Don’t know that option”
Test Results
STRING FUNCTIONS
LCASE$(stringexpression$)
UCASE$(stringexpression$)
Convert strings to all lowercase or all uppercase letters.
■ stringexpression$ Any string expression.
Example:
strPlace = “THE string”
PRINT strPlace
PRINT LCASE$( strPlace); ” in lowercase”
PRINT UCASE$( strPlace); ” IN UPPERCASE”
LEFT$(stringexpression$,n%)
RIGHT$(stringexpression$,n%)
Return a specified number of leftmost or rightmost characters in a string.
■ stringexpression$ Any string expression.
■ n% The number of characters to return, beginning
with the leftmost or rightmost string character.
Example:
strText = “Microsoft QBasic”
PRINT LEFT$( strText, 5) ‘Output is: Micro
PRINT RIGHT$( strText, 5) ‘Output is: Basic
MID$(stringexpression$,start%[,length%])
MID$(stringvariable$,start%[,length%])=stringexpression$
The MID$ function returns part of a string (a substring).
The MID$ statement replaces part of a string variable with another string.
■ stringexpression$ The string from which the MID$ function returns a substring, or the replacement string used by the MID$ statement. It can be any string expression.
■ start% The position of the first character in the substring being returned or replaced.
■ length% The number of characters in the substring. If the length is omitted, MID$ returns or replaces all characters to the right of the start position.
■ stringvariable$ The string variable being modified by the MID$ statement.
Example:
strPlace = “Where is Paris?”
PRINT MID$( strPlace, 10, 5) ‘Output is: Paris
strPlace = “Paris, France”
PRINT strPlace ‘Output is: Paris, France
MID$( strPlace, 8) = “Texas ”
PRINT strPlace ‘Output is: Paris, Texas
Exercise 1
You know how to input numbers, calculate and print out the answer. Now add the case statement to this knowledge and write a program that will input two numbers and then a menu that will add, multiply, subtract or divide those number and print out the answer. You will need the following basic:
LET + – / *, DIM STRING INTEGER SINGLE, CASE, INPUT, PRINT, PRINT USING , CLS
Checking for errors in input
Avoiding negative numbers in calculations
Type this program in
DIM sngPi, sngRadius, sngArea as SINGLE
CLS
sngPi = 3.1415
INPUT “What is the radius of the circle? (-1 to end) “, sngRadius
IF sngRadius <> -1 THEN
sngArea = sngPi * sngRadius ^ 2
PRINT “The area of the circle is “, sngArea
ENDIF
END
Test the program with this data
Input: SngRadius = 2
Output: The area of the circle is
Input: SngRadius = -4 negative radius
Output: The area of the circle is 50.272
Error condition
Input: SngRadius = 20
Output: The area of the circle is
Input: SngRadius = 999999999
Output: The area of the circle is
Error condition
Test the program with this data
Test Results
Try changing sngRadius <> -1 to sngRadius<0
Which is better?
Part 3 Loops/Iteration ‘Repeating things’ (Session 7-9)
There’s one big problem with the program. If you needed to try hundreds of radii, you must run the program over again. This is not practical. If we had some kind of a loop until we wanted to quit that just kept on repeating over and over it would be much more useful. Of course, QBasic has the means of performing this feat. Loop structures. They start with the statement DO, and end with the statement LOOP. You can LOOP UNTIL or WHILE , or DO UNTIL or WHILE a condition is true. Another option (which we will use) is to break out of the loop manually as soon as a condition is true. Lets revise the previous code:
Program Code – Type it in
DIM sngPi, sngRadius, sngArea as SINGLE
CLS
sngPi = 3.1415
DO ‘ Begin the loop here
INPUT “What is the radius of the circle? (-1 to end) “, sngRadius
IF sngRadius <> -1 THEN
sngArea = sngPi * sngRadius ^ 2
PRINT “The area of the circle is “, sngArea
ENDIF
LOOP WHILE sngRadius <> -1
END
Test the program with this data
Input: SngRadius = 2
Output: The area of the circle is
Input: SngRadius = -4
Output: Program finishes
Input: SngRadius = 20
Output: The area of the circle is
Input: SngRadius = 999999999
Output: The area of the circle is
Test the program with this data
Test Results
Now we can end the program by entering -1 as the radius. The program checks the radius after the user inputs it and checks if it is -1. If it is, it exits the loop. If it isn’t it just keeps going it’s merry way. TRY changing
LOOP WHILE sngRadius <> -1 to
LOOP UNTIL sngRadius = -1
The Do statement repeats a block of statements depending on a boolean (true or false) condition. The condition is tested at the beginning if it appears on the Do or at the end of the loop if it appears on the Loop. The While keyword continues the loop while the condition is true. The Until keyword continues the loop while the condition is false (stops when the condition is true).
ANSWER THE FOLLOWING 3 QUESTION and you will know what type of loop you will need.
· If you want to repeat something and you know how many times you will do it before you start – used the FOR NEXT LOOP
· If you want to do something at least once and maybe repeat it again – use DO LOOP
· If you are not sure whether you want to do something nor how many times to repeat it – use the DO Loop
FOR loops
Use where you know how many times you want something to repeat.
The FOR statement repeats a block of statements for a specified number of times.
FOR variable=initialValue TO finalValue
Statements are repeated while the variable is at or between initial and final values. The variable is incremented by 1 each time.
NEXT variable
FOR variable=initialValue TO finalValue STEP
Statements are repeated while the variable is at or between initial and final values. The variable is incremented by increment each time.
NEXT variable
Description
Repeats a group of statements a specified number of times.
Syntax
For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next
The For…Next statement syntax has these parts:
Part
Description
counter
Numeric variable used as a loop counter. The variable can’t be an array element or an element of a user-defined type.
start
Initial value of counter.
end
Final value of counter.
step
Optional: Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements
One or more statements between For and Next that are executed the specified number of times.
DIM intNumOfTimes,intStart,intEnd AS INTEGER
DIM intIncremnt AS INTEGER
LET intStart = 1
LEt intEnd= 10
LET intIncremnt = 2
FOR intNumOfTimes = intStart TO intEnd STEP intIncremnt
Print intNumOfTimes
NEXT ntNumOfTimes
The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:
Value
Loop executes if
Positive or 0
counter <= end Negative counter >= end
Once the loop starts and all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.
Tip Changing the value of counter while inside a loop can make it more difficult to read and debug your code.
EXIT FOR
Exit For can only be used within a For Each…Next or For…Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. Exit For is often used with the evaluation of some condition (for example, If…Then), and transfers control to the statement immediately following Next.
You can nest For…Next loops by placing one For…Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:
For I = 1 To 10
For J = 1 To 10
For K = 1 To 10
. . .
Next
Next
Next
DO LOOPS
Use this loop when your are not sure how many times you want repeat something, but you do know you want to do the action(s) at least once
Use a Do loop to execute a block of statements an indefinite number of times. There are several variations of the Do…Loop statement, but each evaluates a numeric condition to determine whether to continue execution. As with If…Then, the condition must be a value or expression that evaluates to False (zero) or to True (nonzero).
DO LOOP (Pre-test)
DO WHILE condition
The condition is tested at the beginning of every loop.
Statements are repeated while the condition is true
LOOP
DO UNTIL condition
The condition is tested at the beginning of every loop.
statements repeated while the condition is false
LOOP
Dim IntCount AS INTEGER
intCount = 1
DO WHILE intCount < 10
PRINT intCount
intCount = intCount + 1
Loop
END
Try the operators <=, < , > = and <> too
Dim IntCount AS INTEGER
intCount = 1
DO UNTIL intCount >= 10
PRINT intCount
intCount = intCount + 1
LOOP
END
Try the operators <=, < , > = and <> too
DO LOOP (post-test)
This variation of the Do…Loop statement executes the statements first and then tests condition after each execution. This variation guarantees at least one execution of statements:
DO
statements repeated while the condition is true
The condition is tested at the end of every loop.
LOOP WHILE condition
DO
statements repeated while the condition is false
The condition is tested at the end of every loop.
LOOP UNTIL condition
The loop can execute any number of times, as long as condition is nonzero or True.
Dim IntCount AS INTEGER
intCount = 1
DO
PRINT intCount
intCount = intCount + 1
LOOP WHILE intCount < 10
END
Try the operators <=, < , > = and <> too
This is another variation analogous to the previous one, except that they loop as long as condition is False rather than True.
Dim IntCount AS INTEGER
intCount = 1
DO
PRINT intCount
intCount = intCount + 1
LOOP UNTIL intCount >= 10
END
‘ Try the operators <=, < , > = and <> too
Exercises 2
Modify each of the above DO LOOPS so that the Statement block within the loop does the following:
A) Problem one
Input a number
adds it to a total
when the loop finishes it prints out the total of all numbers input.
(HINT Total= Total + NumberToBeAdded)
B) Problem 2
Input a number
Multiplies the number by itself (squared)
Adds the square to a total
When the loop finishes it prints out the total of all numbers input squared.
(HINT Total= Total + NumberToBeAdded)
C) Problem 3
Modify the CASE statement menu program so that it is in a loop. Add an option so that the program quits the loop and finishes when “Q” is entered.
Example of a CGI program
This programs output is HTML, suitable for a web browser
Dim strAirport As String
Dim strTime As String
Dim strDestination As String
Cls
Do While 1 <> 2
RESTORE Start
INPUT strDestination
Print “” Print “” Print “Current flights” Print “” Print “”
READ strAirport, strTime
Do Until UCase$(strAirport) = “END”
READ strAirport, strTime
If UCase$(strAirport) = UCase$(strDestination) Then
Print ”
Airport: “; strAirport; Tab(25); ” Time:
“; Tab(45); strTime
End If
Loop
Print ”
” Print “”
Loop
End
Start: Data “Rome”, “6:00”
Data “Rome”, “7:00”
Data “Rome”, “9:00”
Data “Rome”, “11:00”
Data “Rome”, “14:00”
Data “Rome”, “19:00”
Data “Rome”, “6:00”
Data “Paris”, “7:30”
Data “Paris”, “9:30”
Data “Paris”, “11:30”
Data “Paris”, “14:20”
Data “Paris”, “19:20”
Data “END”, “”
Download it here and type in Paris, then London and finally Rome
Testing
Black box and white-box are test design methods. Black-box test design treats the system as a “black-box”, so it does not explicitly use knowledge of the internal structure. Black-box test design is usually described as focusing on testing functional requirements.
Synonyms for Black-box include: behavioural, functional, opaque-box, and Closed-box. White-box test design allows one to peek inside the “box”, and it focuses specifically on using internal knowledge of the software to guide the selection of test data.
Synonyms for white-box include: structural, glass-box and clear-box.
While black box and white-box are terms that are still in popular use, many people prefer the terms “behavioural” and “structural”. Behavioural Test design is slightly different from black-box test design because the use of internal knowledge isn’t strictly forbidden, but it’s still discouraged. In practice, it hasn’t proven useful to use a single test design method. One has to use a mixture of different methods so that they aren’t hindered by the limitations of a particular one. Some call this “grey-box” or “translucent-box” test design.
It is important to understand that these methods are used during the test design phase, and their influence is hard to see in the tests once they’re implemented. Note that any level of testing (unit testing, system testing, etc.) can use any test design methods. Unit testing is usually associated with structural test design, but this is because testers usually don’t have well-defined requirements at the unit level to validate.
Black box testing
A software testing technique whereby the internal workings of the item being tested are not known by the tester. For example, in a black box test on a software design the tester only knows the inputs and what the expected outcomes should be and not how the program arrives at those outputs. The tester does not ever examine the programming code and does not need any further knowledge of the program other than its specifications.
The advantages of this type of testing include:
The test is unbiased because the designer and the tester are independent of each other.
The tester does not need knowledge of any specific programming languages.
The test is done from the point of view of the user, not the designer.
Test cases can be designed as soon as the specifications are complete.
The disadvantages of this type of testing include:
The test can be redundant if the software designer has already run a test case.
The test cases are difficult to design.
Testing every possible input stream is unrealistic because it would take a inordinate amount of time; therefore, many program paths will go untested.
White box testing
Also known as glass box, structural, clear box and open box testing. A software testing technique whereby explicit knowledge of the internal workings of the item being tested are used to select the test data. Unlike black box testing, white box testing uses specific knowledge of programming code to examine outputs. The test is accurate only if the tester knows what the program is supposed to do. He or she can then see if the program diverges from its intended goal. White box testing does not account for errors caused by omission, and all visible code must also be readable.
For a complete software examination, both white box and black box tests are required.
Source Webopedia
Test data
Test data should include:
1) Normal data, but avoid the same number for two different input values.
2) Extreme data
a. Extra high values
b. Low values
c. Negative
d. zero
3) Abnormal
a. Numbers where text strings expected
b. Text where numbers expected
c. No entry of data where data expected.
Some examples of Loops and selections
A history database, try these programs out with the following data:
First just press return then try: hitler, nero, bodica, capt kirk, moses, noah, dracula, dumbo
Look at the each of the programs and find out what each part does.
History 1 Uses IF
History 2 Uses CASE. This has some errors for you to correct first
Histroy 3 Final Version
Exercises 3 (Session 11-12) (suitable variable names, indention and comments)
Write and test the following programs using:
“PRINT USING” to format any answer.
LOCATE to position inputs and outputs.
a) Test data and expected results for a range of test values
b) Program listing include suitable variable names, indention and comments
c) Screen shots of the test results
a) Input and adds 3 Integer numbers together
b) Input and adds 3 floating point numbers together then divides by 3
c) Input and adds 3 floating numbers together then divides by 3 and then multiplies the answer by 10.
d) Calculate the circumference of a given circle.
e) Input hours worked (floating point) and manufacturing cost per hours (floating point) to calculate the total manufacturing cost of a product
f) Input 5 numbers and display the average.
g) Input hours worked and manufacturing cost per hours to calculate the total manufacturing cost for 5 products.
h) Input length and width then calculate the area of any rectangle in metre2.
i) Input length and width then calculate the area of any two rectangle in metre2.
j) A pool consists of two rectangles in metre2. One of the rectangles is the water-covered area. The other is the full size of pool area (Including water and paved edge. Subtract the total area for the water from the full pool size to produce the paved area. Print water and paved areas out.
· Paved area = Total area – water area
Using DO LOOPS
k) A program that prints out the 3 times table using a DO LOOP
l) A program that prints out the 3 times table using a FOR NEXT LOOP
m) Enter the names mary, bill, bob, jane, gill randomly. The program should say if the name is male or female
n) A program that add a series of number and stops when a negative number is entered. The program then displays the sum of the numbers. (Needs IF and DO LOOP)
o) A program that prints out the Times Table (up to 12 numbers in a column) for any number
Now do assignment 1 Week 12
05 SIPOS Design
SIPOS is a simple design process that allows you design a simple program and produce the code automatically, while also producing the final paper-based documentation. This methodology works well for BTEC Software development courses. If you do not skip a step and throughly test each stage, you will produce a working solution much faster than just ‘messing about and dabbling.’ with making the code first that newbies normally want to do….
(Input/Output Data and calculations/processes)
Learning Objectives
At the end of this tutorial you will know about:
- Understand how to design software and use a design tool
- Be able to design and create a program
- Technical documentation: requirements specification; other as appropriate structure charts, data dictionary
1) Work out the problem’s calculation backwards
2) Put calculations into the Process Column. Make sure you arrange them this way:
Answer = Calculation
3) Check you have used brackets (BODMAS) if required, because multiply and divide is always done before add and subtract . e.g. A = 4 + 6 / 2 A = 7. A= ( 4 + 6)/2 A= 5
4) Work through the right hand side of the calculations and decide whether the variables are input, stored or a calculated output from a previous calculation.
5) Work through the input, output and stored variables and decide if they are:
INTEGER (int)- The largest integer value is 215= ±32768
LONG (lng) – The largest integer value is 231= ±2147483648
SINGLE (sng) – Single-precision floating-point variables can represent a number up to seven digits in length. The decimal point can be anywhere within those digits.
DOUBLE (dbl) – Double-precision floating-point variables can represent a number up to 15 digits in length. The decimal point can be anywhere within those digits.
Problem work out the cost of painting a ceiling
A) Work backwards from the final answer
PaintCost = Price per litre X Litres needed
Price is given, but litres needed require calculation.
Litres Needed = Tins Needed X SizeOfTin
Size of tin is given, but tins needed require calculation.
TinsNeeded = CeilingArea / CoverageOfTin
Coverage of a tin is given, but area needed require calculation.
CeilingArea = Width Of Room X Length Of Room
Both width and length will be input for each room
Place the calculation in reverse order into the SIPO table
Stored |
Input |
|
Outputs |
|
|
B) Work out for each calculation, what is output and what needs to be input or previously stored.
Work right to left
CeilingArea = WidthOfRoom * LengthOfRoom
WidthOfRoom is INPUT
LengthOfRoom is INPUT
CeilingArea is Output
TinsNeeded = CeilingArea / CoverageOfTin
CeilingArea is already available as output
CoverageOfTin is to be stored in the program
TinsNeeded is output
LitresNeeded = TinsNeeded X SizeOfTin
TinsNeeded is already available as output
SizeOfTin is to be stored in program
LitresNeeded is output
PaintCost = TinPricePerLitre * LitresNeeded
TinPricePerLitre is to be stored in the program
LitresNeeded is already available as output
PaintCost is output
Stored |
Input |
Processes |
Outputs |
CoverageOfTin TinPricePerLitre SizeOfTin
|
WidthOfRoom LengthOfRoom
|
CeilingArea = TinsNeeded = LitresNeeded = PaintCost =
|
CeilingArea TinsNeeded LitresNeeded PaintCost |
C) Design Stage Work out varable type
Stored |
Input |
Processes |
Outputs |
CoverageOfTin TinPricePerLitre SizeOfTin
|
WidthOfRoom LengthOfRoom
|
CeilingArea = TinsNeeded = LitresNeeded = PaintCost =
|
CeilingArea TinsNeeded LitresNeeded PaintCost |
D) Use the table to produce the Structure chart
E) Produce a data dictionary
The can also be used to help design the Input and output screens. Note there are no whole numers and none of them exceed 7 digits. Single precision are therefore acceptable as variables
Item | Variable Name |
|
|
sngCoverageOfTin sngPricePerLitre sngSizeOfTin sngWidthOfRoom
dblCeilingArea sngTinsNeeded sngLitresNeeded sngPaintCost |
sngCoverageOfTin sngPricePerLitre sngSizeOfTin sngWidthOfRoom
dblCeilingArea sngTinsNeeded sngLitresNeeded sngPaintCost |
|
|
F) Create the Screen Design
G: Creating the program
You can use the SIPO table to produce the program
The input, output and stored variables can be used pasted at the beginning and turned into DIM statements
DIM sngCoverageOfTin AS SINGLE
DIM dblTinPricePerLitre AS SINGLE
DIM sngSizeOfTin AS SINGLE
REM Input variables
DIM sngWidthOfRoom AS SINGLE
DIM sngLengthOfRoom AS SINGLE
REM Calculatated variables
DIM dblCeilingArea AS SINGLE
DIM sngTinsNeeded AS SINGLE
DIM sngLitresNeeded AS SINGLE
DIM sngPaintCost AS SINGLE
The add the stored values and turn them into LETS
REM Stored values
LET sngCoverageOfTin= 40
LET sngTinPricePerLitre = 5.2
LET sngSizeOfTin = 2.5
Add the INPUTS
INPUT sngWidthOfRoom
INPUT sngLengthOfRoom
Add the calculations
LET dblCeilingArea = sngWidthOfRoom * sngLengthOfRoom
LET sngTinsNeeded = dblCeilingArea / sngCoverageOfTin
LET sngLitresNeeded = sngTinsNeeded * sngSizeOfTin
LET sngPaintCost = sngPricePerLitre * sngLitresNeeded
then print the answers out using the outputsdblCeilingArea
REM Display the answers
PRINT sngTinsNeeded
PRINTsngLitresNeeded
PRINT sngPaintCost
END
Note a better way to store values that don’t change in program is to use CONST to declares symbolic constants. The following comes from the QBASIC help file.
CONST constantname = expression [
constantname: The name of the constant. This name can consist of up to 40 characters and must begin with a letter. Valid characters are A-Z, 0-9, and period (.). expression
An expression that is assigned to the constant. The expression can consist of literals (such as 1.0), other constants, any arithmetic or logical operators except exponentiation (^), or a single literal string. Place the CONST after your DIMs. It is good practice to put the DIMs/CONSTs in alphabetical order.
Example:
CONST PI = 3.141593
CONST intCoverageOfTin= 40
CONST dblTinPricePerLitre = 5.2
CONST sngSizeOfTin = 2.5
04 QBasic Tutorial Procedures
SECTION 5 – DESIGNING APPLICATIONS (Linear V Modular)
Learning Objectives
At the end of this tutorial you will know about:
- How to use functions and procedures
It is not practical in real world terms to set up an application in one long list of code. Many early programming languages were purely linear, meaning that they started from one point on a list of code, and ended at another point. However, linear programming is not practical in a team environment. If one person could write one aspect of code, and another write another part of the program, things would be much more organized. QBasic contains the capability to meet these needs, called modular programming. You can break a program into different “modules” which are separate from the main program and yet can be accessed by any part of it. I highly recommend the use of separate modules in programming applications, although it is not a simple task to learn.
Procedures & Functions
These separate modules are also known as procedures in the QBasic environment. There are two types of procedures: subs and functions. Subs merely execute a task and return to the main program, which functions execute a task and return a value to the main program. An example of a sub might be a procedure which displays a title screen on the screen, while a function may be a procedure that returns a degree in degrees given a number in radians. Function procedures are also used in Calculus, so you Calculus people should already be familiar with functions.
Arguments
Procedures can accept arguments in what is called an argument list. Each argument in the argument list has a defined type, and an object of that type must be passed to the procedure when it is called. For example, the CHR$ QBasic function accepts a numeric argument. The function itself converts this numeric argument into a string representation of the ASCII value of the number passed, and returns this one character string.
Procedures
Procedures in QBasic are given their own screen. When you enter the QBasic IDE, you are in the main procedure which can access all the others. Other procedures are created by typing the type of procedure (SUB or FUNCTION), the procedure name, followed by the complete argument list. You can view your procedures through the VIEW menu. Here is an example of a sub procedure which performs some operations for a program that will be using graphics, random numbers, and a logical plane.
SUB initProgram()
RANDOMIZE TIMER
SCREEN 12
WINDOW (0,0)-(100,100)
COLOR 15
END SUB
The only thing you need to type is SUB initProgram (), and the screen will be switched to that procedure. The END SUB is placed there for you, so the only thing you need to type then is the code within the sub. Try typing this out on your own to see how this works. This procedure is called by simply typing initProgram in the main procedure. An alternative method is CALL initProcedure (). Right here the parentheses are optional, but if you were to pass arguments to the procedure, parentheses would be required with the CALL statement. Now lets try passing an argument to a procedure. We will pass two arguments to a procedure called centre which are a string containing the text to be centreed, and the horizontal location on the screen at which you wish to centre it.
SUB centre( strText, sngHLointC )
LOCATE sngHLointC, 41 – (LEN(strText) / 2)
PRINT strText
END SUB
The first line after the sub declaration positions the starting point of the text at the horizontal location we passed at the second argument and vertical coordinate. The vertical coordinate is calculated by subtracting one half the screen’s width in characters (41) and half the LENgth of the text we passed as the first argument. We would call centre from the main procedure like this:
centre “Programmed by QP7”, 12
Or like this
CALL centre (“Programmed by QP7”, 12)
The Concrete Calculator
This program calculates the volume of a block using a procedure
Program Code – Type it in | |||
DECLARE SUB subBlock ()
DECLARE SUB subcylinder () ‘Program: Concrete Calculator ‘Author Michael Fabbro ‘Date 7 December 2003 ‘This program will work out costings for quotes Dim dblTotalVolume As Double Dim intStartLine As Integer ‘Main section intStartLine = 2 Call subBlock End
Sub subBlock() ‘Procedure to calculate volume of a block Dim sngHeight, sngWidth, sngLength As Single Dim dblVolume As Double Color 10, 1 Cls LOCATE 2, 25: Print “Concrete Calculator” LOCATE intStartLine + 5, 5: Print “Height” LOCATE intStartLine + 7, 5: Print “Width” LOCATE intStartLine + 9, 5: Print “Length” LOCATE intStartLine + 15, 15: Print “Volume” LOCATE intStartLine + 5, 12: INPUT ” “, sngHeight LOCATE intStartLine + 7, 12: INPUT ” “, sngWidth LOCATE intStartLine + 9, 12: INPUT ” “, sngLength ‘Calculate Volume dblVolume = sngHeight * sngWidth * sngLength LOCATE intStartLine + 15, 24: Print USING “#####.##”; dblVolume; End Sub
Results |
The full program in modular form can be found here. A menu using procedures is used and INKEY$ which reads a character from the keyboard.
IN KEY$
■ INKEY$ returns a null string if there is no character to return
■ For standard keys, INKEY$ returns a 1-byte string containing the character read.
■ For extended keys, INKEY$ returns a 2-byte string made up of the character (ASCII 0) and the keyboard scan code.
Example:
PRINT “Press Esc to exit…”
DO
LOOP UNTIL INKEY$ = CHR$(27) ’27 is the ASCII code for Esc.
Keycodes
Key Code ║ Key Code ║ Key Code c 1 ║ A 30 ║ Caps Lock 58 ! or 1 2 ║ S 31 ║ F1 59 @ or 2 3 ║ D 32 ║ F2 60 # or 3 4 ║ F 33 ║ F3 61 $ or 4 5 ║ G 34 ║ F4 62 % or 5 6 ║ H 35 ║ F5 63 ^ or 6 7 ║ J 36 ║ F6 64 & or 7 8 ║ K 37 ║ F7 65 * or 8 9 ║ L 38 ║ F8 66 ( or 9 10 ║ : or ; 39 ║ F9 67 ) or 0 11 ║ " or ' 40 ║ F10 12 ║ ~ or ` 41 ║ F11 133 + or = 13 ║ Left Shift 42 ║ F12 134 Bksp 14 ║ | or \ 43 ║ NumLock 69 Tab 15 ║ Z 44 ║ Scroll Lock 70 Q 16 ║ X 45 ║ Home or 7 71
This is the full program
DECLARE SUB subBlock ()
DECLARE SUB subCylinder ()
‘Program: Concrete Calculator
‘Author Michael Fabbro
‘Date 7 December 2003
‘This program will work out costings for quotes
‘Glossary of Variables
‘intStartLine – start position of the inputscrenn
‘dblTotalVolume – running total of volume
‘Global Scope Variables
Dim dblTotalVolume As Double
Dim intStartLine As Integer
‘Local Variables
Dim strCommand As String
‘Main section
‘initialise variables
dblTotalVolume = 0
‘Set up input screen
intStartLine = 2
Color 10, 1
DO
CLS
LOCATE 2, 25: Print “Concrete Calc Main Menu”
LOCATE intStartLine + 6, 15: Print “[B]lock”
LOCATE intStartLine + 8, 15: Print “[C]ylinder”
LOCATE intStartLine + 10, 15: Print “[R]set Total”
LOCATE intStartLine + 12, 15: Print “[Q]uit”
LOCATE intStartLine + 14, 15: Print “Enter B,C,R,Q”
strCommand = “”
‘scan for menu choice
Do While strCommand = “”
‘note strCommand= ucase$(inkey$) is a better solution
strCommand = INKEY$
Loop
‘note strCommand= ucase$(inkey$) above is a better solution
‘convert to uppercase
strCommand = UCase$(strCommand)
Select Case strCommand
Case Is = “B”
Call subBlock
Case Is = “C”
Call subCylinder
Case Is = “R”
dblTotalVolume = 0
Case Is = “Q”
END
END SELECT
LOOP WHILE strCommand <> “Q”
Sub subBlock()
‘Procedure to calculate volume of a block
‘ Alphabetical Glossary of Local Variables
‘ sngJunk – used for pausing screen
‘sngLength – Length of Cylinder
‘sngWidth – Width of Block
‘sngHeight – height of block
‘dblVolume – Calulated Volume of Cylinder
‘Declare Local Variables
Dim sngRadius, sngWidth, sngLength As Single
Dim dblVolume As Double
Dim strJunk As String
‘input screen
Color 10, 1
Cls
LOCATE 2, 25: Print “Concrete Calculator”
LOCATE intStartLine + 5, 5: Print “Height”
LOCATE intStartLine + 7, 5: Print “Width”
LOCATE intStartLine + 9, 5: Print “Length”
LOCATE intStartLine + 15, 15: Print “Volume”
LOCATE intStartLine + 5, 12: INPUT ” “, sngHeight
LOCATE intStartLine + 7, 12: INPUT ” “, sngWidth
LOCATE intStartLine + 9, 12: INPUT ” “, sngLength
‘Calculate Volume and output
dblVolume = sngHeight * sngWidth * sngLength
dblTotalVolume = dblTotalVolume + dblVolume
LOCATE intStartLine + 15, 24: Print USING “#####.##”; dblVolume;
Print ” Cubic Metres”
LOCATE intStartLine + 17, 24: Print “Total so far: “;
Print USING “#####.##”; dblTotalVolume;
Print ” Cubic Metres”
LOCATE intStartLine + 19, 24: INPUT “Press enter to continue”; strJunk
End Sub
Sub subCylinder()
‘Subroutine to calulate volume of a concrete cylinder
‘Alphabetical Glossary of Local Variables
‘sngJunk – used for pausing screen
‘sngLength – Length of Cylinder
‘sngRadius – Radius of Cylinder
‘dblVolume – Calulated Volume of Cylinder
‘Declare Local Variables
Dim strJunk As String
Dim sngLength, sngRadius As Integer
Dim dblVolume As Integer
Const conPi = 3.142
‘Procedure to calculate volume of a cylinder
Color 10, 1
CLS
LOCATE 2, 25: Print “Concrete Calculator”
LOCATE intStartLine + 5, 5: Print “Radius”
LOCATE intStartLine + 7, 5: Print “Length”
LOCATE intStartLine + 15, 15: Print “Volume”
LOCATE intStartLine + 5, 12: INPUT ” “, sngRadius
LOCATE intStartLine + 7, 12: INPUT ” “, sngLength
‘Calculate Volume
dblVolume = conPi * sngRadius ^ 2 * sngLength
dblTotalVolume = dblTotalVolume + dblVolume
LOCATE intStartLine + 15, 24: Print USING “#####.##”; dblVolume;
Print ” Cubic Metres”
LOCATE intStartLine + 17, 24: Print “Total so far: “;
Print USING “#####.##”; dblTotalVolume;
Print ” Cubic Metres”
LOCATE intStartLine + 19, 24: INPUT “Press enter to continue”; strJunk
End Sub
Advanced Example
There is one final concept which has proven to be very successful in programming: a message loop. With QBasic, you can construct a loop which runs for the length of the program, receives input from the user, and executes a message based on what the user does. We will construct a basic application which receives input from the user in the form of an arrow key, and moves a box on the screen based on the direction the user pressed. The arrow keys are different from normal inputted keys received with INKEY$.
On the enhanced 101 keyboards which have arrow keys, INKEY$ returns two values: the ASCII text representation of the key pressed, and the keyboard scan code of the key pressed. Since the arrow keys do not have an ASCII text representation, we must use the keyboard scan codes for them. The keyboard scan codes can be viewed in the HELP | CONTENTS section of the QBasic menus. For this program, we will have two procedures in addition to the main procedure. The first will initialize the program settings and position the character in his starting position. The other will move the guy in the direction which we pass to the function. The main procedure will call the sub procedures and contains the main message loop which retrieves input from the user. First of all, here is the code for the main procedure:
CONST UP = 1
CONST DOWN = 2
CONST LEFT = 3
CONST RIGHT = 4
TYPE objectType
intX AS INTEGER
intY AS INTEGER
END TYPE
DIM object AS objectType
initScreen
object.x = 41
object.y = 24
DO
SELECT CASE INKEY$
CASE CHR$(0) + CHR$(72)
move UP, object
CASE CHR$(0) + CHR$(80)
move DOWN, object
CASE CHR$(0) + CHR$(75)
move LEFT, object
CASE CHR$(0) + CHR$(77)
move RIGHT, object
CASE CHR$(32)
EXIT DO
END SELECT
LOOP
LOCATE 1,1: PRINT “Thank you for playing”
END
This code is fairly self explanatory with the exception of the SELECT CASE… END SELECT structure which I have not yet explained. This type of conditional testing format tests a condition, and several cases for that condition are then tested. In this case, we are seeing IF INKEY$ = CHR$(0) + CHR$(72), IF INKEY$ = CHR$(0) + CHR$(80), and so on. This is just a more legible format than IF…THEN…ELSE. Note that in the QuickBasic compiler, a CASE ELSE statement is required in the structure for what reason
I have no idea. The above code is the driver for the rest of the program. First some CONSTants are declared which remain constant for the duration of the program and in any module. A user defined type is declared to store the coordinates of the character.
Then an endless loop is executed, calling the appropriate procedure for the arrow key pressed until the user presses the space bar (CHR$(32)). Here is the code for the initScreen procedure:
SUB initScreen ()
SCREEN 12
COLOR 9
WIDTH 80,50
LOCATE 24,41
PRINT CHR$(1)
END SUB
The WIDTH 80,50 statement sets the screen text resolution to 80 columns and 50 rows. We then print a smiley face in the middle of the screen in a nice bright blue colour. Next we need to write the move procedure, and then we will be done with the program.
SUB move (way AS INTEGER, object AS objectType)
LOCATE object.y, object.x
PRINT CHR$(0) ‘ erase previous image
SELECT CASE way
CASE UP
IF object.y > 1 THEN
object.y = object.y – 1
END IF
CASE DOWN
IF object.y < 49 THEN
object.y = object.y + 1
END IF
CASE LEFT
IF object.x > 1 THEN
object.x = object.x – 1
END IF
CASE RIGHT
IF object.x < 79 THEN
object.x = object.x + 1
END IF
END SELECT
LOCATE object.y, object.x
PRINT CHR$(1) ‘ draw current image
END SUB
And that’s the whole program… confusing as it may be! Ideas should be going through your head about what you could do with this information. Entire games can be created with this simple construct.
There are more things to consider, but they are beyond the scope of this tutorial. If you were to design an application in QBasic, you would only need the information from this section and imagination. Programming takes knowledge of the language and a creative mind… programs are made by programmers with both. If you can develop a creative mind, then you can develop any program conceivable.
Validation Checking for Errors
This program checks the input of hours worked for erroneous data, i.e. working for more than 60 hours.
‘ Program to validate inputs ‘ Author Michael J Fabbro ‘ Date 16 December 2003 Dim sngHoursWorked As Integer Const cntRed = 12 Const cntBlue = 9 Const cntYellow = 14 Color cntYellow, cntBlue Cls Do LOCATE 5, 5: Print “Hours Worked: “; INPUT ” “, sngHoursWorked If sngHoursWorked >= 60 Then ‘ invalid hours input Color , cntRed LOCATE 7, 5: Print “Warning ‘con’ in progress” Do Loop While INKEY$ = “” Color cntYellow, cntBlue Cls End If Loop While sngHoursWorked >= 60 |
||
This is a final example of Validation
‘ Program to validate inputs ‘ Author Michael J Fabbro ‘ Date 16 December 2003 Dim strTitle As String ‘ Modification of valid titles? Const strValidTitles = “Mr:Mrs:Ms:Master” Const cntRed = 12 Const cntBlue = 9 Const cntYellow = 14 Color cntYellow, cntBlue CLS DO LOCATE 5, 5: Print “Title: “; INPUT ” “, strTitle Select Case strTitle Case Is = “Mr” LOCATE 7, 5: Print “Male title known” Case Is = “Mrs” LOCATE 7, 5: Print “Female title known” Case Is = “Ms” LOCATE 7, 5: Print “Female title known” Case Else ‘ invalid title Color , cntRed LOCATE 7, 5: Print “Title not known” Do Loop While INKEY$ = “” Color cntYellow, cntBlue Cls End Select Loop Until strTitle = “Mr” Or strTitle = “Ms” Or strTitle = “Mrs” |
|
02 Tutorial – Software Development Basic QBasic
INTRODUCTION Session 1
Learning Objectives
At the end of this tutorial you will know about:
- The basic nature and features of a procedural programming language
- Variables – naming conventions and data types: text; integer; floating point; byte; date; Boolean. The benefits of appropriate choice of data type eg additional validation and efficiency of storage
- How and when to use assignment statements; input statements; output statements
SECTION 1 – VARIABLES
A variable, simply defined, is a name which can contain a value. Programming involves giving values to these names and presenting them in some form to the user. A variable has a type which is defined by the kind of value it holds. If the variable holds a number, it may be of integer, floating decimal, long integer, or imaginary. If the variable holds symbols or text, it may be a character variable or a string variable. These are terms you will become accustomed to as you continue programming.
Here are some examples of values a variable might contain:
- STRING “hello, this is a string”
- INTEGER 5
- LONG 92883
- SINGLE 39.2932
- DOUBLE 98334288.18
- INTEGER A 16-bit signed integer variable.
- LONG 32-bit signed integer variable.
- SINGLE single-precision 32-bit floating-point variable.
- DOUBLE double-precision 64-bit floating-point variable.
- STRING * n% fixed-length string variable n% bytes long.
- STRING variable-length string variable.
- INTEGER (int)- The largest integer value is 215= ± 32768. The smallest is 1, if you exclude zero.
- LONG (lnt) – The largest integer value is 231= ±2147483648. The smallest is 1, if you exclude zero.
- SINGLE (sng) – Single-precision floating-point variables can represent a number up to seven digits in length. The decimal point can be anywhere within those digits. The largest number is 9,999,999 the smallest is .0000001 if you exclude zero.
- DOUBLE (dbl) – Double-precision floating-point variables can represent a number up to 15 digits in length. The decimal point can be anywhere within those digits. The largest number is 99,999,999,999,999,999 the smallest is .000000000000001 if you exclude zero.
Variable types support by C++
Name | Description | Size* | Range* |
---|---|---|---|
char | Character or small integer. | 1byte | signed: -128 to 127 unsigned: 0 to 255 |
short int (short) | Short Integer. | 2bytes | signed: -32768 to 32767 unsigned: 0 to 65535 |
int | Integer. | 4bytes | signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 |
long int (long) | Long integer. | 4bytes | signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 |
bool | Boolean value. It can take one of two values: true or false. | 1byte | true or false |
float | Floating point number. | 4bytes | +/- 3.4e +/- 38 (~7 digits) |
double | Double precision floating point number. | 8bytes | +/- 1.7e +/- 308 (~15 digits) |
long double | Long double precision floating point number. | 8bytes | +/- 1.7e +/- 308 (~15 digits) |
wchar_t | Wide character. | 2 or 4 bytes | 1 wide character |
Declaration of variables
In order to use a variable in BASIC we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float…) followed by a valid variable identifier. For example:
DIM intNumber AS INTEGER
Remember the largest integer value you can store in here is is 215= ± 32768. The smallest is 1, if you exclude zero. It will use up two bytes of RAM in the memory used by the program. It uses two bytes to store number
DIM lngNumber AS LONG
The largest integer value is now 231= ±2147483648. The smallest is 1, if you exclude zero. LONG uses four bytes to store a number.
Note
You choose which on the basis of speed and ram usage.
Think
This is done by using the DIM statement. Say you wanted to make a variable called intNumber which would contain an integer (whole number, no digits after the decimal point).
Then you would use that variable as an integer. The word DIM actually originates from the word Dimension, but you won’t see why until we discuss the topic of arrays.
SECTION 2 – INTERACTING WITH THE COMPUTER
You know what a variable is and how to control them, it’s time you learned some programming. QBasic (like all other languages) is set up using pre-defined statements according to the syntax specified for that statement. It may be helpful to look in the help index to learn a statement, although I’ve heard many complaint’s that the help index is too hard. Indeed it is too hard for new programmers, but as you learn more and more statements and their syntaxes, you’ll become accustomed to the index and use it as a casual reference. Lets make a program that prints some text on the screen. Type qbasic at the DOS prompt and enter the following program.
Program Code – Type it in | |||||
CLSPRINT “This text will appear on the screen”
END
|
|||||
Typing
QBasic allows to you define the ‘type’ of variable as number or characters like C++. It also allows loose typing, i.e where context tells you the type of data stored. Below is show how variables can be ‘typed,’ for loose typing all you need to do is give a variable a value:
name$ =” fred
age=3
pay = 3.45
This means spelling errors in variable names can cause problems. JavaScript is prone to this. QBasic provides good practice in dealing with this problem.
COLOUR
Below are the 16 colours QBASIC uses –
00 = black01 = dark blue
02 = dark green 03 = dark cyan 04 = dark red 05 = dark purple 06 = orange brown 07 = gray |
08 = dark gray09 = light blue
10 = light green 11 = light cyan 12 = light red 13 = magenta 14 = yellow 15 = bright white |
CLS
COLOR 12 PRINT “I’m light red text!” COLOR 14 PRINT “I’m yellow text!” END |
Sets the screen display colours.
COLOR [foreground%] [,[background%] [,border%]] Screen mode 0 (text only)
COLOR [background%] [,palette%] Screen mode 1
COLOR [foreground%] Screen modes 4, 12, 13
COLOR [foreground%] [,background&] Screen modes 7-10
foreground% A number that sets the foreground screen colour.
background% A number that sets the background screen colour.
border% A colour attribute that sets the screen border colour.
palette% A number (0 or 1) that specifies which of two sets of colour attributes to use:
The available colour attributes and values depend on your graphics adapter and the screen mode set by the most recent SCREEN statement
LET and INPUT
You have learned how to use the PRINT and CLS commands. In this chapter, you will learn about variables and the INPUT command.
What are variables? Variables are “boxes” in the computer’s memory to store a value – be it a number, name, decimal, currency amount, or what have you. There are two main types of variables – numbers and “strings,” which are text variables.
The “numbers” category is further broken down into two areas.
Integer Numbers
Integers, they can be in the range of -32767 to 32767.
Long integers, they have a range of -2 billion to 2 billion. “Why not make all numbers long integers?” The memory of the computer, especially in QBasic, is limited – you should save as much space as possible. Only use long integers where they are necessary.
Floating-point” numbers.
These are decimal variables that can have very long decimal spaces.
Single types
Double types
You still may be in the dark as to how variables are used.
Variables are assigned a value using the LET command. For example:
LET intNumber = 123
This would assign a value of 123 to the short integer variable ” intNumber.” You can use maths functions while assigning variables, too. “LET intNumber = 4 * 12″ would make ” intNumber ” equal 48. You can increment variables like this:
LET intNumber = intNumber + 1
Or, you can make it ” intNumber = intNumber + 2, intNumber = number – 1,” and so on. You can also add two variables together using the same syntax, or sequence of commands. You need a way to output these variables to the screen if you want them to have any meaning to the user of the program.
You can use the PRINT command for this task easily:
PRINT intNumber
This would output to the screen the value assigned to “intNumber.” If you want to include text before the number, you must use this format:
Dim IntNumber AS INTEGER CLS LET intNumber = 100 PRINT “The number is”; intNumber END |
This would output, when run:
The number is 100
“How do I ask the user for something?”
Like strings, You do this by using the INPUT command. :
DIM IntNumber AS INTEGER
CLS INPUT intNumber PRINT “The number is”; intNumber END |
This would give the user a prompt for a short integer to assign to “number” and then print it out. You can also supply a prompt for INPUT to use – like this:
DIM IntNumber AS INTEGER
CLS INPUT “Enter a Number”; intNumber PRINT “You typed “; intNumber; “.” END |
Exercise 1
Write a program to input the user’s name (STRING) and age (INTEGER) and output them using the PRINT command.
The first statement — CLS — stands for “clear screen.” It erases whatever was on the screen before it was executed. PRINT simply displays its argument to the screen at the current text cursor location. The argument in this case is the text enclosed in quotes. PRINT displays text within quotes directly, or it can display the value of a variable, like this:
Program Code – Type it in | |||||
DIM intA, intB AS INTEGERCLS
LET intA = 50 LET intB = 100 PRINT “The value of a is “; intA; ” and the value of b is “; intB END
|
|||||
This will yield the output; The value of a is 50 and the value of b is 100. The semicolons indicate that the next time something is printed, it will be right after where the last PRINT statement left off. Remember that PRINT prints literally what is inside quotes, and the value of the variable which is not in quotes. intA and intB are integers containing values in this example, and their values are printed using the PRINT statement.
Say you want to interact with the user now. You’ll need to learn a statement called INPUT. INPUT displays a prompt (the first argument) and assigns what the user types in to a variable (the second argument)
Program Code – Type it in | |||||
DIM strName as StringDIM intAge as Integer
CLS INPUT “What is your name? “, strName INPUT “How old are you? “, intAge PRINT “So, “; strName; “, you are “; intAge; ” years old. That’s interesting.” END
|
|||||
Test 1Test 2 |
This firsts asks the user for their name and assigns it to the string variable strName. Then the age is requested, and the result is printed in a sentence. Try it out! So what happens if you input I DON’T KNOW for the age prompt? You’ll get a weird message that says REDO FROM START. Why? The program is trying to assign a string (text) to an integer (number) type, and this makes no sense so the user is asked to do it over again.
Another cornerstone of programming is the conditional test. Basically, the program tests if a condition is true, and if it is, it does something. It looks like English so it’s not as hard as it sounds.
DIM intSelection as INTEGER
CLS PRINT “1. Say hello” ‘ option 1 PRINT “2. Say nice tie” ‘ option 2 PRINT “Enter your selection ” INPUT intSelection IF intSelection = 1 THEN PRINT “hello” ENDIF IF intSelection = 2 THEN PRINT “nice tie” ENDIF END |
The user is given a set of options, and then they input a value which is assigned to the variable selection%. The value of selection% is then tested, and code is executed based on the value. If the user pressed 1, it prints hello, but if they pressed 2, it prints nice tie. Also notice the text after the ‘ in the code. These are remark statements. Anything printed after a ‘ on a line does not affect the outcome of the program. Back to the actual code — but what if the user doesn’t input 1 or 2? What if they input 328? This must be taken into account as part of programming. You usually can’t assume that the user has half a brain, so if they do something wrong, you can’t screw up the program. So the ELSE statement comes into play. The logic goes like this:
IF the condition is true, THEN do something, but if the condition is anything ELSE, then do something else. The ELSE statement is used with IF…THEN to test if a condition is anything else.
DIM intNumber as INTEGERCLS
INPUT “Press 1 if you want some pizza.”, intNumber IF intNumber = 1 THEN PRINT “Here’s your pizza” ELSE PRINT “You don’t get pizza” ENDIF END |
Revision Session 2
Solving simple mathematical problems is one of the easiest tasks that you could do in BASIC. If you are more keen at writing a game or making graphics, you will have to be patient.:) We’ll deal about that later.
Before proceeding, you’ll have to understand some Basic concepts:
What is a program?
A program is a set of instructions that makes the computer work.
In most programs you will have to write you will have to think as follows:
What data do I need to give to the computer?
What operations will the computer have to perform with the data given?
What results will the program display
There are three parts in every task that we accomplish
Input | –> | Process | –> | Output |
Input: What is needed
Process: What you need to do, calculate with the input
Output: The result obtained when the process has been done
Before beginning to code your program, it is important to write algorithms or pseudo codes in plain English that will outline what you want to do.
Algorithms
An algorithm is a set of precise instructions for solving a problem. Algorithms can be represented in plain English or in form of flowcharts
Here’s a simple algorithm for calculating the sum of 2 numbers
Get the first numberGet the second number
Calculate the sum Display the sum |
Let’s illustrate this concept using some mathematical examples:
We’ll be using colours to differentiate between the Input, Process and Output parts of the algorithm and program code.
|
You will have noticed that this program is not very explicit. The following code makes the presentation more understandable:
|
The use of semi-colons in the PRINT statement tells BASIC to keep the cursor on the same line.
Enhancing Program Presentation
It’s important for you to enhance you program by:
- Documenting your program
- Using meaningful variables
- Saying what is the purpose of the program
- Documenting your program
As you will notice later, programs may become huge, thus difficult to understand. The REM statement allows you to put remarks in your program. Any line starting with the REM statement is ignored at run-time. You can replace the REM statement by a single-quote ( ‘ ) symbol.
The two lines below are similar:
REM Program written by H.B.
‘ Program written by H.B.
The single-quote form of REM can also be placed at the end of a line
PRINT “Welcome everybody” ‘Welcome message
Using meaningful variables
The use single-letter variables may be easy to type especially if your typewriting speed is slow. However they may cause your program to be difficult to understand in the long-run. The use of meaningful variables makes your program easier to understand and maintain. Here is an illustration:
ix = 2000y = 10
z = x * (100 + y)/100 |
Could you guess the code above? Now see how it is easy when meaningful variables are used:
LET intOldSalary = 2000LET intPercentageIncrease = 10
LET sngNewSalary = intOldSalary * (100 + intPercentageIncrease )/100 |
Saying what is the purpose of the program Many novice programmers learning how to program, often neglect to say what is the purpose of their program. Example of an undocumented program:
LET a = 20LET b = 30
LET c = a * b PRINT “The product is “; c |
As we said above, use the REM statement to put remarks, use meaningful variables and, at run-time, say what your program is doing.
REM This program calculates the product of 2 numbers: 20 and 30. LET intnumber1 = 20LET intNumber2 = 30LET intProduct = intNumber1 * intNumber2PRINT “This program calculates the product of 2 numbers”PRINT “The first number is”; intNmber1PRINT “The second number is”; intNumber2PRINT “The product is “; intProduct |
Getting user input at run-time
Two commands or functions that allow you to get user input at run-time are:
The INPUT statement
The INKEY$ function
The INPUT statement
INPUT [variable] |
Example:
|
The lines:
PRINT “Enter your name:”;
INPUT strYourname
can also be written as:
INPUT “Enter your name:”; strYourname
Personally I prefer to use the first option because it is easier to understand and because it is the standard procedure in most programming languages.
|
Program Code – Type it in | |||||||||||||
DIM sngPi, sngRadius, sngArea as SINGLECLS
LET sngPi = 3.1415 INPUT “What is the radius of the circle? “, sngRadius LET sngArea = sngPi * sngRadius ^ 2 PRINT “The area of the circle is “, sngArea END
|
First, we’re defining the variable pi. It’s a single number, which means that it can be a fairly large number with some decimal places. The exclamation mark tells QBasic that sngPi is of the single type. Next, the user is prompted for the radius of their circle. Then the area is calculated. The * means “times,” and the ^ (carrot) means “to the power of.” sngRadius ^ 2 means “radius squared.” This could also be written as:
sngPi! * sngRadius * sngRadius.
Worked Examples
IPO TABLE For Block problem
Input | Process | Output |
Height (H) | Calculate volume by multiplying H X W X L | Volume |
Width (W) | ||
Length (L) | ||
Input controls/Variables | Calculations | Output Controls/variables |
sngHeight | dblVolume = sngHeight * sngWidth * sngLength | dblVolume |
sngWidth | ||
sngLength |
Structure Chart For Block problem
Program Code – Type it in | |||
‘Program: Concrete Calculator’Author Michael Fabbro
‘Date 7 December 2003 ‘This program will work out costings for quotes DIM sngPi, sngRadius, sngArea as SINGLE Dim sngHeight, sngWidth, sngLength As Single Dim dblVolume As Double Dim intStartLine As Integer ‘Main section ‘Set up input screen intStartLine = 2 Color 10, 1 Cls LOCATE 2, 25: Print “Concrete Calculator” LOCATE intStartLine + 5, 5: Print “Height” LOCATE intStartLine + 7, 5: Print “Width” LOCATE intStartLine + 9, 5: Print “Length” LOCATE intStartLine + 15, 15: Print “Volume” LOCATE intStartLine + 5, 12: INPUT ” “, sngHeight LOCATE intStartLine + 7, 12: INPUT ” “, sngWidth LOCATE intStartLine + 9, 12: INPUT ” “, sngLength ‘Calculate Volume dblVolume = sngHeight * sngWidth * sngLength LOCATE intStartLine + 15, 24: Print USING “#####.##”; dblVolume; END
Expected Results |
Exercises
- Create the test data and state the output the program should produce for the problems below.
- At least five different tests for each.
- Write the QBASIC code to solve the problem – USE MEANINGFUL VARIABLE NAMES AND COMMENTS.
- Print out copies of the program and the test results, keep them in a safe place as they are to be handed in.
- Add two numbers input from the keyboard together and output the answer.
- Subtract two numbers input from the keyboard together and output the answer.
- Divide two numbers input from the keyboard together and output the answer.
- Add three numbers input from the keyboard together and then divide the sum by 3.Output the answer to this calculation as the average. (Do the problem as two separate calculations not one)
- Rewrite exercise using just one calculation.
- Input the cost of an item and add 30% of its cost as profit to give the retail price. Output the retail price.
Print Using revisited
PRINT [#filenumber%,] USING formatstring$; expressionlist [{; | ,}]
LPRINT USING formatstring$; expressionlist [{; | ,}]
The PRINT with no arguments prints a blanks line so we can separate our answers.
Say you want to print something in a certain pre-defined format. Say you want to print a series of digits with only 2 places after the decimal point and a dollar sign before the first digit. To do this requires the PRINT USING statement, which is very handy in applications for businesses. The PRINT USING statement accepts two types of arguments. The first is a string which has already been defined. This is a special type of string, in that it contains format specifiers, which specify the format of the variables passed as the other arguments. Confused? You won’t be. Here’s a quick list of the most common format specifiers:
### digits
& Prints an entire string
\ \ Prints a string fit within the backslashes. Any thing longer is truncated
$$ Puts a dollar sign to the left of a number
. Prints a decimal point
, Prints a comma every third digit to the left of the decimal point.
- And these can be combined in a format string to make a user defined way to print something.
- So $$#,###.## will print a number with a dollar sign to the left of it. If the number has more than two decimal places, it is truncated to two. If it is more than four digits long to the left of the decimal place, it is also truncated to fit.
- To use a PRINT USING statement, you must first define the format string containing the format specifiers. Then you use PRINT USING, then the name of the format string, and variable values to fill the places defined in the format string.
Here’s a code example:
DIM intA AS INTEGERDIM strA AS STRING
intA = 123.4567 PRINT USING “###.##”; intA PRINT USING “+###.####”; intA strA = “ABCDEFG” PRINT USING “!”; strA PRINT USING “\ \”; strA |
||||||
Program Code – Type it in | ||||||
DIM strItemName AS STRINGDIM strFormat AS STRING
DIM intNumItems AS INTEGER DIM sngItemCost, sngTotalCost AS SINGLE CLS ‘ get user input INPUT “Enter item name: “, strItemName INPUT “How many items?: “, intNumItems INPUT “What does one cost?: “, sngItemCost CLS ‘ display inputs strFormat = “\ \ #,### $$#,###.## $$#,###,###.##” PRINT “Item Name Quantity Cost Total Cost ” PRINT “————– ——– ———- ————–” sngTotalCost = intNumItems * sngItemCost PRINT USING strFormat; strItemName ; intNumItems ; sngItemCost; sngTotalCost END
|
||||||
First, we get the item name, number of items, and cost per item from the user. Then we clear the screen and define the format string to be used. It contains a static length string (text that will be truncated if it is too long), up to 4 digits for the quantity, 4 digits and two decimals for the item cost, and 7 digits and two decimals for the total cost. Then we print out some column headers so we know what each value will represent, and some nice lines to go under the column headers. Then the total cost is calculated by multiplying the number of items by the item cost. Finally, the four variable’s values are displayed under the column headers using the PRINT USING statement.
Volume of a Cylinder
Volume of a cylinder is the area of the a circle making up the clynder times the height of the cylinder.
Area = pi X radius X radius
Volume = Area X height
Or
Volume = pi X radius X radius X height
Or
Volume = pi X radius2 X height
IPO TABLE For Cylinder problem
Input | Process | Output |
Radius (R) | Calculate volume by multiplying pi * radius * radius * Length | Volume |
Length (L) | ||
Input controls/Variables | Calculations | Output Controls/variables |
sngHeight | dblVolume = 3.142 * sngRadius * sngRadius * sngLength | dblVolume |
sngRadius |
Structure Chart For Cylinder problem
A Data Dictionary
Variable Name | Description/Use | Type | Picture |
sngHeight | Height of Cylinder | Single | 9999.99 |
sngRadius | Radius of Cylinder | Single | 9999.99 |
dblVolume | Volumeof Cylinder | Double | 999999.99 |
Program Code – Type it in | |||||||||||||||||||||||||||
‘Program: Concrete Calculator’Author Michael Fabbro
‘Date 7 December 2003 ‘This program will work out costings for quotes Dim sngLength, sngRadius As SINGLE Dim dblVolume, As DOUBLE Dim intStartLine AS INTEGER Const conPi = 3.142 ‘Procedure to calculate volume of a cylinder Color 10, 1 CLS ‘draw input screen LOCATE 2, 25: Print “Concrete Calculator” LOCATE intStartLine + 5, 5: Print “Radius” LOCATE intStartLine + 7, 5: Print “Length” LOCATE intStartLine + 15, 15: Print “Volume” LOCATE intStartLine + 5, 12: INPUT ” “, sngRadius LOCATE intStartLine + 7, 12: INPUT ” “, sngLength ‘Calculate Volume LET dblVolume = conPi * sngRadius ^ 2 * sngLength LOCATE intStartLine + 15, 24: Print USING “#####.##”; dblVolume; END
|
Enter the following programs and test they are working correctly
Exercise 3
Payroll Problem
Write an IPO table to process payroll. To calculate Pay multiply hours work time rate of pay.
Input | Process | Output |
Input controls/Variables | Calculations | Output Controls/variables |
Now draw a Sructure Chart for the problem
Program Code – Type it in | |||
‘Program: Payroll program’Author Michael Fabbro
‘Date 7 December 2003
DIM sngRate, shgHours,sngWage AS SINGLE DIM strName As STRING DIM intPayNum, intStartLine As Integer ‘Main section ‘Set up input screen intStartLine = 2 Color 10, 1 CLS LOCATE 2, 25: Print “Concrete Calculator” LOCATE intStartLine + 5, 5: Print “Name” LOCATE intStartLine + 7, 5: Print “Payroll Number” LOCATE intStartLine + 9, 5: Print “Pay Rate” LOCATE intStartLine + 15, 15: Print “Hours” LOCATE intStartLine + 5, 12: INPUT ” “, strName LOCATE intStartLine + 7, 12: INPUT ” “, intPAyNum LOCATE intStartLine + 9, 12: INPUT ” “, sngRate LOCATE intStartLine + 11, 12: INPUT ” “, sngHours ‘Calculate Volume LET sngWage = sngHours * sngRate LOCATE intStartLine + 15, 24: Print USING “#####.##”; sngPay; END
Expected Results |
Enter the following programs and test they are working correctly using the supplied test data. Note some of these programs may not be working correctly. If the program is not working properly state on the listing you produced what was wrong with it and what you did to correct it.
Exercise 4
Using this sheet annotate the listing below describing what each line does.
‘Program: Payroll program
‘Author Michael Fabbro
‘Date 7 December 2003
DIM sngRate, shgHours,sngWage AS SINGLE
DIM strName As STRING
DIM intPayNum, intStartLine As Integer
‘Main section
‘Set up input screen
intStartLine = 2
Color 10, 1
CLS
LOCATE 2, 25: Print “Concrete Calculator”
LOCATE intStartLine + 5, 5: Print “Name”
LOCATE intStartLine + 7, 5: Print “Payroll Number”
LOCATE intStartLine + 9, 5: Print “Pay Rate”
LOCATE intStartLine + 15, 15: Print “Hours”
LOCATE intStartLine + 5, 12: INPUT ” “, strName
LOCATE intStartLine + 7, 12: INPUT ” “, intPAyNum
LOCATE intStartLine + 9, 12: INPUT ” “, sngRate
‘Calculate Volume
sngWage = sngHours * sngRate
LOCATE intStartLine + 15, 24: Print USING “#####.##”; sngPay;
END
Glossary of Basic found in this Chapter.
Writes data to the screen or to a file. LPRINT prints data on the printer LPT1.
Print [#filenumber%,]; [expressionlist]; [{; | ,}]
LPRINT [expressionlist] [{; | ,}]
filenumber% The number of an open file. If you don’t specify a file number, PRINT writes to the screen.
expressionlist A list of one or more numeric or string expressions to print.
{; | ,} Determines where the next output begins:
; means print immediately after the last value.
, means print at the start of the next print zone.
Print zones are 14 characters wide.
See Also PRINT USING, LPRINT USING, WIDTH, WRITE
TAB
Moves the text cursor to a specified print position.
TAB(column%)
column% The column number of the new print position.
Example:
Print Tab(25); “Text”
SPC
Skips a specified number of spaces in a PRINT or LPRINT statement.
SPC(n%)
n% The number of spaces to skip; a value in the range
o through 32, 767#
Example: Print “Text1”; Spc(10); “Text2”
CLS
Clears the screen.
Cls [{0 | 1 | 2}]
CLS Clears either the text or graphics viewport. If a graphics viewport has been set using VIEW), clears only the graphics viewport. Otherwise, clears the text viewport or entire screen.
CLS 0 Clears the screen of all text and graphics.
CLS 1 Clears the graphics viewport or the entire screen if no graphics viewport has been set.
CLS 2 Clears the text viewport.
See Also VIEW VIEW PRINT WINDOW
REM
Allows explanatory remarks to be inserted in a program.
Rem remark
‘ remark
remark Any text.
Remarks are ignored when the program runs unless they contain
metacommands. A remark can be inserted on a line after an executable statement if it is preceded by the single-quote (‘) form of REM or if REM is preceded by a colon (:).
Example:
Rem This is a comment.
‘ This is also a comment.
Print “Test1” ‘This is a comment after a PRINT statement.
Print “Test2”: Rem This is also a comment after a PRINT statement.
LET
Assigns the value of an expression to a variable.
[LET] variable=expression
■ variable Any variable. Variable names can consist of up to 40 characters and must begin with a letter. Valid characters are A-Z, 0-9, and period (.).
■ expression Any expression that provides a value to assign.
■ Use of the optional LET keyword is not recommended. The
variable=expression assignment statement performs the same action
with or without LET.
LOCATE
Moves the cursor to a specified position on the screen.
CSRLIN returns the current row position of the cursor.
POS returns the current column position of the cursor.
LOCATE [row%] [,[column%] [,[cursor%] [,start% [,stop%]]]]
CSRLIN
POS(expression)
■ row% and column% The number of the row and column to which the
cursor moves.
■ cursor% Specifies whether the cursor is visible:
0 = invisible, 1 = visible
■ start% and stop% Integer expressions in the range 0 through 31
that specify the first and last cursor scan lines.
You can change the cursor size by changing the
cursor scan lines.
■ expression Any expression.
Task – Data Types | |
Task 1 Data types include string/ text; integer; floating point; byte; date; Boolean other eg long, double single. Using examples from Microsoft Qbasic and other languages, describe the benefits of the appropriate choice of data types available to the programmer, eg additional validation, efficiency of storage, strong typing. Task 2 Write the following program for a mail order company. Input the purchase cost of an item add 30% to give the retail then add a delivery charge of 10% of the retail cost. Ensure your programs are documented with comments. You should submit
a) Structure chart b) Test data and the results expected c) A listing of the program’s code with comments d) A screen grab of you program’s results with the test data. e) A Data dictionary of variables.
|
01 Introduction to Software Design using QBASIC
There are six sections to this tutorial:
- Introduction
- Basics ‘Basic’
- Decisions and Loops
- Procedures
- The SIPOS Way
Introduction to Software Design using QBASIC
QBasic is a programming language designed for DOS (disk operating system) and is a very good language to learn and then migrate to modern day languages like VBA, VBSCRIPT, ASP, Visual Basic, C++, javascript and Java. You will learn to deal with more code, commands, and complex routines. Once you have learnt these basics, it easier to learn other more modern languages. You will find (QBasic.exe and QBasic.hlp) on DOS disks and Windows 98-95 CDs.
Typing
QBasic allows to you define the ‘type’ of variable as number or characters like C++. It also allows loose typing, i.e where context tells you the type of data stored. Below is show how variables can be ‘typed,’ for loose typing all you need to do is give a variable a value:
name$ =” fred
age=3
pay = 3.45
This means spelling errors in variable names can cause problems. JavaScript is prone to this. QBasic provides good practice in dealing with this problem.
Warning
The tutorial can be used in standalone mode, but is designed to complement classroom teaching. Do not switch off and think you can do this course all by yourself at the last minute.
Navigation
You can navigate the tutorial using the menu shown below. You can see it in the banner above.
Learning Objectives
At the end of this tutorial you will know about:
- The basic nature and features of a procedural programming language
- Variables – naming conventions and data types: text; integer; floating point; byte; date; Boolean. The benefits of appropriate choice of data type eg additional validation and efficiency of storage
- How and when to use assignment statements; input statements; output statements
- How to use Loops eg conditional (pre-check, post-check), fixed to repeat actions
- How to use conditional statements and logical operators to make decisions
- How and when to use assignment statements; input statements; output statements
- How to use functions and procedures
- Understand how to design software and use design tools
- Understand the software development life cycle
- Be able to design and create a program
- Technical documentation: requirements specification; other as appropriate to
structure charts, data dictionary - Be able to document, test, debug and review a programmed solution
- Testing and debugging: test strategy; test plan structure eg test, date, expected
result, actual resultUser documentation: eg details of hardware platform required, loading instructions, user guide; getting help