0% found this document useful (0 votes)
0 views42 pages

CMP 102 Introduction To Problem Solving Techniques2

CMP 102 is an introductory course focused on problem-solving strategies, algorithm development, and flowchart creation. The course aims to equip students with the ability to define problems, develop algorithms, and implement solutions using BASIC programming. Key learning outcomes include understanding problem-solving concepts, algorithm properties, and the ability to write and debug simple programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views42 pages

CMP 102 Introduction To Problem Solving Techniques2

CMP 102 is an introductory course focused on problem-solving strategies, algorithm development, and flowchart creation. The course aims to equip students with the ability to define problems, develop algorithms, and implement solutions using BASIC programming. Key learning outcomes include understanding problem-solving concepts, algorithm properties, and the ability to write and debug simple programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

CMP 102 INTRODUCTION TO PROBLEM SOLVING (3 UNITS)

COURSE CONTENTS
Problem Solving Strategies; Role of Algorithm in Problem Solving Process; Implementation
Strategies, Concepts and Properties of Algorithm.

OBJECTIVES
The specific objectives of this course are to:
1. Understand the concept of Problem solving.
2. Understand steps involved in algorithm development.
3. Understand the concept of Algorithm.
4. Develop Algorithm for simple problem.
5. Understand the concept of Flowchart development.
6. Draw the symbols used in Flowcharts.
7. Understand Basic program for problem solving.

LEARNING OUTCOMES
The students should be able to:
1. Discuss concept of Problem solving.
2. Explain the steps involved in problem solving.
3. Explain steps involved in algorithm development.
4. Explain the concept of Flowchart development.
5. Know the Symbols used in Flow Charts.
6. Explain the concept of Pseudo Code.
7. Explain BASIC programming language and its importance.
8. Explain various data types in BASIC.
9. Use BASIC program as a working vehicle for problem solving.
10. Write short computer programs in BASIC
11. Debug a simple computer programs in BASIC

TEXT BOOK(S):
1. O’connell, S. (2007). Introduction to problem solving. Portsmouth: Heinemann.
2. Noggle, J. H. (1992). QuickBASIC programming for scientists and engineers. CRC
Press.

Course Writer/Developer: Dr. F.E. AYO, Department of Mathematical Sciences, Computer


science unit, Olabisi Onabanjo University, Ago-Iwoye.
E-mail: [email protected]
INTRODUCTION TO PROBLEM SOLVING TECHNIQUES
Introduction
A computer is a very powerful and versatile machine capable of performing a multitude of
different tasks, yet it has no intelligence or thinking power. The intelligence Quotient (I.Q) of
a computer is zero. A computer performs many tasks exactly in the same manner as it is told
to do. This places responsibility on the user to instruct the computer in a correct and precise
manner, so that the machine is able to perform the required job in a proper way. A wrong or
ambiguous instruction may sometimes prove disastrous.
In order to instruct a computer correctly, the user must have clear understanding of the problem
to be solved. A part from this he should be able to develop a method, in the form of series of
sequential steps, to solve it. Once the problem is well-defined and a method of solving it is
developed, then instructing the computer to solve the problem becomes relatively easier task.
Thus, before attempt to write a computer program to solve a given problem. It is necessary to
formulate or define the problem in a precise manner. Once the problem is defined, the steps
required to solve it, must be stated clearly in the required order.
Steps Involved in Problem Solving
A computer cannot solve a problem on its own. One has to provide step by step solutions of
the problem to the computer. In fact, the task of problem solving is not that of the computer. It
is the programmer who has to write down the solution to the problem in terms of simple
operations which the computer can understand and execute.
In order to solve a problem by the computer, one has to pass though certain stages or steps.
They are:
1. Problem Definition
2. Problem Analysis
3. Developing the solution
4. Coding and implementation.
In order to understand the basic steps in solving a problem on a computer, let us define a single
problem that we will solve step-by-step as we discuss the problem solving methodologies in
detail. The problem we will solve will be defined in the next section.
PROBLEM DEFINITION
A programmer is usually given a task in the form of a problem. Before a program can be
designed to solve a particular problem, the problem must be well and clearly defined first in
terms of its input and output requirements.
A clearly defined problem is already half the solution. Computer programming requires us to
define the problem first before we even try to create a solution.
Let us now define our example problem:
“Create a program that will determine the number of times a name occurs in a list.”
PROBLEM ANALYSIS
After the problem has been adequately defined, the simplest and yet the most efficient and
effective approach to solve the problem must be formulated.
Usually, this step involves breaking up the problem into smaller and simpler subproblems.
Example Problem:
Determine the number of times a name occurs in a list
Input to the program:
list of names, name to look for
Output of the program:
the number of times the name occurs in a list

DEVELOPING THE SOLUTION


Algorithm Design and Representation
Once our problem is clearly defined, we can now set to finding a solution. In computer
programming, it is normally required to express our solution in a step-by-step manner.
An Algorithm is a clear and unambiguous specification of the steps needed to solve a problem.
It may be expressed in either Human language (English, Tagalog), through a graphical
representation like a flowchart or through a pseudocode, which is a cross between human
language and a programming language.
Now given the problem defined in the previous sections, how do we express our general
solution in such a way that it is simple yet understandable?
Expressing our solution through Human language:
1. Get the list of names, nameList
2. Get the name to look for, let's call this the keyname
3. Compare the keyname to each of the names in the list
4. If the keyname is the same with a name in the list, add 1 to the count
5. If all the names have been compared, output the result

Expressing our solution through a flowchart:


Figure 1. Example of a flow chart

Expressing our solution through pseudocode:


1. Start
2. Let nameList = List of Names
3. Let keyName = the name to be sought
4. Let Count = 0
5. For each name in NameList do the following
6. if name == keyName
7. Count = Count + 1
8. Display Count
9. Stop

CODING AND IMPLEMENTATION


The last stage of the problem solving is the conversion of the detailed sequence of operations
in to a language that the computer can understand. Here each step is converted to its equivalent
instruction or instructions in the computer language that has been chosen for the implantation.
Algorithm
Definition
A set of sequential steps usually written in Ordinary Language to solve a given problem is
called Algorithm.
It may be possible to solve to problem in more than one ways, resulting in more than one
algorithm. The choice of various algorithms depends on the factors like reliability, accuracy
and easy to modify. The most important factor in the choice of algorithm is the time
requirement to execute it, after writing code in High-level language with the help of a computer.
The algorithm which will need the least time when executed is considered the best.

Steps involved in algorithm development


An algorithm can be defined as “a complete, unambiguous, finite number of logical steps for
solving a specific problem “:
Step1. Identification of input: For an algorithm, there are quantities to be supplied called
input and these are fed externally. The input is to be identified first for any specified problem.
Step2: Identification of output: From an algorithm, at least one quantity is produced, called
for any specified problem.
Step3 : Identification the processing operations : All the calculations to be performed in
order to lead to output from the input are to be identified in an orderly manner.
Step4 : Processing Definiteness: The instructions composing the algorithm must be clear and
there should not be any ambiguity in them.
Step5 : Processing Finiteness : If we go through the algorithm, then for all cases, the algorithm
should terminate after a finite number of steps.
Step6 : Possessing Effectiveness : The instructions in the algorithm must be sufficiently basic
and in practice they can be carries out easily.
An algorithm must possess the following properties
1. Finiteness: An algorithm must terminate in a finite number of steps
2. Definiteness: Each step of the algorithm must be precisely and unambiguously stated
3. Effectiveness: Each step must be effective, in the sense that it should be primitive easily
convert able into program statement) can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it can be used to solve problems
of a specific type for any input data.
5. Input/output: Each algorithm must take zero, one or more quantities as input data produce
one or more output values. An algorithm can be written in English like sentences or in any
standard representation sometimes, algorithm written in English like languages are called
Pseudo Code.
Example
1. Suppose we want to find the average of three numbers, the algorithm is as follows
Step 1 Read the numbers a, b, c
Step 2 Compute the sum of a, b and c
Step 3 Divide the sum by 3
Step 4 Store the result in variable d
Step 5 Print the value of d
Step 6 End of the program

Algorithms for Simple Problem


Write an algorithm for the following
1. Write an algorithm to calculate the simple interest using the formula.
Simple interest = P*N* R/100.
Where P is principle Amount, N is the number of years and R is the rate of interest.
Step 1: Read the three input quantities’ P, N and R.
Step 2 : Calculate simple interest as
Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.

2. Area of Triangle: Write an algorithm to find the area of the triangle.


Let b, c be the sides of the triangle ABC and A the included angle between the given sides.
Step 1: Input the given elements of the triangle namely sides b, c and angle between the sides
A.
Step 2: Area = (1/2) *b*C* sin A
Step 3: Output the Area
Step 4: Stop.

3. Write an algorithm to find the largest of three numbers X, Y,Z.


Step 1: Read the numbers X,Y,Z.
Step 2: if (X > Y)
Big = X
else BIG = Y
Step 3 : if (BIG < Z)
Step 4: Big = Z
Step 5: Print the largest number i.e. Big
Step 6: Stop.
4. Write down an algorithm to find the largest data value of a set of given data values
Algorithm largest of all data values:
Step 1: LARGE ← 0
Step 2: read NUM
Step 3: While NUM > = 0 do
3.1 if NUM > LARGE
3.1.1 then
3.1.1.1 LARGE ← NUM
3.2. read NUM
Step 4: Write “largest data value is”, LARGE
Step 5: end.

5. Write an algorithm which will test whether a given integer value is prime or not.
Algorithm prime testing:
Step 1: M ← 2
Step 2: read N
Step 3: MAX ← SQRT (N)
Step 4: While M < = MAX do
4.1 if (M* (N/M) = N
4.1.1 then
4.1.1.1 go to step 7
4.2. M ← M + 1
Step 5: Write “number is prime”
Step 6: go to step 8
Step 7: Write “number is not a prime”
Step 8: end.

6. Write algorithm to find the factorial of a given number N


Step 1: PROD ← 1
Step 2: I ← 0
Step 3: read N
Step 4: While I < N do
4.1 I ← I + 1
4.2. PROD ← PROD* I
Step 5: Write “Factorial of”, N, “is”, PROD
Step 6: end.

7. Write an algorithm to find sum of given data values until negative value is entered.
Algorithm Find – Sum
Step 1: SUM ← 0
Step 2: I ← 0
Step 3: read NEW VALUE
Step 4: While NEW VALUE < = 0 do
4.1 SUM ← SUM + NEW VALUE
4.2 I ← I + 1
4.3 read NEW VALUE
Step 5: Write “Sum of”, I, “data value is, “SUM
Step 6: END

8. Write an algorithm to calculate the perimeter and area of rectangle. Given its length and
width.
Step 1: Read length of the rectangle.
Step 2: Read width of the rectangle.
Step 3: Calculate perimeter of the rectangle using the formula perimeter =2* (length + width)
Step 4: Calculate area of the rectangle using the formula area = length*width.
Step 5: Print perimeter.
Step 6: Print area.
Step 7: Stop.
Flowchart
A flow chart is a step by step diagrammatic representation of the logic paths to solve a given
problem. Or A flowchart is visual or graphical representation of an algorithm.
The flowcharts are pictorial representation of the methods to b used to solve a given problem
and help a great deal to analyze the problem and plan its solution in a systematic and orderly
manner. A flowchart when translated in to a proper computer language, results in a complete
program.
Advantages of Flowcharts
1. The flowchart shows the logic of a problem displayed in pictorial fashion which felicitates
easier checking of an algorithm.
2. The Flowchart is good means of communication to other users. It is also a compact means
of recording an algorithm solution to a problem.
3. The flowchart allows the problem solver to break the problem into parts. These parts can be
connected to make master chart.
4. The flowchart is a permanent record of the solution which can be consulted at a later time.
Differences between Algorithm and Flowchart
Algorithm Flowchart
1. A method of representing the step-by-step 1. Flowchart is diagrammatic representation
logical procedure for solving a problem of an algorithm. It is constructed using
different types of boxes and symbols.
2. It contains step-by-step English 2. The flowchart employs a series of blocks
descriptions, each step representing a and arrows, each of which represents a
particular operation leading to solution of particular step in an algorithm
problem
3. These are particularly useful for small 3. These are useful for detailed
problems representations of complicated programs
4. For complex programs, algorithms prove 4. For complex programs, Flowcharts prove
to be Inadequate to be adequate

Symbols Used In Flow Charts


The symbols that we make use while drawing flowcharts as given below are as per conventions
followed by International Standard Organization (ISO).
a. Oval: Rectangle with rounded sides is used to indicate either START/ STOP of the program.

b. Input and output indicators: Parallelograms are used to represent input and output
operations. Statements like INPUT, READ and PRINT are represented in these Parallelograms.
c. Process Indicators: Rectangle is used to indicate any set of processing operation such as for
storing arithmetic operations.

d. Decision Makers: The diamond is used for indicating the step of decision making and
therefore known as decision box. Decision boxes are used to test the conditions or ask questions
and depending upon the answers, the appropriate actions are taken by the computer. The
decision box symbol is

e. Flow Lines: Flow lines indicate the direction being followed in the flowchart. In a
Flowchart, every line must have an arrow on it to indicate the direction. The arrows may be in
any direction

f. On- Page connectors: Circles are used to join the different parts of a flowchart and these
circles are called on-page connectors. The uses of these connectors give a neat shape to the
flowcharts. Ina complicated problems, a flowchart may run in to several pages. The parts of
the flowchart on different pages are to be joined with each other. The parts to be joined are
indicated by the circle.
g. Off-page connectors: This connector represents a break in the path of flowchart which is
too large to fit on a single page. It is similar to on-page connector. The connector symbol marks
where the algorithm ends on the first page and where it continues on the second.

Simple Problems Using Flow Chart


Draw the Flowchart for the following
1. Draw the Flowchart to find Roots of Quadratic equation ax2+ bx + c= 0. The coefficients a,
b, c are the input data

2. Draw a flowchart to find out the biggest of the three unequal positive numbers.
3. Draw a flowchart for adding the integers from 1 to 100 and to print the sum.

4. Draw a flowchart to find the factorial of given positive integer N.


5. Develop a flowchart to illustrate how to make a Land phone telephone call

Flowchart for Telephone call


6. ABC company plans to give a 6% year-end bonus to each of its employees earning N6,000
or more per month, and a fixed N250/bonus to the remaining employees. Draw a flowchart for
calculating the bonus for an employee.

Pseudo Code
The Pseudo code is neither an algorithm nor a program. It is an abstract form of a program. It
consists of English like statements which perform the specific operations. It is defined for an
algorithm. It does not use any graphical representation. In pseudo code, the program is
represented in terms of words and phrases, but the syntax of program is not strictly followed.
Advantages:
 Easy to read
 Easy to understand
 Easy to modify.
Example: Write a pseudo code to perform the basic arithmetic operations.
Read n1, n2
Sum = n1 + n2
Diff = n1 – n2
Mult = n1 * n2
Quot = n1/n2
Print sum, diff, mult, quot
End.
PROGRAMMING IN BASIC
The original BASIC was first developed at Dartmouth College by John Kemeny, Mary Keller,
and Thomas Kurtz and introduced on May 1, 1964. BASIC is short for Beginner’s All-purpose
Symbolic Instruction Code and is an easy-to-understand programming language that was
popular during 1970 – 1980. Today, BASIC is not used to develop programs, but is sometimes
used to help teach the fundamentals of programming.
The BASIC language was originally designed as a simplified version of FORTRAN for use in
teaching programming. From the simple beginnings, the language has grown to become a very
popular multi-purpose language available on a wide variety of machines.
There are many versions of the Basic language:
1. Ms-Basic
2. GW- Basic
3. QBasic-Quick Basic
4. Just BASIC (JBasic)
5. BASIC Plus
6. BASIC A
7. Turbo BASIC

INSTALLING AND RUNNING JBASIC


Download it here: https://justbasic.com/download.html
ELEMENTS OF BASIC
 Character set
BASIC has the character set consisting of the following elements:
1. Alphabets: A, B, C,….Z (small or capital)
2. Digits: 0, 1, 2……..,9 and
3. Special characters: + – * / ( ) . , $ ; ,: ,= ,> ,< , ^
 Variables
The quantity which may change its values during the execution of the program is called the
variable. A variable is a piece of data kept in the computer's memory (RAM). The location
of a variable in RAM is called the "address."
In QBASIC, variables are also of two types:
i. Numeric variable: Numeric variable can assume numeric value and is represented
by an alphabet or an alphabet followed by another alphabet or digit. For example
A, C, A2, ABC, A6 etc., represent numeric variables.
ii. String/character variable: A string variable is represented by an alphabet
followed by dollar ($) sign. It should be kept in mind that while constructing the
string variable, dollar ($) should be the last character. For example, B1$, NAME$,
BOOK1$, etc. are valid string variables.
 Constants
A quantity in a computer program which does not change its value during the execution of
the program is called a constant. BASIC allows the following constants:
i. Numeric constant: The numeric constant is one that is formed by a sequence
of digits 0, 1, 2,…..9 and may include a decimal point. A numeric constant may
be an integer or a real number. 383, +57, 0, -6.2 and 6.15E4 are valid numeric
constants.
ii. String/character constant: A string constant consists of a sequence of
characters which must be enclosed by a quotation.
 Operator and Operands
Operands are the data or variables on which mathematical, logical and string operations
take place.
Operators are the symbols, which are used in arithmetic operations, logical expressions,
and string expressions.
 Expression
An expression can be a string, or numeric constant, a variable or a combination of constants,
variables with operators which returns a single value.
 Statements
A statement is a set of instructions written using keywords or commands of BASIC. Every
programming language uses keywords as a statement with certain syntax.

BASIC KEYWORDS
1. Remark Statement (REM): This is a remark. It does not affect the program in terms
of instruction or command line. REM: It is used in explaining what the program is all
about.
Example,
10 REM. Program to calculate average of numbers.
This statement will appear as comment on the screen
2. Assignment Statement: This keyword is used in assigning values to variables, e.g.
READ, DATA, LET, INPUT.
 READ statement: This is a statement used in giving values to variables. Usually
READ statement has DATA statement with it.
Example:
10 REM PROGRAM TO SUM NUMBERS
20 READ X
30 DATA 2
40 READ Y
50 DATA 3
60 READ Z
70 DATA 5
80 SUM=X+Y+Z
90 PRINT "The sum is:", SUM
 LET statement: This statement is used in attaching strings of fixed characters and
numeric data in BASIC.
Examples,
10 REM PROGRAM TO SUM NUMBERS
20 READ X
30 DATA 2
40 READ Y
50 DATA 3
60 READ Z
70 DATA 5
80 LET SUM=X+Y+Z
90 PRINT "The sum is:", SUM
 INPUT/ PRINT statements: INPUT statement is used assigning values to variables.
PRINT statement is used displaying values to the screen. The PRINT statement is
usually followed by a list of items to be displayed and each item is separated by a
comma (,) or semi-colon (;).
Example 1:
10 REM PROGRAM TO SUM NUMBERS
20 input "Enter first number:"; X
30 INPUT "Enter second number:"; Y
40 INPUT "Enter third number:"; Z
50 PRINT X, Y, Z
60 PRINT "X=",X,"Y=",Y,"Z=",Z
70 LET SUM=X+Y+Z
80 PRINT "The sum is:", SUM
Example 2:
PRINT 512 + 478
Program output:
990
If you enclose the expression with quotation marks, the expression becomes a string and
isn't evaluated. For example:
PRINT "512 + 478"
Output:
512 + 478
You can use multiple print statements in your program.
PRINT "Hello"
PRINT "World"
Output:
Hello
World

To place World onto the previous line, place a semi-colon after PRINT "Hello".
PRINT "Hello";
PRINT "World"
Output:
HelloWorld

Also, if you put a comma instead of a semi-colon on the first line, the program will insert
spaces between the two words.
PRINT "Hello",
PRINT "World"
Output:
Hello World
 Program Terminator: These keywords are used to terminate the program, e.g. STOP
and END.
a) STOP statement: This statement is used to terminate a program.
b) END statement: This statement is used to terminate a program.
Example:
10 REM PROGRAM TO SUM NUMBERS
20 input "Enter first number:"; X
30 INPUT "Enter second number:"; Y
40 INPUT "Enter third number:"; Z
50 PRINT X, Y, Z
60 PRINT "X=",X,"Y=",Y,"Z=",Z
70 LET SUM=X+Y+Z
80 PRINT "The sum is:", SUM
90 STOP

Assignments
1. Write a BASIC program to calculate the product of three numbers
2. Write a program to calculate the area of a circle. (Area= πr2)
3. Write a program to calculate simple interest
4. Write a BASIC program to calculate the sum of two numbers
5. Write a BASIC program to find the average of 3 Numbers
6. Write a BASIC program to calculate the area of a triangle with base
7. Write a program to find the product of four numbers using the ‘LET’ statement
8. Write a program to calculate the average of five numbers using the ‘INPUT’ statement

VARIABLES
A variable is a piece of data kept in the computer's memory (RAM). The location of a variable
in RAM is called the "address."
The following program prints the variable X to the screen:
print X
Since the variable hasn't been assigned a number, the value of the variable is 0. So, the output
of the program is:
0
This next program sets X to 15, and then prints the variable:
X = 15
print X
This time, the output is:
15
Also, you can use multiple variables in your program.
X = 82
Y = 101
Z = 79
PRINT X
PRINT Y
PRINT Z
Output:
82
101
79

EXPRESSIONS
If you pass an expression to a variable, the expression is evaluated and the variable is set to
that value.
x = 500 + (10 * 7)
PRINT x
Output:
570

You can also use variables as expressions.


rate = 50
time = 2
distance = rate * time
PRINT distance
Output:
100

Plus, you can have both variables and numbers in an expression.


X = 100
Y=X*7
PRINT Y
Output:
700

STRINGS
If you add a dollar sign ($) to the end of a variable, the variable is a string.
X$ = "Hello World!"
PRINT X$
Output:
Hello World!

A string can be added to the end of an existing variable string.


X$ = "Hello"
X$ = X$ + "World"
PRINT X$
Output:
HelloWorld

You can also add variable strings together.


a$ = "String1"
b$ = "String2"
c$ = "String3"
d$ = a$ + b$ + c$
PRINT d$
Output:
String1String2String3

RECEIVING KEYBOARD INPUT FROM THE USER


One way to receive input from the keyboard is with the INPUT command. The INPUT
command allows the user to enter either a string or a number, which is then stored in a variable.
INPUT data$
PRINT data$
When this program is executed, the INPUT command displays a question mark, followed by a
blinking cursor. And when you enter text, the program stores that text into the variable data$,
which is printed to the screen.
To receive a number, use a non-string variable.
INPUT number
PRINT number

Below is another example of the INPUT command:

PRINT "Enter some text:"


INPUT text$

PRINT "Now enter a number:"


INPUT num

PRINT text$
PRINT num

CONTROL STRUCTURE
Control structure/statements are used in program to direct the order of execution of the
program. Normally, statements in a program are executed one after the other in the order in
which they’re written. This process is called sequential execution. Various Basic statements,
enable you to specify that the next statement to execute is not necessarily the next one in
sequence. This is called transfer of control. Structured programs are clearer, easier to debug
and modify, and more likely to be bug free in the first place.
Programs could be written in terms of only three control statements:
 the selection statement
 the Jump statement
 the repetition statement.
SELECTION STATEMENT
The selection structure are known as decision making structures. It require that the programmer
specify one or more conditions to be evaluated or tested by the program, along with a statement
or statements to be executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.
There are three basic types of selection statements:
i. If-then (Single-Selection) Statement
The if statement either performs (selects) an action, if a condition is true, or skips it, if the
condition is false. The if-then statement is the simplest form of control statement, frequently
used in decision making and changing the control flow of the program execution.
Example:
x=5
IF x = 5 THEN PRINT "x equals 5"
Since X does equal 5 in this case, the program outputs:
x equals 5

Expression signs
You can also enter the following statements, instead of the equals sign:
x < 5 (x is less than 5)
x > 5 (x is greater than 5)
Run the following:
x = 16
IF (x > 5) THEN PRINT "x is greater than 5"
Output:
x is greater than 5
You can also combine the signs like this:
x <= 5 (x is less than or equal to 5)
x >= 5 (x is greater than or equal to 5)
x <> 5 (x does not equal 5)
Run the following example:

CLS
x=5
IF (x >= 5) THEN PRINT "x is greater than or equal to 5"
IF (x <= 5) THEN PRINT "x is less than or equal to 5"
IF (x <> 5) THEN PRINT "x does not equal 5"

Output:
x is greater than or equal to 5
x is less than or equal to 5
ii. if-then-else (Double Selection) Statement
The if-then-else statement performs an action if a condition is true and performs a different
action if the condition is false. The if-then single-selection statement performs an indicated
action only when the condition is true; otherwise, the action is skipped. The if-then-else double-
selection statement allows you to specify an action to perform when the condition is true and a
different action when the condition is false.
Using the ELSE command, you can have the program perform a different action if the statement
is false.
x=3
IF x = 5 THEN PRINT "Yes" ELSE PRINT "No"
Output
No

END IF
END IF allows you to have multiple commands after the IF...THEN statement, but they must
start on the line after the IF statement. END IF should appear right after the list of commands.
x=5
IF (x = 5) THEN
INPUT a$
PRINT a$
END IF

The following program uses ELSE with the END IF command:


x = 16
IF (x = 5) THEN
INPUT a$
PRINT a$
ELSE
PRINT x * 2
END IF

Output:
32

iii. if-then-else-if (Multiple Selection) Statement


The if-then-else-if statement enable us to implement multiple decisions in a program. Basic use
the if-then-else-if command to perform a secondary action if the first expression was false.

Example 1:
x=6
IF (x = 5) THEN
PRINT "Statement 1 is true"
ELSEIF (x = 6) THEN
PRINT "Statement 2 is true"
END IF

Output:
Statement 2 is true
Example 2:
You can have multiple ELSEIF commands, along with ELSE.
x=8
IF (x = 5) THEN
PRINT "Statement 1 is true"
ELSEIF (x = 6) THEN
PRINT "Statement 2 is true"
ELSEIF (x = 7) THEN
PRINT "Statement 3 is true"
ELSE
PRINT "No above statements are true"
END IF

Output:
No above statements are true

Strings in IF...THEN
So far in this chapter, we've only been dealing with numbers, but you can also use strings with
the IF...THEN command.
x$ = "Hello"
IF (x$ = "Hello" OR x$ = "World") THEN PRINT x$

Output:
Hello

You can also compare two variable strings:


x$ = "Hello"
y$ = "World"
IF (x$ <> y$) THEN PRINT x$; " "; y$

Output:
Hello World

JUMP STATEMENT
The GOTO and GOSUB commands enables you to jump to certain positions in your program.
Labels are used to specify what point in the program to continue execution.
GOTO
To use GOTO, place a label somewhere in your program, and then enter.
GOTO <label>
Example
Run the following example program:
PRINT "1"
GOTO TheLabel
PRINT "2"
TheLabel:
PRINT "3"

Output (notice how PRINT "2" is skipped):


1
3

GOSUB
The GOSUB command is the same as GOTO, except when it encounters a RETURN statement,
the program "returns" back to the GOSUB command. In other words, RETURN continues
program execution immediately after the previous GOSUB statement.
PRINT "1"
GOSUB TheLabel
PRINT "2"
END
TheLabel:
PRINT "3"
RETURN

Output (Note: The END command exits the program.)


Since the program returns to the GOSUB command, the number 2 is printed this time.
1
3
2
LINE NUMBERS
"Line numbers" can be used as labels.

PRINT "1"
GOTO 10
PRINT "2"
10 PRINT "3" (Notice the line number)

You can also write the program like this:


10 PRINT "1"
20 GOTO 40
30 PRINT "2"
40 PRINT "3"

The line numbers don't even have to be in sequence.


17 PRINT "1"
2 GOTO 160
701 PRINT "2"
160 PRINT "3"

Each of these programs output:


1
3

GUESSING GAME
The following is a simple guessing game:
CLS
start:
PRINT "Guess a number between 1 and 10: ";
INPUT num
IF (num < 1 OR num > 10) THEN
PRINT "That is not between 1 and 10"
GOTO start
END IF
IF (num = 6) THEN
PRINT "Correct!!!"
ELSE
PRINT "Try again"
PRINT
GOTO start
END IF

Output (may be slightly different):


Guess a number between 1 and 10: ? 2
Try again
Guess a number between 1 and 10: ? 7
Try again
Guess a number between 1 and 10: ? 6
Correct!!!

REPETITION or LOOP STATEMENT


There may be a situation, when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. Programming languages provide various control
structures that allow for more complicated execution paths.
Loops make it easier to do an action multiple times. There are at least four types of loops:
 IF...GOTO
 WHILE...WEND
 DO...LOOP, and
 FOR...NEXT
IF...GOTO
This program uses IF...GOTO to create a loop:
x = 10
start:
PRINT x
x = x + 1 (This adds 1 to x)
IF x < 15 THEN GOTO start

Output:
10
11
12
13
14

WHILE...WEND
The WHILE...WEND commands continue a loop until a specified expression is false.
To use WHILE...WEND:
1. Place an expression after WHILE
2. Enter a list of commands
3. Place WEND at the end

Example:
x = 10
WHILE x < 15
PRINT x
x=x+1
WEND
Output (same as in previous example):
10
11
12
13
14

DO...LOOP
DO...LOOP is exactly the same as WHILE...WEND, except it has at least two slight
advantages.
With DO...LOOP you can:
1. Loop until an expression is true
2. Loop at least one time regardless of whether the expression is true or not.
To use DO...LOOP:
1. Specify whether the loop continues "while" the expression is true or "until" the
expression is true, using the WHILE and UNTIL statements, respectively.
2. Place an expression after WHILE/UNTIL
3. Enter a list of commands
4. Place LOOP at the end
The following uses the WHILE statement:
x = 10
DO WHILE x < 15
PRINT x
x=x+1
LOOP

This program uses the UNTIL statement:


x = 10
DO UNTIL x = 15
PRINT x
x=x+1
LOOP
They both output:
10
11
12
13
14

If you place the expression at the end of the loop instead, the program goes through the loop at
least once.
x = 32
DO
PRINT x
x=x+1
LOOP WHILE x < 5

This is the output because the loop was only gone through one time:
32

FOR...NEXT
FOR...NEXT provides an easier way to create a loop.
Example:
FOR x = 1 TO 5
PRINT x
NEXT x

Output:
1
2
3
4
5
Also, you can use the STEP attribute to specify how much X will be increased each time
through the loop.
FOR x = 1 TO 5 STEP 2
PRINT x
NEXT x

Output:
1
3
5

STOPPING LOOPS
To stop a loop prematurely, use the EXIT command, followed by either FOR or DO.
Example:
FOR x = 1 TO 5
PRINT x
IF (x = 3) THEN EXIT FOR
NEXT x

Output:
1
2
3
(NOTE: This command only works with the DO...LOOP and FOR...NEXT commands, not
with WHILE...WEND or IF...GOTO.)

MATHEMATICS FUNCTIONS
Basic provides several functions to do mathematical calculations. A few of them are discussed
here.
SQR
Use SQR to find the "square root" of a number.
PRINT SQR(1)
PRINT SQR(4)
PRINT SQR(9)
PRINT SQR(16)
PRINT SQR(25)

Output:
1
2
3
4
5

ABS
ABS returns the absolute value of a number. In other words, ABS converts a negative number
to a positive number (if you pass a positive number, ABS does nothing).
PRINT ABS(12)
PRINT ABS(-12)
Output:
12
12

COS, SIN, TAN, and ATN


You can do the following trigonometric functions in QBasic:
COS (Cosine)
SIN (Sine)
TAN (Tangent)
ATN (Arctangent, inverse of TAN)
Example:
CONST PI = 3.141593
PRINT COS(PI / 4)
PRINT SIN(PI / 3)
PRINT TAN(-PI / 2)
PRINT ATN(TAN(-PI / 2))

Output:
.7071067
.8660254
6137956
1.570796 (Same as PI / 2)

ARRAYS
An array is a list of variables of the same type. Arrays are useful for organizing multiple
variables. To create an array, use the DIM (dimension) command.
The following example does not use arrays:
a=2
b=4
c=6
d=8
e = 10
PRINT a, b, c, d, e
Output:
2 4 6 8 10

This uses an array called vars, which contains 5 variables:


DIM vars(5)
Each of these are separate variables:
vars(1) = 2
vars(2) = 4
vars(3) = 6
vars(4) = 8
vars(5) = 10
PRINT vars(1), vars(2), vars(3), vars(4), vars(5)
Output:
2 4 6 8 10

How an array of variables is stored in memory


(NOTE: Memory addresses are not necessarily as specified)

The above program can also be written like this:


DIM vars(5)
FOR x = 1 to 5
vars(x) = x * 2
NEXT
FOR x = 1 to 5
PRINT vars(x),
NEXT

Output:
2 4 6 8 10
STRINGS
You can also create an array of string variables.
DIM vars$(5)
vars$(1) = "Two"
vars$(2) = "Four"
vars$(3) = "Six"
vars$(4) = "Eight"
vars$(5) = "Ten"
PRINT vars$(1), vars$(2), vars$(3), vars$(4), vars$(5)

Output:
Two Four Six Eight Ten

SUBROUTINES AND FUNCTIONS


A subroutine (also called a "module") is a "mini-program" inside your program. In other words,
it is a collection of commands--and can be executed anywhere in your program.
To create a subroutine:
1. Go to the "Edit" menu
2. Select "New Sub"
3. Enter a name for the subroutine
4. Type a list of commands between SUB and END SUB

The following example does not use subroutines:


PRINT "Enter some text:";
INPUT text$
PRINT "The text you entered was: "; text$

PRINT "Enter some text:";


INPUT text$
PRINT "The text you entered was: "; text$

PRINT "Enter some text:";


INPUT text$
PRINT "The text you entered was: "; text$

PRINT "Enter some text:";


INPUT text$
PRINT "The text you entered was: "; text$

PRINT "Enter some text:";


INPUT text$
PRINT "The text you entered was: "; text$

PRINT "Enter some text:";


INPUT text$
PRINT "The text you entered was: "; text$

PRINT "Enter some text:";


INPUT text$
PRINT "The text you entered was: "; text$

By using a subroutine, the above program can be simplified like this:


CALL GetText
CALL GetText
CALL GetText
CALL GetText
CALL GetText
CALL GetText
CALL GetText

SUB GetText
PRINT "Enter some text:";
INPUT text$
PRINT "The text you entered was: "; text$
END SUB

The following is even more concise:


FOR x = 1 TO 7
CALL GetText
NEXT

SUB GetText
PRINT "Enter some text:";
INPUT text$
PRINT "The text you entered was: "; text$
END SUB

FUNCTIONS
A function is the same as a subroutine, except it returns a value. Also, you must leave out the
CALL command.
To return a value, set a variable with the same name as the function.

PRINT Add(10, 7)

FUNCTION Add (num1, num2)


Add = num1 + num2
END FUNCTION

Output:
17

Since a function can return a value, the name of the function can end with special characters
(see Variable types, Using special characters).
' Notice the dollar sign ($) after "Add." It means
' the function returns a string.

PRINT Add$ ("Hello", "World")

FUNCTION Add$ (str1$, str2$)


Add$ = str1$ + str2$
END FUNCTION

Output:
HelloWorld

You might also like