Unit 20 · Programming · 49 min read
Computer Programming using QBASIC
What the syllabus asks for 7
- QBASIC: features and the QBASIC screen
- Character set, constants, variables and operators
- Statements: CLS, REM, LET, INPUT, PRINT and END
- Library functions: mathematical and string functions
- Selection: IF...THEN...ELSE and SELECT CASE
- Loops: FOR...NEXT, WHILE...WEND and DO...LOOP
- Writing, running and debugging simple programs
In Lesson 18 you planned solutions as algorithms and flowcharts, and in Lesson 19 you met the languages that turn plans into programs. Now you will write real programs in QBASIC: programs that read data from the keyboard, calculate, decide and repeat, and print their results on the screen. QBASIC is small, forgiving and almost plain English, which makes it an ideal first language. Every program in this lesson was run in two modern QBASIC-compatible systems, FreeBASIC 1.10 (fbc -lang qb) and QB64-PE 4.7, and the output shown under each program is exactly what appeared on the screen. Type them in, run them, and then change them: that is how programming is learnt.
Expect definitions and features (QBASIC, the parts of its screen, character set, constants, variables, operators, library functions), the syntax and use of statements (CLS, REM, LET, INPUT, PRINT, END, IF … THEN … ELSE, SELECT CASE, FOR … NEXT, WHILE … WEND, DO … LOOP), QBASIC expressions from algebra, the output of a short program or of a library function (LEN, LEFT$, MID$, INT, MOD), debugging (find and correct the errors) and, above all, writing complete programs. A 4-mark program is marked by its parts: CLS and REM, correct input with a prompt, the correct calculation or condition or loop, correct output, and END.
20.1 QBASIC: features and the QBASIC screen
QBASIC (Quick Beginner's All-purpose Symbolic Instruction Code) is a high-level programming language and its programming environment, made by Microsoft and supplied with MS-DOS 5.0 in 1991. It grew out of BASIC, which John Kemeny and Thomas Kurtz created at Dartmouth College in 1964. QBASIC programs are run by an interpreter, one statement at a time.
Features of QBASIC
- Easy to learn. Its keywords are plain English words —
PRINT,INPUT,IF,THEN,FOR,NEXT. - Interpreter. A program runs at once, without a separate compiling step, and stops at the first error with a message, so mistakes are easy to find.
- A smart editor. When you finish typing a line, QBASIC checks its syntax, changes keywords to capital letters and points out mistakes straight away.
- Structured programming. It has block IF, SELECT CASE, several kinds of loop, and SUB and FUNCTION procedures, so a program can be divided into clear parts. Line numbers are not needed.
- Many library functions for mathematics, text, date and time.
- Graphics and sound statements (such as
CIRCLE,LINE,SOUNDandPLAY) for drawing and music. - Built-in help. Pressing F1 on a keyword shows its syntax and an example.
- Programs are saved as plain text files with the extension .BAS.
QBASIC was written for MS-DOS and does not run directly on 64-bit Windows. In computer labs today it is usually run in a DOS emulator such as DOSBox, or replaced by QB64, a free program that looks and works like QBASIC and runs the same programs on Windows, Linux and macOS.
The QBASIC screen
When QBASIC starts, a welcome box appears; press Esc to clear it. The screen then has these parts.

| Key | What it does |
|---|---|
| Shift + F5 | runs the program from the beginning (Run → Start) |
| F5 | continues a program that has paused (Run → Continue) |
| F4 | shows the output screen; any key returns to the program |
| F6 | moves the cursor between the program window and the Immediate window |
| F8 | runs the program one line at a time (Debug → Step) |
| F9 | sets or removes a breakpoint on the current line |
| F1 | help on the keyword under the cursor |
| Alt | selects the menu bar |
| Esc | closes a menu or a dialog box |

20.2 Character set, constants, variables and operators
Character set
The character set of QBASIC is the set of characters from which every statement is built.
| Group | Characters |
|---|---|
| Letters | A to Z and a to z |
| Digits | 0 to 9 |
| Special characters | + - * / \ ^ = < > ( ) . , ; : ' " $ % & ! # ? and the space |
Words with a fixed meaning in QBASIC, such as PRINT, INPUT, IF, FOR and END, are called keywords or reserved words. They cannot be used as variable names.
Constants and variables
Lesson 19 defined constants, variables and data types. In QBASIC:
- A numeric constant is written without commas or currency signs:
25000, not25,000orRs 25000. Very large or small numbers may use E notation:1.5E+6means 1,500,000. - A string constant is written between double quotes:
"Pokhara","98". - A symbolic constant is made with
CONST:CONST PI = 3.14gives the name PI to 3.14, and the program cannot change it later. - A numeric variable holds a number (
A,TOTAL,AGE%); a string variable holds text and ends in$(N$,ADDRESS$). A variable's type can also be declared in words:DIM AGE AS INTEGER,DIM NM AS STRING.
Operators
An operator is a symbol or word that tells the computer to do something with values (its operands). An expression combines constants, variables and operators into one value.
| Arithmetic operator | Meaning | Example | Result |
|---|---|---|---|
^ |
exponent (power) | 2 ^ 5 |
32 |
* |
multiplication | 6 * 7 |
42 |
/ |
division | 17 / 5 |
3.4 |
\ |
integer division (the whole-number part of the quotient) | 17 \ 5 |
3 |
MOD |
remainder after division | 17 MOD 5 |
2 |
+ |
addition | 17 + 5 |
22 |
- |
subtraction, or a negative sign | 17 - 5 |
12 |
Relational (comparison) operators compare two values and give true or false. QBASIC stores true as −1 and false as 0.
| Relational operator | Meaning | Example | Result |
|---|---|---|---|
= |
equal to | 5 = 5 |
true (−1) |
<> |
not equal to | 5 <> 5 |
false (0) |
> |
greater than | 5 > 3 |
true |
< |
less than | 5 < 3 |
false |
>= |
greater than or equal to | 7 >= 7 |
true |
<= |
less than or equal to | 8 <= 7 |
false |
Logical operators join conditions. AND is true only when both conditions are true; OR is true when at least one is true; NOT turns true into false and false into true. So (5 > 3) AND (2 > 4) is false, (5 > 3) OR (2 > 4) is true and NOT (5 > 3) is false.
| A | B | A AND B | A OR B | NOT A |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
The string operator + joins (concatenates) strings: "Kath" + "mandu" gives "Kathmandu".
Hierarchy of operations
When an expression has several operators, QBASIC works them out in this order (the hierarchy, or precedence); operators of the same level are done from left to right.
| Order | Operation |
|---|---|
| 1 | brackets ( ), innermost first |
| 2 | exponent ^ |
| 3 | negative sign - |
| 4 | multiplication * and division / |
| 5 | integer division \ |
| 6 | MOD |
| 7 | addition + and subtraction - |
| 8 | relational operators = <> < > <= >= |
| 9 | NOT, then AND, then OR |
Problem. (a) Find the value of 10 + 8 / 2 ^ 2 * 3. (b) Write QBASIC expressions for \frac{a+b}{c}, a^2 + 2ab and \sqrt{a^2 + b^2}, and find their values when a = 3, b = 4 and c = 5.
Solution. (a) Exponent first: 2 ^ 2 = 4. Then division and multiplication from left to right: 8 / 4 = 2 and 2 * 3 = 6. Last, addition: 10 + 6 = 16.
(b)
| Algebra | QBASIC expression | Value for A = 3, B = 4, C = 5 |
|---|---|---|
| \frac{a+b}{c} | (A + B) / C |
7 / 5 = 1.4 |
| a^2 + 2ab | A ^ 2 + 2 * A * B |
9 + 24 = 33 |
| \sqrt{a^2 + b^2} | SQR(A ^ 2 + B ^ 2) |
√25 = 5 |
QBASIC printed exactly these values, 1.4 33 5, when the three expressions were run. In algebra ab means a × b, but in QBASIC the * must always be written: 2AB is an error, 2 * A * B is correct.
20.3 Statements: CLS, REM, LET, INPUT, PRINT and END
A statement is one complete instruction. Each line of a QBASIC program usually holds one statement; two short statements may share a line if they are separated by a colon (:).
| Statement | Purpose | Syntax | Example |
|---|---|---|---|
CLS |
clears the output screen | CLS |
CLS |
REM |
writes a remark (comment) for people; it is not carried out | REM remark or ' remark |
REM Area of a circle |
LET |
stores the value of an expression in a variable (assignment); the word LET may be left out | [LET] variable = expression |
LET S = A + B |
INPUT |
waits for the user to type values and stores them in variables | INPUT ["prompt";] variable list |
INPUT "Your age"; A |
PRINT |
displays values, text and results on the screen | PRINT [list] |
PRINT "Sum ="; S |
END |
ends the program | END |
END |
INPUT prints its prompt and waits. If a semicolon follows the prompt, QBASIC adds a question mark and a space (Your age?); with a comma it adds nothing (Your age: is shown exactly as typed). Several variables can be read at once — INPUT "Two numbers: ", A, B — and the user then types the values separated by commas, such as 20, 8. Type numbers without commas or units: typed as 25,000, the number is read as two values, and QBASIC asks again with "Redo from start".
PRINT displays each item of its list. A semicolon prints the next item right after the last one; a comma moves to the next print zone (the screen is divided into zones of 14 columns, starting at columns 1, 15, 29, 43 and 57); TAB(n) moves to column n; and PRINT alone prints a blank line. A semicolon at the very end of a PRINT keeps the next output on the same line. QBASIC prints every number with a space in front (where a minus sign would go) and a space after it, so PRINT "Sum ="; 28 shows Sum = 28.
Problem. Write a program that displays the name and address of a school, a blank line, and the class.
Solution.
CLS
REM Program 20.1: my first program
PRINT "Shree Janata Secondary School"
PRINT "Biratnagar-7, Morang"
PRINT
PRINT "Class 8 Computer Science"
END
Shree Janata Secondary School
Biratnagar-7, Morang
Class 8 Computer Science
The REM line does not appear in the output: it is a note for people reading the program.
Problem. Show the effect of ;, , and TAB in PRINT statements.
Solution.
CLS
REM Program 20.2: semicolon, comma and TAB
PRINT "Name"; "Marks"
PRINT "Name", "Marks"
PRINT "Asha", 87
PRINT "Bikash", 92
PRINT "Roll"; TAB(10); "Name"; TAB(25); "Marks"
PRINT 1; TAB(10); "Asha"; TAB(25); 87
END
NameMarks
Name Marks
Asha 87
Bikash 92
Roll Name Marks
1 Asha 87
The semicolon joined "Name" and "Marks" with no space. The comma started "Marks" at column 15; the numbers 87 and 92 begin at column 15 too, but their first character is the space for the sign. TAB lines up the columns of a table.
Problem. Read two numbers and display their sum, difference, product and quotient.
Solution.
CLS
REM Program 20.3: four operations on two numbers
INPUT "Enter the first number"; A
INPUT "Enter the second number"; B
LET S = A + B
LET D = A - B
LET P = A * B
LET Q = A / B
PRINT "Sum ="; S
PRINT "Difference ="; D
PRINT "Product ="; P
PRINT "Quotient ="; Q
END
Enter the first number? 20
Enter the second number? 8
Sum = 28
Difference = 12
Product = 160
Quotient = 2.5
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print("Sum =", a + b)
print("Difference =", a - b)
print("Product =", a * b)
print("Quotient =", a / b)
Enter the first number: 20
Enter the second number: 8
Sum = 28
Difference = 12
Product = 160
Quotient = 2.5
Python's input() always gives text, so int() turns it into a whole number; QBASIC's INPUT does this by itself for a numeric variable.
Problem. Read the principal, time and rate, and display the simple interest and the amount. (This is the algorithm of Worked example 18.3, now coded.)
Solution.
CLS
REM Program 20.4: simple interest
INPUT "Principal (Rs)"; P
INPUT "Time (years)"; T
INPUT "Rate (% per year)"; R
SI = P * T * R / 100
A = P + SI
PRINT "Simple interest = Rs"; SI
PRINT "Amount = Rs"; A
END
Principal (Rs)? 25000
Time (years)? 3
Rate (% per year)? 9.5
Simple interest = Rs 7125
Amount = Rs 32125
Check: 25,000 × 3 × 9.5 ÷ 100 = 7,125 and 25,000 + 7,125 = 32,125 ✓.
Problem. Convert a temperature from degrees Celsius to degrees Fahrenheit using F = C × 9 ÷ 5 + 32.
Solution.
CLS
REM Program 20.5: Celsius to Fahrenheit
INPUT "Temperature in Celsius: ", C
F = C * 9 / 5 + 32
PRINT C; "degrees Celsius ="; F; "degrees Fahrenheit"
END
Temperature in Celsius: 37
37 degrees Celsius = 98.6 degrees Fahrenheit
The prompt ends with a comma, so no question mark appears. The output line starts with a space because it begins with a number.
Problem. Read the radius of a circle and display its area (πr²) and circumference (2πr), taking π = 3.14.
Solution.
CLS
REM Program 20.6: area and circumference of a circle
CONST PI = 3.14
INPUT "Radius of the circle (cm)"; R
A = PI * R ^ 2
C = 2 * PI * R
PRINT "Area ="; A; "sq. cm"
PRINT "Circumference ="; C; "cm"
END
Radius of the circle (cm)? 7
Area = 153.86 sq. cm
Circumference = 43.96 cm
(1) A prompt or text without its closing quote. (2) A missing *: 2 * PI * R, never 2PIR. (3) A variable name that changes spelling in the middle of a program — TOTAL and TOTL are two different variables, and the misspelt one is 0. (4) INPUT A, B but only one value typed. (5) Forgetting CLS and END in an exam answer: the program may still run, but each carries a mark.
20.4 Library functions: mathematical and string functions
A library function (built-in function) is a ready-made routine supplied with QBASIC that takes one or more values, called arguments, and gives back (returns) one result. A function is always used inside an expression or a statement, never alone: PRINT SQR(16) or R = SQR(X). Functions whose names end in $ return strings.
Mathematical functions
| Function | Returns | Example | Result |
|---|---|---|---|
SQR(x) |
square root of x (x must not be negative) | SQR(144) |
12 |
ABS(x) |
absolute value (the number without its sign) | ABS(-25) |
25 |
INT(x) |
the largest whole number not greater than x | INT(7.8), INT(-7.8) |
7, −8 |
FIX(x) |
x with its decimal part removed | FIX(7.8), FIX(-7.8) |
7, −7 |
CINT(x) |
x rounded to the nearest whole number | CINT(7.8), CINT(-7.3) |
8, −7 |
SGN(x) |
1 if x is positive, −1 if negative, 0 if zero | SGN(-9) |
−1 |
SIN(x), COS(x), TAN(x) |
sine, cosine, tangent of x in radians | COS(0) |
1 |
LOG(x), EXP(x) |
natural logarithm, and e to the power x | EXP(0) |
1 |
RND |
a random number from 0 up to (not including) 1 | INT(RND * 6) + 1 |
a dice throw, 1 to 6 |
Problem. Display the values of several mathematical functions.
Solution.
CLS
REM Program 20.7: mathematical functions
PRINT "SQR(144) ="; SQR(144)
PRINT "ABS(-25) ="; ABS(-25)
PRINT "INT(7.8) ="; INT(7.8); " INT(-7.8) ="; INT(-7.8)
PRINT "FIX(7.8) ="; FIX(7.8); " FIX(-7.8) ="; FIX(-7.8)
PRINT "CINT(7.8) ="; CINT(7.8); " CINT(-7.3) ="; CINT(-7.3)
PRINT "SGN(-9) ="; SGN(-9); " SGN(0) ="; SGN(0)
PRINT "17 MOD 5 ="; 17 MOD 5; " 2 ^ 10 ="; 2 ^ 10
END
SQR(144) = 12
ABS(-25) = 25
INT(7.8) = 7 INT(-7.8) =-8
FIX(7.8) = 7 FIX(-7.8) =-7
CINT(7.8) = 8 CINT(-7.3) =-7
SGN(-9) =-1 SGN(0) = 0
17 MOD 5 = 2 2 ^ 10 = 1024
A negative number is printed with its minus sign in the place where a positive number has its leading space, which is why "=-8" has no gap.
For 7.8 both give 7. For −7.8, FIX simply cuts off the decimals and gives −7, while INT goes down to the next whole number, −8, because −8 is less than −7.8. Students who learn "INT removes the decimal part" lose this mark every year.
String functions
| Function | Returns | Example (W$ = "Kathmandu") |
Result |
|---|---|---|---|
LEN(s$) |
the number of characters | LEN(W$) |
9 |
LEFT$(s$, n) |
the first n characters | LEFT$(W$, 4) |
Kath |
RIGHT$(s$, n) |
the last n characters | RIGHT$(W$, 5) |
mandu |
MID$(s$, p, n) |
n characters starting at position p | MID$(W$, 3, 4) |
thma |
UCASE$(s$) |
the string in capital letters | UCASE$(W$) |
KATHMANDU |
LCASE$(s$) |
the string in small letters | LCASE$("NEPAL") |
nepal |
LTRIM$(s$), RTRIM$(s$) |
the string without spaces on the left or right | LTRIM$(" Nepal") |
Nepal |
ASC(s$) |
the ASCII code of the first character | ASC("A") |
65 |
CHR$(n) |
the character whose ASCII code is n | CHR$(66) |
B |
STR$(n) |
a number turned into a string (with a leading space if positive) | STR$(45) |
" 45" |
VAL(s$) |
a string of digits turned into a number | VAL("12.5") |
12.5 |
INSTR(s$, t$) |
the position where t$ first appears in s$ (0 if not found) |
INSTR(W$, "man") |
5 |
SPACE$(n), STRING$(n, c$) |
n spaces; n copies of a character | STRING$(5, "*") |
* |
DATE$, TIME$ |
today's date (mm-dd-yyyy) and the time (hh:mm:ss) from the computer's clock | PRINT DATE$ |
the date |
Problem. Display the results of the main string functions on the word "Kathmandu".
Solution.
CLS
REM Program 20.8: string functions
W$ = "Kathmandu"
PRINT LEN(W$)
PRINT LEFT$(W$, 4)
PRINT RIGHT$(W$, 5)
PRINT MID$(W$, 3, 4)
PRINT UCASE$(W$); " "; LCASE$(W$)
PRINT ASC("A"); CHR$(66)
PRINT "["; STR$(45); "]"; VAL("12.5") + 1
PRINT "["; LTRIM$(" Nepal"); "]"; INSTR(W$, "man")
END
9
Kath
mandu
thma
KATHMANDU kathmandu
65 B
[ 45] 13.5
[Nepal] 5
The square brackets show where each string starts and ends: STR$(45) keeps the leading space of a positive number, and LTRIM$ removed the three spaces before "Nepal".
20.5 Selection: IF...THEN...ELSE and SELECT CASE
Selection lets a program choose what to do, as the diamond does in a flowchart (Lesson 18).
Single-line IF. The whole decision is written on one line:
IF condition THEN statement
IF condition THEN statement1 ELSE statement2
For example, IF M >= 35 THEN PRINT "Pass" ELSE PRINT "Fail".
Block IF. When each branch needs several statements, or there are more than two choices, use the block form. It must end with END IF.
IF condition1 THEN
statements done when condition1 is true
ELSEIF condition2 THEN
statements done when condition2 is true
ELSE
statements done when no condition is true
END IF
The conditions are tested from the top, and only the first true branch is carried out. ELSEIF and ELSE parts may be left out. An IF inside another IF is a nested IF.
Problem. Read a whole number and say whether it is odd or even.
Solution. A number is even when the remainder after dividing by 2 is 0.
CLS
REM Program 20.9: odd or even
INPUT "Enter a whole number"; N
IF N MOD 2 = 0 THEN
PRINT N; "is an even number."
ELSE
PRINT N; "is an odd number."
END IF
END
Two runs:
Enter a whole number? 46
46 is an even number.
Enter a whole number? -7
-7 is an odd number.
Problem. Read three numbers and display the greatest.
Solution. AND joins two conditions; >= handles equal numbers.
CLS
REM Program 20.10: the greatest of three numbers
INPUT "Enter three numbers: ", A, B, C
IF A >= B AND A >= C THEN
G = A
ELSEIF B >= A AND B >= C THEN
G = B
ELSE
G = C
END IF
PRINT "The greatest number is"; G
END
Enter three numbers: 45, 72, 68
The greatest number is 72
To test "A is greater than both", students write IF A > B > C. QBASIC first works out A > B as −1 or 0 and then compares that number with C, so the answer is nonsense. Join two complete conditions with AND: IF A > B AND A > C THEN.
SELECT CASE
When one value is compared with many possibilities, SELECT CASE is neater than a long chain of ELSEIFs.
SELECT CASE expression
CASE value list
statements
CASE value1 TO value2
statements
CASE IS relational-operator value
statements
CASE ELSE
statements
END SELECT
A CASE can list several values separated by commas (CASE 1, 3, 5), a range (CASE 40 TO 49), or a comparison (CASE IS >= 90). As with block IF, only the first matching CASE is carried out; CASE ELSE catches everything else.
Problem. Read a percentage and display the letter grade of the SEE grading system: A+ (90 and above), A (80 to below 90), B+ (70–80), B (60–70), C+ (50–60), C (40–50), D (35–40) and NG (below 35).
Solution. The cases are checked from the top, so CASE IS >= 80 is reached only by marks below 90.
CLS
REM Program 20.11: SEE grade from percentage
INPUT "Enter the percentage"; P
SELECT CASE P
CASE IS > 100, IS < 0
G$ = "not a valid percentage"
CASE IS >= 90
G$ = "A+"
CASE IS >= 80
G$ = "A"
CASE IS >= 70
G$ = "B+"
CASE IS >= 60
G$ = "B"
CASE IS >= 50
G$ = "C+"
CASE IS >= 40
G$ = "C"
CASE IS >= 35
G$ = "D"
CASE ELSE
G$ = "NG"
END SELECT
PRINT "Grade: "; G$
END
Three runs:
Enter the percentage? 86.5
Grade: A
Enter the percentage? 33
Grade: NG
Enter the percentage? 105
Grade: not a valid percentage
Python has no SELECT CASE in the grade 9 course; an if … elif … else chain does the same job.
p = float(input("Enter the percentage: "))
if p > 100 or p < 0:
g = "not a valid percentage"
elif p >= 90:
g = "A+"
elif p >= 80:
g = "A"
elif p >= 70:
g = "B+"
elif p >= 60:
g = "B"
elif p >= 50:
g = "C+"
elif p >= 40:
g = "C"
elif p >= 35:
g = "D"
else:
g = "NG"
print("Grade:", g)
Enter the percentage: 86.5
Grade: A
Problem. Read a number from 1 to 7 and display the day of the week, Sunday being day 1.
Solution.
CLS
REM Program 20.12: day of the week
INPUT "Enter a day number (1 to 7)"; D
SELECT CASE D
CASE 1
PRINT "Sunday"
CASE 2
PRINT "Monday"
CASE 3
PRINT "Tuesday"
CASE 4
PRINT "Wednesday"
CASE 5
PRINT "Thursday"
CASE 6
PRINT "Friday"
CASE 7
PRINT "Saturday - the weekly holiday in Nepal"
CASE ELSE
PRINT "There is no day number"; D
END SELECT
END
Two runs:
Enter a day number (1 to 7)? 7
Saturday - the weekly holiday in Nepal
Enter a day number (1 to 7)? 9
There is no day number 9
Problem. Read a letter and say whether it is a vowel or a consonant.
Solution. UCASE$ turns a small letter into a capital, so only capitals need to be listed. A string range such as "B" TO "Z" follows alphabetical order.
CLS
REM Program 20.13: vowel or consonant
INPUT "Enter a letter"; L$
L$ = UCASE$(L$)
SELECT CASE L$
CASE "A", "E", "I", "O", "U"
PRINT L$; " is a vowel."
CASE "B" TO "Z"
PRINT L$; " is a consonant."
CASE ELSE
PRINT "That is not a letter."
END SELECT
END
Three runs, with e, k and 7:
Enter a letter? e
E is a vowel.
Enter a letter? k
K is a consonant.
Enter a letter? 7
That is not a letter.
| Point | IF … THEN … ELSE | SELECT CASE |
|---|---|---|
| Tests | any conditions, possibly on different variables | one expression against many values |
| Joins conditions with AND, OR | yes | no (but a CASE may list several values) |
| Ranges | written as M >= 40 AND M < 50 |
written as CASE 40 TO 49 or CASE IS >= 40 |
| Best for | two or three choices, or mixed conditions | many choices on one value: grades, menus, days |
| Ends with | END IF (block form) |
END SELECT |
20.6 Loops: FOR...NEXT, WHILE...WEND and DO...LOOP
A loop repeats a block of statements. QBASIC has three kinds.
FOR … NEXT repeats a fixed number of times, using a counter variable:
FOR counter = start TO end [STEP increment]
statements
NEXT counter
The counter starts at start, goes up by the STEP (1 if STEP is left out) after each pass, and the loop stops when the counter passes end. A negative STEP counts down. The number of passes is (end − start) ÷ step + 1, ignoring any fraction: FOR I = 1 TO 10 STEP 3 runs for I = 1, 4, 7 and 10, which is (10 − 1) ÷ 3 + 1 = 4 times.
WHILE … WEND repeats as long as a condition is true. The condition is tested before each pass, so if it is false at the start, the loop does not run at all.
WHILE condition
statements
WEND
DO … LOOP is the most flexible. The test can be at the top (WHILE or UNTIL after DO) or at the bottom (after LOOP); WHILE means "repeat while true", UNTIL means "repeat until true". A loop with its test at the bottom always runs at least once.
DO WHILE condition DO
statements statements
LOOP LOOP UNTIL condition
| Point | FOR … NEXT | WHILE … WEND / DO WHILE … LOOP | DO … LOOP UNTIL |
|---|---|---|---|
| Use when | the number of passes is known | the loop goes on while a condition holds | the body must run at least once |
| Where the test is | at the top (the counter is compared with the end value) | at the top | at the bottom |
| Fewest passes | 0 | 0 | 1 |
| Counter changed by | NEXT, automatically | a statement you write in the body | a statement you write in the body |
Problem. Display the multiplication table of a number.
Solution.
CLS
REM Program 20.14: multiplication table
INPUT "Enter a number"; N
FOR I = 1 TO 10
PRINT N; "x"; I; "="; N * I
NEXT I
END
Enter a number? 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
range(1, 11) produces 1 to 10: the end value 11 is not included.
n = int(input("Enter a number: "))
for i in range(1, 11):
print(n, "x", i, "=", n * i)
Enter a number: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Problem. Display the even numbers from 2 to 20 and their sum, then count down from 10 to 1.
Solution.
CLS
REM Program 20.15: counting with STEP
PRINT "Even numbers from 2 to 20:"
S = 0
FOR I = 2 TO 20 STEP 2
PRINT I;
S = S + I
NEXT I
PRINT
PRINT "Their sum ="; S
PRINT "Countdown:"
FOR I = 10 TO 1 STEP -1
PRINT I;
NEXT I
PRINT
PRINT "Blast off!"
END
Even numbers from 2 to 20:
2 4 6 8 10 12 14 16 18 20
Their sum = 110
Countdown:
10 9 8 7 6 5 4 3 2 1
Blast off!
The semicolon after PRINT I keeps the numbers on one line; the empty PRINT after the loop ends that line.
FOR I = 10 TO 1 without STEP -1 does not count down: the start is already past the end, so the loop body is skipped completely and nothing is printed. When FreeBASIC and QB64 ran such a loop, its body was carried out 0 times.
Problem. Find the factorial of a number, N! = 1 × 2 × … × N.
Solution. F starts at 1 (not 0), because it is a product.
CLS
REM Program 20.16: factorial of a number
INPUT "Enter a number"; N
F = 1
FOR I = 1 TO N
F = F * I
NEXT I
PRINT "Factorial of"; N; "is"; F
END
Enter a number? 6
Factorial of 6 is 720
Problem. Read a positive whole number. Find the sum of its digits and the number reversed, and say whether it is a palindrome (the same when reversed).
Solution. N MOD 10 gives the last digit and N \ 10 removes it; the loop goes on while digits are left. The original number is kept in M, because N is used up by the loop.
CLS
REM Program 20.17: sum of digits, reverse and palindrome
INPUT "Enter a positive whole number"; N
M = N
S = 0
R = 0
WHILE N > 0
D = N MOD 10
S = S + D
R = R * 10 + D
N = N \ 10
WEND
PRINT "Sum of the digits ="; S
PRINT "Reversed number ="; R
IF R = M THEN PRINT M; "is a palindrome." ELSE PRINT M; "is not a palindrome."
END
Two runs:
Enter a positive whole number? 4521
Sum of the digits = 12
Reversed number = 1254
4521 is not a palindrome.
Enter a positive whole number? 12321
Sum of the digits = 9
Reversed number = 12321
12321 is a palindrome.
Trace for 4521: digits 1, 2, 5, 4 come off one by one; S goes 1, 3, 8, 12; R goes 1, 12, 125, 1254; N goes 452, 45, 4, 0 and the loop stops.
Python writes MOD as % and integer division as //.
n = int(input("Enter a positive whole number: "))
m = n
s = 0
r = 0
while n > 0:
d = n % 10
s = s + d
r = r * 10 + d
n = n // 10
print("Sum of the digits =", s)
print("Reversed number =", r)
if r == m:
print(m, "is a palindrome.")
else:
print(m, "is not a palindrome.")
Enter a positive whole number: 4521
Sum of the digits = 12
Reversed number = 1254
4521 is not a palindrome.
Problem. Display the Fibonacci numbers (0, 1, 1, 2, 3, 5, …, each the sum of the two before it) that are less than a given limit.
Solution.
CLS
REM Program 20.18: Fibonacci series below a limit
INPUT "Show the Fibonacci numbers below"; L
A = 0
B = 1
DO WHILE A < L
PRINT A;
C = A + B
A = B
B = C
LOOP
PRINT
END
Show the Fibonacci numbers below? 100
0 1 1 2 3 5 8 13 21 34 55 89
The number of terms is not known in advance, so a FOR loop does not fit; the loop runs while A is still below the limit.
Problem. Keep reading numbers until the user types 0, then display how many numbers were entered and their total.
Solution. The body must run at least once — a number has to be read before it can be tested — so the test goes at the bottom.
CLS
REM Program 20.19: add numbers until 0 is entered
T = 0
C = 0
DO
INPUT "Enter a number (0 to stop)"; N
T = T + N
IF N <> 0 THEN C = C + 1
LOOP UNTIL N = 0
PRINT "You entered"; C; "numbers."
PRINT "Their total is"; T
END
Enter a number (0 to stop)? 25
Enter a number (0 to stop)? 40
Enter a number (0 to stop)? 15
Enter a number (0 to stop)? 0
You entered 3 numbers.
Their total is 80
Python has no DO … LOOP UNTIL. A while True loop with break does the same: the test sits after the input.
total = 0
count = 0
while True:
n = float(input("Enter a number (0 to stop): "))
if n == 0:
break
total = total + n
count = count + 1
print("You entered", count, "numbers.")
print("Their total is", total)
Enter a number (0 to stop): 25
Enter a number (0 to stop): 40
Enter a number (0 to stop): 15
Enter a number (0 to stop): 0
You entered 3 numbers.
Their total is 80.0
Problem. Display the pattern 1 / 1 2 / 1 2 3 / 1 2 3 4 / 1 2 3 4 5, one row per line.
Solution. The outer loop counts the rows (I = 1 to 5); the inner loop prints the numbers 1 to I on that row.
CLS
REM Program 20.20: a number triangle (nested loops)
FOR I = 1 TO 5
FOR J = 1 TO I
PRINT J;
NEXT J
PRINT
NEXT I
END
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
The inner loop must be completely inside the outer one: NEXT J comes before NEXT I.
Problem. Read a word, display it reversed, count its vowels, and say if it is a palindrome.
Solution. The loop runs backwards over the positions of the word, from LEN(W$) down to 1, taking one character at a time with MID$. INSTR checks whether that character appears in the list of vowels.
CLS
REM Program 20.21: reverse a word and count its vowels
INPUT "Enter a word"; W$
R$ = ""
V = 0
FOR I = LEN(W$) TO 1 STEP -1
CH$ = MID$(W$, I, 1)
R$ = R$ + CH$
IF INSTR("AEIOUaeiou", CH$) > 0 THEN V = V + 1
NEXT I
PRINT "Reversed: "; R$
PRINT "Number of vowels:"; V
IF UCASE$(R$) = UCASE$(W$) THEN PRINT W$; " is a palindrome."
END
Two runs:
Enter a word? Nepal
Reversed: lapeN
Number of vowels: 2
Enter a word? Malayalam
Reversed: malayalaM
Number of vowels: 4
Malayalam is a palindrome.
w[::-1] reverses a string in one step, and in tests whether a character is in a string.
w = input("Enter a word: ")
r = w[::-1]
v = 0
for ch in w:
if ch in "AEIOUaeiou":
v = v + 1
print("Reversed:", r)
print("Number of vowels:", v)
if r.upper() == w.upper():
print(w, "is a palindrome.")
Enter a word: Malayalam
Reversed: malayalaM
Number of vowels: 4
Malayalam is a palindrome.
In Program 20.17, if the line N = N \ 10 is left out, N never becomes 0, the condition N > 0 stays true, and the program prints nothing and never stops. Press Ctrl + Break to stop a program that is stuck in a loop. Before running any WHILE or DO loop, find the line that moves the condition towards false.
20.7 Writing, running and debugging simple programs
From problem to program
- Plan the solution: write the algorithm or draw the flowchart (Lesson 18) and list the input, process and output.
- Start QBASIC (or QB64) and press Esc to clear the welcome box. For a new program choose File → New.
- Type the program in the program window, one statement per line. QBASIC capitalises the keywords as you leave each line; if it shows an error box instead, correct that line at once.
- Run the program with Shift + F5 (Run → Start). Type the inputs it asks for.
- Read the output screen. Press any key to return to the program; press F4 to see the output again.
- Test with data whose answers you know, including unusual values.
- Save with File → Save (or Save As), giving a name such as
MARKS.BAS; in MS-DOS a file name has at most eight characters before the extension. File → Open loads a saved program; File → Print prints it; File → Exit closes QBASIC.
Finding and fixing errors
- Syntax errors are caught as you type or when you run: QBASIC shows a message box and highlights the line.
- Run-time errors stop the running program with a message such as "Division by zero", "Overflow" or "Illegal function call", and the line is highlighted when you return to the editor.
- Logical errors give no message. Find them by comparing the output with the answers you worked out, by a trace table, by pressing F8 to run one line at a time, by setting a breakpoint with F9 to pause at a chosen line, or by typing
PRINT Sin the Immediate window while the program is paused, to see the value of S at that moment.
Problem. This program should find the average of N numbers typed by the user, but it has three faults. Find each, name its type, and write the corrected program.
CLS
REM Average of N numbers typed by the user
INPUT "How many numbers"; N
S = 1
FOR I = 1 TO N
INPUT "Enter a number"; X
S = S + X
NEXT J
PRINT "Average ="; S / N
END
Solution.
NEXT Jdoes not matchFOR I. QBASIC cannot pair them and refuses to run the program; FreeBASIC reported "FOR/NEXT variable name mismatch" and QB64 "Incorrect variable after NEXT". It must beNEXT I.S = 1is a logical error: a sum must start at 0. With only the NEXT corrected, the numbers 12, 15, 9 and 20 gave "Average = 14.25" instead of 14, with no warning at all.- If the user enters 0 for N,
S / Ndivides by zero — a run-time error. The corrected program checks N first.
CLS
REM Program 20.22: average of N numbers typed by the user
INPUT "How many numbers"; N
IF N <= 0 THEN
PRINT "Nothing to average."
ELSE
S = 0
FOR I = 1 TO N
INPUT "Enter a number"; X
S = S + X
NEXT I
PRINT "Average ="; S / N
END IF
END
Two runs:
How many numbers? 4
Enter a number? 12
Enter a number? 15
Enter a number? 9
Enter a number? 20
Average = 14
How many numbers? 0
Nothing to average.
Check: (12 + 15 + 9 + 20) ÷ 4 = 56 ÷ 4 = 14 ✓.
Start with CLS and a REM line saying what the program does; give every INPUT a clear prompt; use the same variable names throughout; indent the statements inside IF, SELECT CASE and loops; print the answer with a label (PRINT "Area ="; A); end with END. Then dry-run the program with one simple input and write that output below the program. In "give the output" questions, remember the leading space before every positive number, and trace loops in a table, one row per pass.
In pairs, in the computer lab: (1) Type and run Programs 20.3, 20.11 and 20.17 and save them as OPS.BAS, GRADE.BAS and DIGITS.BAS. (2) Change Program 20.14 so that it prints the table up to 20 and in the form 7 × 1 = 7. (3) Write a program that reads the electricity units used by a household and prints the bill at Rs 10 per unit with a minimum charge of Rs 100. (4) Write a program that prints the squares of the numbers 1 to 10, first with FOR … NEXT and then with WHILE … WEND. (5) Swap programs with your partner, find one error in each other's work by testing, and record it as a syntax, run-time or logical error.
Chapter summary
- QBASIC (Microsoft, 1991; from BASIC, 1964) is an interpreted, easy, structured language with a smart editor and built-in help; its screen has a title bar, menu bar, program window, Immediate window, scroll bars and status bar. Shift + F5 runs a program; F8 steps; F9 sets a breakpoint.
- Character set: letters, digits and special characters. Operators: arithmetic (
^ * / \ MOD + -), relational (= <> > < >= <=, true = −1, false = 0), logical (NOT, AND, OR) and string+; brackets first, then^, then* /, then\, then MOD, then+ -. - Statements: CLS clears the screen, REM writes a remark, LET assigns, INPUT reads (
;adds "? "), PRINT displays (;joins,,jumps to a 14-column zone, TAB(n) moves to column n), END ends. - Library functions: mathematical (SQR, ABS, INT, FIX, CINT, SGN, RND …) and string (LEN,
LEFT$,RIGHT$,MID$,UCASE$,LCASE$, ASC,CHR$,STR$, VAL, INSTR …). - Selection: single-line IF, block IF … ELSEIF … ELSE … END IF, and SELECT CASE with value lists,
TOranges,IScomparisons and CASE ELSE; only the first true branch runs. - Loops: FOR … NEXT (known count; STEP, negative STEP to count down), WHILE … WEND and DO WHILE … LOOP (test first; may run 0 times), DO … LOOP UNTIL (test last; runs at least once); loops can be nested.
- Writing and debugging: plan, type, run, test with known answers, save as .BAS; syntax and run-time errors give messages, logical errors are found by testing, trace tables, F8 and F9.
Practice questions
Group A — Objective (1 mark each)
- Which statement clears the output screen? [1]aENDbCLScREMdCLEAR SCREEN
- What is printed by
PRINT 17 MOD 5? [1]a3b3.4c2d5 - What is the value of
LEN("NEPAL")? [1]a4b5c6dNEPAL MID$("COMPUTER", 4, 3)gives [1]aCOMbPUTcMPUdTER- Which key runs a QBASIC program from the beginning? [1]aF1bF4cShift + F5dF9
- How many times does
FOR I = 1 TO 10 STEP 3repeat its body? [1]a3b4c10d30 - Which loop always runs its body at least once? [1]aFOR … NEXTbWHILE … WENDcDO WHILE … LOOPdDO … LOOP UNTIL
- The value of
INT(-4.5)is [1]a−4b−5c4d−4.5 - In QBASIC the expression
2 ^ 3 * 2gives [1]a64b12c16d10 - Which of these is a string function? [1]aSQRbABSc
UCASE$dINT - The REM statement is used to [1]aremove a linebwrite remarks that are not executedcrepeat statementsdread input
- The QBASIC window in which a statement runs as soon as Enter is pressed is the [1]aprogram windowbImmediate windowctitle bardstatus bar
Answers to Group A
1. (b) — CLS means clear screen.
2. (c) — 17 ÷ 5 = 3 remainder 2.
3. (b) — N, E, P, A, L: five characters.
4. (b) — three characters from position 4: P, U, T.
5. (c) — Shift + F5 is Run → Start.
6. (b) — I = 1, 4, 7, 10.
7. (d) — its test comes after the body.
8. (b) — INT goes down to the next whole number below −4.5.
9. (c) — the power first: 2 ^ 3 = 8, then 8 × 2 = 16.
10. (c) — UCASE$ works on a string and returns a string.
11. (b) — REM lines are remarks for people.
12. (b) — the Immediate window carries out a statement at once.
Group B — Short answer (2 marks each)
- Write any four features of QBASIC. [2]
- Write QBASIC expressions for(a) \frac{a+b}{2}(b) \pi r^2(c) \sqrt{b^2-4ac}(d) p \times t \times \frac{r}{100}. [2]
- Write the syntax and one example of the INPUT and PRINT statements. [2]
- Write the output of
PRINT LEFT$("BHAKTAPUR", 4),PRINT RIGHT$("BHAKTAPUR", 3),PRINT MID$("BHAKTAPUR", 3, 4)andPRINT LEN("BHAKTAPUR"). [2] - Differentiate between WHILE … WEND and DO … LOOP UNTIL. [2]
- Write a program to find the area of a triangle from its base and height. [2]
- Write a program to check whether a number is divisible by 5. [2]
- Write a program to display the squares of the numbers from 1 to 5. [2]
- Write the output of this program and say how many times the loop runs. [2]
FOR I = 1 TO 10 STEP 3
PRINT I;
NEXT I
- What is the difference between
/,\andMOD? Give the value of each for 17 and 5. [2]
Answers to Group B
1. Any four: it is easy to learn, with English keywords; programs are run by an interpreter, line by line; its smart editor checks syntax and capitalises keywords; it supports structured programming (block IF, SELECT CASE, loops, SUB and FUNCTION) without line numbers; it has many library functions; it has graphics and sound statements; it has built-in help (F1).
2. (a) (A + B) / 2 (b) 3.14 * R ^ 2 (or PI * R ^ 2 after CONST PI = 3.14) (c) SQR(B ^ 2 - 4 * A * C) (d) P * T * R / 100.
3. INPUT: INPUT ["prompt";] variable list, for example INPUT "Enter your name"; N$. PRINT: PRINT [list of expressions separated by ; or ,], for example PRINT "Total ="; T.
4. The four statements print BHAK, PUR, AKTA and 9 on four lines (the 9 with a space in front, because it is a number).
5. WHILE … WEND tests its condition before each pass, so its body may run zero times, and it repeats while the condition is true. DO … LOOP UNTIL tests after each pass, so its body runs at least once, and it repeats until the condition becomes true.
6.
CLS
INPUT "Base and height of the triangle: ", B, H
A = 1 / 2 * B * H
PRINT "Area of the triangle ="; A
END
Base and height of the triangle: 10, 6
Area of the triangle = 30
7.
CLS
INPUT "Enter a number"; N
IF N MOD 5 = 0 THEN PRINT N; "is divisible by 5." ELSE PRINT N; "is not divisible by 5."
END
Enter a number? 35
35 is divisible by 5.
8.
CLS
FOR I = 1 TO 5
PRINT I ^ 2;
NEXT I
END
1 4 9 16 25
9. The output is 1 4 7 10, on one line. The loop runs 4 times (I = 1, 4, 7, 10; the next value, 13, is past 10).
10. / is ordinary division, \ is integer division (the whole-number part of the quotient) and MOD gives the remainder. For 17 and 5: 17 / 5 = 3.4, 17 \ 5 = 3 and 17 MOD 5 = 2.
Group C — Long answer (4 marks each)
- Write a program that reads the marks of a student in five subjects, then displays the total, the percentage and the SEE grade (A+ 90 and above, A 80, B+ 70, B 60, C+ 50, C 40, D 35, NG below 35), using SELECT CASE. [4]
- Write a program to display the series 5, 10, 15, …, 50 and the sum of its terms. [4]
- Write a program to check whether a number is prime or composite. [4]
- Write a program to display this pattern: [4]
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
- Dry-run the program below in a trace table and write its output. [4]
CLS
N = 5
S = 0
WHILE N > 0
S = S + N * N
N = N - 2
WEND
PRINT "S ="; S
END
Answers to Group C
1.
CLS
REM Total, percentage and grade from marks in five subjects
T = 0
FOR I = 1 TO 5
PRINT "Marks in subject"; I;
INPUT M
T = T + M
NEXT I
P = T / 5
SELECT CASE P
CASE IS >= 90
G$ = "A+"
CASE IS >= 80
G$ = "A"
CASE IS >= 70
G$ = "B+"
CASE IS >= 60
G$ = "B"
CASE IS >= 50
G$ = "C+"
CASE IS >= 40
G$ = "C"
CASE IS >= 35
G$ = "D"
CASE ELSE
G$ = "NG"
END SELECT
PRINT "Total ="; T
PRINT "Percentage ="; P
PRINT "Grade: "; G$
END
Marks in subject 1 ? 78
Marks in subject 2 ? 85
Marks in subject 3 ? 69
Marks in subject 4 ? 92
Marks in subject 5 ? 74
Total = 398
Percentage = 79.6
Grade: B+
(Marks: the loop or five INPUTs, the total and percentage, the SELECT CASE, and the output.)
2.
CLS
REM The series 5, 10, 15, ..., 50 and its sum
S = 0
FOR I = 5 TO 50 STEP 5
PRINT I;
S = S + I
NEXT I
PRINT
PRINT "Sum ="; S
END
5 10 15 20 25 30 35 40 45 50
Sum = 275
3. A prime number has exactly two factors, 1 and itself, so the program counts the factors.
CLS
REM Prime or composite
INPUT "Enter a whole number greater than 1"; N
C = 0
FOR I = 1 TO N
IF N MOD I = 0 THEN C = C + 1
NEXT I
IF C = 2 THEN
PRINT N; "is a prime number."
ELSE
PRINT N; "is a composite number. It has"; C; "factors."
END IF
END
Two runs:
Enter a whole number greater than 1? 29
29 is a prime number.
Enter a whole number greater than 1? 51
51 is a composite number. It has 4 factors.
(51 = 3 × 17, so its factors are 1, 3, 17 and 51.)
4. Row I prints the numbers from 5 down to I.
CLS
REM A pattern made with nested loops
FOR I = 1 TO 5
FOR J = 5 TO I STEP -1
PRINT J;
NEXT J
PRINT
NEXT I
END
The program printed the pattern exactly as shown in the question.
5.
| Pass | N at the test | N > 0? | S = S + N × N | N = N − 2 |
|---|---|---|---|---|
| 1 | 5 | yes | 0 + 25 = 25 | 3 |
| 2 | 3 | yes | 25 + 9 = 34 | 1 |
| 3 | 1 | yes | 34 + 1 = 35 | −1 |
| — | −1 | no | — | — |
Output:
S = 35
Practise more: Computer Science question bank