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

PRINT

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

PRINT

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