1. The base and height of a triangle are 15 cm and 10 cm respectively. Write a
program in QBASIC to calculate the area of a triangle.
2. Write a program to input radius of a circle and find the area of a circle.
3. Write a program that converts centigrade temperature to fahrenheit
temperature. The formula is:
F= (9/5)*C+32. F is the fahrenheit temperature and C is the centigrade
temperature.
4. Write a program that calculates the area of a circle. The formula for the area
of a circle is pi times the radius squared.
5. Write a program that calculates the area of a rectangle. The formula for the
area of a circle is length multiplied by breadth.
6. Write a program in BASIC to input the height, base and find out the area of
triangle.
7. Write a program to find the perimeter of a rectangle supplying the length and
breadth.
8. Write a program to calculate the area and circumference of a circle.
9. Write a program to calculate volume and total surface area of a cylinder.
(Hint: vol = pr2h and TSA = 2pr(r+h))
10. In a class of 60 students, 55 are present. Write a program to calculate the
number of students absent and the percentage of absentees.
11. Write a program with READ and DATA statements to find the simple interest
and the amount for the following:
Principal – Rs.800
Time – 3 years
Rate – 5%
12. The cost of petrol is Rs.85 per litre. You have paid Rs.500 to the person
concerned and asked for 5 litres to be filled in the tank. Write a program in
BASIC to calculate the cost of petrol and money refunded.
13. Fine Leather company announces 25% discount on all leather items. You
have purchased a leather jacket that costs Rs.2500 and a belt for Rs.250. Write
a program in BASIC to calculate the amount to be paid to the shopkeeper.
14. Write a program in BASIC to find the simple interest and amount using
INPUT statement.
15. Write a program in BASIC to find the value of the given expressions after
taking the suitable value of a and b from the console.
i. a2 + b2 ii. (a+b)/ab
JBD
Computer Studies-9 201
In the Lab
1. Write a program in BASIC to make a name sticker, which includes your name,
class, roll no., subject and school using INPUT statement.
Display the result as given in the following format:
Output
Name : ________________________
Class : ________________________
R_No : ________________________
Subject : ________________________
School : ________________________
2. Write a program in BASIC to print the total amount paid to the shop keeper
for the following items:
No. of copies purchased = 6
No. of brown rolls = 3
taking the price of each article as INPUT.
3. In an examination, 20% failed in English and 30% failed in Maths. Write a
program in BASIC to find the total failures in both the subjects taking total
number of students in the class as an input.
4. Write a program to print the formatted output as given below :
$1.00
$10.00
$100.00
$1000.00
$10000.00
=========
$11111.00
5. The formula for the final amount of money invested in a bank at compound
interest is:
V=P(1+r)n
P is the principal amount, r is the interest rate in decimal value per year and n
is the time period in years. Write a program to calculate V for various values
of p, r and n.
6. Write a program to input the value of two angles and find out the third angle
of a triangle. (Hint: The sum of all the three angles of a triangle is 180°.)
JBD
202 Computer Studies-9
Chapter 16
QBASIC
CONTROL
STATEMENTS
Objectives
After completing this chapter, you will be able to:
y Define control statement and explain the two categories of control statement.
y Explain the function and syntax of branching statements.
y Explain the function and syntax of looping statements.
y Define counter and accumulator.
y Explain the rules for the formation of nested loop.
C Ooncept verview
The program flow in high-level languages is sequential i.e., they appear in order
from top to bottom. The statement in which these statements are sequentially
executed are called sequential control structure programs. These types of
programs are easy to understand and modify. But not many programs execute all
their statements in strict order from top to bottom. Most of the programs decide
what to do in response to changing circumstances. These programs change the
order of execution of statements or repeat a group of statements until certain
specified conditions are met. These types of programs are useful for storage of
data, manipulation of data and modification of data. QBASIC provides facilities
for controlling the order of execution of statements. They are known as the
program control statements.
The control statements of QBASIC can be put into the following categories:
• Branching statements
• Looping statements
JBD
Computer Studies-9 203
Branching statement
Branching statement is a statement that allows program to transfer the control
to some other specified statement instead of the sequential execution. There are
two types of branching statements: unconditional and conditional branching
statements.
Unconditional branching
The unconditional branching statement allows one to make an absolute jump
to another point in the program. It allows an unconditional transfer of control.
Therefore, the sequence of execution is broken without performing a test and
control is transferred to the target statement having the statement label. The most
commonly used unconditional branching statement is GOTO statement.
GOTO statement
The GOTO statement allows an unconditional transfer of control from one part of
the program to the other without performing a test. The general format of GOTO
statement is:
GOTO [line number | line label]
Where,
line number is the valid line is from 0 to 65,529.
line label is the valid line label starting with a letter.
Solved Examples
REM **Program to find area of rectangle**
top:
INPUT “Enter the length”; l
INPUT “Enter the breadth”; b
LET area = l * b
PRINT “Area of a rectangle”; area
GOTO top
END
In the above program, when the control of execution comes to GOTO top, it will
be again transferred to the label top: A label is a name followed by a colon (:). The
computer will go on asking for more values of l and b because the control will
never come to END statement. So, it becomes an infinite loop (i.e a never-ending
loop). To stop the execution of this program, press CONTROL key and type the
letter C or press Pause Break key.
JBD
204 Computer Studies-9
Conditional branching
Conditional branching statement is a statement that allows selective execution of
statements based on a condition having a certain value. It enables the computer
to decide which of the several possible actions are to be taken. On the basis of a
given condition a selected segment of the program is executed. It depends upon
the state of a particular condition being true or false. The most commonly used
conditional statement is IF...THEN statement. Conditional branching statement
is also called decision-making statement. The most commonly used conditional
branching statements are:
• IF...THEN statement
• SELECT CASE statement
IF...THEN statement
The IF...THEN statement allows branching depending upon the value of an
expression. The statement to be executed or ignored depends upon the condition.
The different forms of IF...THEN statement are:
• IF...THEN statement
• IF...THEN...ELSE statement
• IF...ELSEIF...ENDIF statement
IF...THEN statement
The IF...THEN statement tests a particular condition; if the condition evaluates
to true, a course-of-action is followed i.e., a statement or set-of-statements is
executed. Otherwise (if the condition evaluates to false), the course-of-action is
ignored. The general format of the IF...THEN statement is:
IF <condition> THEN <statement>
Condition? False
True
Statement
JBD
Computer Studies-9 205
Solved Examples
CLS
INPUT “Enter any number”;n
IF n>0 THEN PRINT “Positive Number”
IF n<0 THEN PRINT “Negative Number”
IF n=0 THEN PRINT “Zero”
END
IF...THEN...ELSE statement
The IF...THEN...ELSE is an extension of IF...THEN statement. If the condition
specified after IF is true, then the statement after the THEN statement will be
executed. And if it is false, the statement given next to ELSE will be executed. The
general format of the IF...THEN... ELSE statement is:
IF <condition> THEN <statement1> ELSE_ <statement2>
Entry
True Condition False
Statement1
Statement2
Exit
Solved Examples
CLS
INPUT “Enter the annual salary”; sal
IF sal > 15000 THEN tax = 15 / 100 * sal_ ELSE tax = 10 / 100 * sal
PRINT “The total tax paid by an_ employee:::”; tax
END
The program output with example input shown in bold
Enter the annual salary? 20000
The total tax paid by an employee:::3000
Enter the annual salary? 10000
The total tax paid by an employee:::1000
JBD
206 Computer Studies-9
IF...ELSEIF...ENDIF statement
A common programming statement in QBASIC is the IF...ELSEIF...ENDIF ladder,
which is often called the IF...ELSEIF...ENDIF staircase because of its appearance.
The conditions are evaluated from the top downward. As soon as the condition
evaluates to true, the statement associated with it is executed and the rest of the
ladder is bypassed. If none of the conditions are true, the final else gets executed.
If the final else is missing, no action takes place if all other conditions are false.
The general format of the IF...ELSEIF... ENDIF statement is:
IF <condition1> THEN
<statementblock-1>
ELSEIF <condition2> THEN
<statementblock-2>
ELSE
<statementblock-n>
END IF Select Case exp
Case test1? True Statement1
False
True Statement2
Case test2?
False
Case test3? True Statement3
False
End If
Statement
JBD
Computer Studies-9 207
Solved Examples
INPUT “Enter no. of passenger”; p
INPUT “Enter destination”; d$
IF d$ = “pokhara” THEN
t = 200 * p
ELSEIF d$ = “butwal” THEN
t = 300 * p
ELSEIF d$ = “chitwan” THEN
t = 180 * t
END IF
IF p >= 5 THEN d = 5 / 100 * t
f=t-d
PRINT “Total bus fare=”; f
END
SELECT CASE statement
SELECT CASE statement is a multi-branch selection statement. This selection
statement successively tests the value of an expression against a list of integer or
character constants. When a match is found, the statements associated with that
constant are executed. If the value does not match, the CASE goes on to the next
CASE statement. The general format of SELECT CASE statement is:
SELECT CASE test exp
CASE test 1
statements
CASE test 2
statements
....
CASE ELSE
statements
END SELECT
Where,
test exp is the expression that is evaluated to decide which branch of the SELECT
CASE statement is executed.
test1, test2 are the possible results of the test expression.
statements are QBASIC executable statements that are executed when the test
exp evaluates true for test1 or test2.
JBD
208 Computer Studies-9
Solved Examples
INPUT “Enter the grade (A-D)”; grade$
INPUT “Enter the hours of work”; hrs
SELECT CASE grade$
CASE “A”
totalPay = hrs * 5.35
CASE “B”
totalPay = hrs * 4.85
CASE “C”
totalPay = hrs * 4.35
END SELECT
PRINT “Total Pay=”; totalPay
END
Select Case exp
Case test1? True Statement1
False
Case test2? True Statement1
False
Case test3? True Statement1
False
End Select
JBD
Computer Studies-9 209
Looping statement
The looping statements allow a set of instructions to be performed repeatedly
until a certain condition is fulfilled. The repetition continues while the condition
set for it remains true. When the condition becomes false, the loop ends and the
control is passed to the statement, following the loop. The looping statements
allow the programmer to control the number of times a specific instruction is to
be repeated. The looping statements are also called iteration statements.
QBASIC supports the following looping statements:
• FOR...NEXT
• WHILE...WEND
• DO...LOOP
Loop Counter
Loop counter is the term often used to refer to the variable that controls the
iterations of a loop. The following points should be taken care while using the
counters:
• Initialize the counter by setting it to a starting value.
• Increase/decrease the counter each time the loop is executed.
• The counters have to be checked against the maximum limit of the number of
repetitions required.
Looping with IF...THEN and GOTO
The IF...THEN with GOTO statements can be used to test whether the required
number of repetitions of certain steps have been completed or not. This can be
done with the help of counters.
Solved Examples
REM “Printing Kathmandu ten times”
LET counter = 0
top:
PRINT “Kathmandu”
counter = counter + 1
IF counter< 10 THEN GOTO top
END
Accumulator
Accumulator is a variable that acts as a temporary storage area in the Arithmetic
and Logical Unit (ALU) and in which the result of Arithmetic and Logical
operation is stored. This variable is initialized to zero at the beginning of the
program. The total can be computed by picking a value from the list and adding
to the variable. This process can be repeated till the end of the list.
JBD
210 Computer Studies-9
FOR...NEXT statement
The FOR...NEXT statement is used to execute a series of instructions a given
number of times. The general format of the FOR...NEXT statement is:
FOR variable = x to y <STEP z>
<statements to be executed>
NEXT variable
Where,
variable is a numeric variable that controls the number of repetitions to be
performed.
x is a numeric expression that is the starting value of the counter.
y is a numeric expression that is the final value of the counter.
z is the number that is used to increase or decrease the counter.
Start
Counter variable
= Initial value
Is Counter Execute steps
variable>Final
value?
Counter variable=
Counter variable + 1
Counter variable
moves out of the
loop
If the beginning value of the loop is greater than the ending value, QBASIC does
not repeat the loop but continues at the statement that follows the NEXT.
Solved Examples
REM “To generate numbers from 1 - 5”
FOR I = 1 TO 5
PRINT I ;
NEXT I
END
JBD
Computer Studies-9 211
Program output
12345
In the above program, I is the control variable. 1 is the initial value and 5 is the
final value. Since the STEP is omitted, the value of the control variable is increased
by 1 each time, whenever the loop is repeated. As soon as it exceeds the final
value, the statement after the NEXT statement is executed. The NEXT statement
closes the loop.
EXIT FOR statement
The EXIT FOR statement is used with IF...THEN statement that is included
within the loop. When the EXIT FOR statement is encountered during program
execution, control is immediately transferred out of the FOR...NEXT loop, to the
first statement following the NEXT statement.
Solved Examples
FOR Number = 1 TO 50
PRINT Number
IF Number = 4 THEN
EXIT FOR
END IF
NEXT Number
END
Program output
1
2
3
4
Use the EXIT FOR statement if you want to terminate a loop before its normal
termination. If you want to stop a FOR...NEXT loop before the condition is
satisfied, execute an EXIT FOR statement within the loop.
WHILE...WEND statement
The WHILE...WEND statement is an entry-controlled loop. It allows a block
of statements to be executed repeatedly till the condition is true. The WHILE...
WEND statement has the following syntax:
WHILE <condition>
<program statements>
WEND
JBD
212 Computer Studies-9
The condition can be numeric or logical expression or a variable that WHILE
evaluates. The loop iterates while the condition evaluates to true. When the
condition becomes false, the program control passes to the line after the loop-
body code.
In a WHILE...WEND loop, a loop control variable should be initialized before
the loop begins as an uninitialized variable can be used in a condition. The loop
should be updated inside the body of the WHILE...WEND loop.
Statements
Condition? False
True
Execute body
of loop
Solved Examples
CLS
x=1
WHILE x <= 10
PRINT x ;
x =x +2
WEND
END
DO...LOOP statement
The DO...LOOP statement causes a set of program statements to execute
repeatedly until certain conditions are met or as long as certain conditions are
true. The different variation of DO...LOOP statements are:
a. DO WHILE <condition>
<statement>
LOOP
1. Tests the <condition> first and if true, executes the <statement>.
2. Loops based on condition.
JBD
Computer Studies-9 213
Solved Examples
c=1
DO WHILE c <= 10
PRINT c
c=c+1
LOOP
END
b. DO
<statement>
LOOP WHILE <condition>
1. Executes the <statement> first and then tests the <condition>.
2. Loops at least once, then
tests the <condition>.
Solved Examples
c=1
DO
PRINT c
c=c+1
LOOP WHILE c <= 10
END
c. DO UNTIL <condition>
<statement>.
LOOP
1. Tests the <condition> first and if false, executes the <statement>
2. Loops till the <condition> is
false.
Solved Examples
c=1
DO UNTIL c > 10
PRINT c
c=c+1
LOOP
END
JBD
214 Computer Studies-9
d. DO
<statement>
LOOP UNTIL <condition>
1. Executes the <statement> and then tests the <condition>.
2. Loops at least once, then
tests the <condition>.
Solved Examples
c=1
DO
PRINT c
c=c+1
LOOP UNTIL c > 10
END
EXIT DO statement
The EXIT DO statement can be used to transfer the control out of a DO...LOOP
block. When the EXIT DO statement is encountered during program execution,
control is transferred out of the DO...LOOP block to the first executable statement
following the loop.
Solved Examples
x=1
DO
PRINT x
IF x = 4 THEN
EXIT DO
END IF
x=x+1
LOOP WHILE x <= 50
END
Program output
1
2
3
4
JBD
Computer Studies-9 215
Nested Looping
Nested loop is a logical structure used in computer programming where two
repeating statements are placed in a “nested” form, i.e., one loop is situated within
the body of the other. In a nested loop, the first iteration of the outer loop causes
the inner loop to execute. The inner loop then repeats for as many times as is
specified. When the inner loop completes, the outer loop is executed for its second
iteration, triggering the inner loop again, and so on until the requirements for the
outer loop are complete. The rules for the formation of nested loop are:
• An outer loop and inner loop cannot have the same control variable.
• The inner loop must be completely
nested inside the body of the outer loop.
• The inner loop must terminate before the outer loop.
• Outer loop opens first but closes last.
• Loops must never cross each other.
Solved Examples
FOR i = 1 TO 5
FOR j = 1 TO i
PRINT j;
NEXT
PRINT
NEXT
END
Program output
1
12
123
1234
12345
In the above program, there are two counter variables. The variable i is the outer
loop which has the starting value 1 and the final value is 5. The variable j is
the inner loop which has the starting value 1 and the final value is the counter
variable i. When the value of i is 1 in the beginning, the control is transferred to
the variable j and the variable j will iterate one time. After the completion of inner
loop, the control will be passed to the outer loop. This process continues until
the value of the variable i becomes 5. As soon as it exceeds the final value, the
program ends.
JBD
216 Computer Studies-9
C Dompu- ictionary
Branching statement : A statement that allows program to transfer the
control to some other specified statement instead of
the sequential execution.
Conditional : A statement that allows selective execution of
statements based on a condition having a certain
branching statement value.
Looping statement : A set of instructions to be performed repeatedly until
a certain condition is fulfilled.
Loop counter : The term often used to refer to the variable that controls
the iterations of a loop.
Accumulator : A variable that acts as a temporary storage area in the
Arithmetic and Logical Unit (ALU) and in which the
Recap result of Arithmetic and Logical operation is stored.
• QBASIC provides facilities for controlling the order of execution of statements.
They are known as the program control statements.
• Branching statement allows your program to transfer the control to some other
specified statement instead of the sequential execution.
• The unconditional branching statement allows one to make an absolute jump
to another point in the program.
• The GOTO statement allows an unconditional transfer of control from one
part of the program to the other without performing a test.
• Conditional statement is a statement that allows selective execution of
statements based on a condition having a certain value.
• IF...THEN statement tests a particular condition; if the condition evaluates
to true, a course-of-action is followed i.e., a statement or set-of-statements is
executed.
• SELECT CASE statement successively tests the value of an expression against
a list of integer or character constants.
• The looping statements allow a set of instructions to be performed repeatedly
until a certain condition is fulfilled.
• A counter is a variable which keeps track of the number of times a particular
program or part of the program has been executed.
JBD
Computer Studies-9 217
Review Yourself
1. Answer the following questions.
a. What is a control flow statement? What are the two categories of control
flow statement?
b. What do you mean by branching statement? What is the difference
between conditional and unconditional branching statements?
c. What is a loop counter? How does it differ from accumulator?
d. What is a looping statement?
e. What is nested loop? What are the rules for the formation of nested loop?
f. Write the function and syntax of the following statements:
i. IF...THEN
ii. SELECT...CASE
iii. FOR...NEXT
iv. WHILE...WEND
v. DO...LOOP
2. Debug the following programs.
a. CLS b. INPUT “Enter a number”; n
LET X = 1 m = n
DO DO
LET S = S + X r = n MOD 10
LET X = X + 1 s = s * 10 + r
NEXT X<=10 n = n / 10
PRINT S LOOP WHILE n = 0
END IF m = s THEN
PRINT “Palindrome”
ELSE
PRINT “Not Palindrome”
END
3. Write down the output of following programs.
a. LET sum = 0
FOR c = 1 to 10
LET sum = sum + c
NEXT c
PRINT “The sum is:”;sum
END
JBD
218 Computer Studies-9
b. n = 5 c. CLS
WHILE n <= 25 FOR I = 1 TO 3
c = 1 LET J = 1
WHILE c <= 10 WHILE J < = 4
PRINT n; “x”; c; “=”; n * c LET B = I * J
c = c + 1 PRINT B;
WEND LET J = J + 1
PRINT WEND
N = N + 5 PRINT
WEND NEXT I
END END
4. Rewrite the following programs.
a. (Use FOR...NEXT statement) b. (Use WHILE...WEND statement)
CLS s = 0
LET n=2 FOR ctr = 1 TO 10
LET c=1 s = s + ctr
DO NEXT
PRINT c*n PRINT “The sum is:::”; s
c = c+1 END
LOOP UNTIL c > 10
END
1. Write a program to input three sides of a triangle and determine whether a
triangle can be formed or not.
2. Write a program that identifies and prints a given character as a digit, an
alphabet or any other character.
3. Write a program to input three numbers and find the middle number.
4. A factory gives the following rates of commission for the monthly sales of its
product:
Below Rs.10,000/- 2.5% commission
10001-15000/- 5% commission
15001-20000/- 7.5% commission
Above 20000/- 10% commission
JBD
Computer Studies-9 219
5. Write a program to generate the following pattern:
1
1
123
1234
12345
6. Write a program to print the prime numbers from 1 to 50.
7. Write a program that asks the user for a positive integer value. The program
should use a FOR...NEXT loop to get the sum of all the integers from 1 up to
the number entered. For example, if the user enters 10, the loop will find the
sum of 1, 2, 3, 4, ....10.
8. Write a program to print the multiplication table of 2 to 5 up to 12 multiples
using DO...LOOP nested loop.
9. Write a program to find number of odd and even numbers from “N” input
numbers.
In the Lab
1. The marks obtained by a student in 5 different subjects are input through the
keyboard. The students gets a division as per the following rules:
Per>= 60 ~ First division
Per >=50 and Per<=59 ~ Second division
Per>= 40 and Per<=49 ~ Third division
Per<40 ~ Failed
2. Write to input number of passenger and the destination. The program should
calculate total bus fare and discount according to the following condition.
The rates for different destination is given below:
Destination Rate
Pokhara 250
Butwal 150
Chitwan 100
Number of passengers Discount
Below 5 2.5%
5 or above 5%
JBD
220 Computer Studies-9
3. Write a program to read ten different numbers. Find out prime numbers and
composite numbers using FOR...NEXT statement.
4. Write a program to count the number of digits in a number entered by the
user.
5. Write a program to input a number and check whether it is palindrome or
not.
6. Write a program to input a number and check whether it is armstrong or not.
7. Write a program to find the HCF of any two given numbers.
8. Write a program to print multiplication table of 5,10,15,20 and 25 upto 10
multiples using DO...WHILE statement.
9. Write a program to print 7, 22, 11, 34, 17, 52, 26, 13, 40, 20.
10. Write a program to generate fibonacci series up to ten terms. (Hint: 1,1, 2, 3,
5, 8, 13, 21, 34, 55)
11. Generate the following number patterns:
i. 10 20 30
20 30 40
30 40 50
ii. 1 iii. 1
121 22
12321 333
1234321 4444
123454321 55555
iv. 3 v. 54321
33 5432
333 543
3333 54
33333 5
JBD
Computer Studies-9 221
Chapter 17
LIBRARY
FUNCTIONS
IN QBASIC
Objectives
After completing this chapter, you will be able to:
y Define function and explain the two types of functions in QBASIC.
y Explain the function and syntax of numeric functions.
y Explain the function and syntax of string functions.
y Explain the function and syntax of special functions.
C Ooncept verview
Function is a built-in formula to accomplish certain task such as mathematical,
statistical, financial, logical/data calculations, etc. Functions in QBASIC are
readymade programs which take some data, manipulate them and return the
value, which may be string or numeric type. There are two types of functions in
QBASIC. They are:
a. User Defined Function
User-defined functions are created by the programmer to perform some
operation as per program requirements. User-defined functions may be
numeric or string.
b. Built-in Function
Built-in functions are pre-defined programs provided by QBASIC to perform
some routine and repetitive tasks easily and conveniently. QBASIC offers a
rich set of built-in-functions for manipulating strings, numbers, dates and
time. Built in functions are important and useful as they cut down effort and
time, if one has to write the entire program all over.
JBD
222 Computer Studies-9
User Defined Function
User-defined functions are created by the programmer to perform some operation
as per program requirements. User-defined functions may be numeric or string.
The DEF FN statement is used to define a function. The DEF FN statement must
be executed before the function it defines may be called. If a function is called
before it has been defined, an undefined user function error occurs.
The general format of DEF FN is:
Syntax1 DEF FNname (parameter list) = expression
Syntax2 DEF FNname (parameter list)
[statements]
FNname = expression
[statements]
END DEF
Where,
name is any legal variable name, up to 40 characters long; including any type of
declaration character.
parameter list is a list of variable names, using commas as separators.
expression performs the operation of the function.
Solved Examples
i = 2: j = 3
DEF FNB (x, y) = x ^ 3 / y ^ 2
t = FNB (i, j)
PRINT t
END
Built-in Function
Built-in functions are pre-defined programs provided by BASIC to perform some
routine and repetitive tasks easily and conveniently. Most of these functions
perform their pre-defined operations based on values (data) provided to them
at the time of their use. The values so provided are known as arguments. Built-
in functions may accept one or more arguments. A built-in function returns a
value after performing its pre-defined operation. The value returned by built-in
function is called its return value. A return value may be numeric, alphanumeric
or data and may be stored in an appropriate variable for future reference. There
are three types of built-in functions-numeric functions, string functions, and
special functions.
JBD
Computer Studies-9 223
Numeric Functions
The QBASIC “numeric function” provides an easy and quick way to evaluate
many mathematical functions. Mathematical functions operate upon numeric
expressions. They are referenced by a symbolic name. When they are called, they
return a single value that can be either an integer or a single precision data type.
Some of the commonly used numeric functions are discussed below:
ABS function
The ABS function returns the absolute value i.e. the corresponding positive value
of a numeric expression. It takes a numeric expression as argument.
The general format is:
ABS (x)
Where,
x may be any numeric expression.
For example:
LET M = 32
PRINT ABS(M)
CINT function
CINT function returns the integer nearest to a numeric expression. In other
words, it rounds off the numeric expression to the next integer. It takes a numeric
expression in the range -32768 to 32767 as argument.
The general format is:
CINT (x)
Where,
x may be any numeric expression. If it is
not in range (-32768) - (+32767), an
overflow error occurs.
Solved Examples
REM Demonstrates the use of CINT”
LET M = 127.26+8/2
LET N = -127.26
PRINT CINT(M)
PRINT CINT(N)
END
JBD
224 Computer Studies-9
COS function
The COS function is used to obtain the cosine of x. The calculation of COS is
performed in single precision. To convert degrees to radians, use the formula:
radians = degrees * (PI/180). The general format is:
COS (x)
Where,
x is the angle whose cosine is to be calculated. x must be expressed in r radians.
Solved Examples
PI = 3.141593 : DEGREE=270
RADIANS = DEGREE * PI/180
A = COS (RADIANS)
PRINT A
END
INT function
INT function returns an integer that is smaller then or equal to a numeric
expression. It takes a numeric expression as argument.
The general format is:
INT (x)
Where,
x is any numeric expression.
Solved Example Solved Examples
LET M = 127.26+8/2
LET N = -127.26
PRINT INT (M)
PRINT INT(N)
END
SIN function
The SIN function is used to obtain the sine of x. SIN is calculated in single precision.
To convert degrees to radians, use the formula: radians = degree * (PI/180). The
value of PI is 3.141593. The general format is:
SIN (x)
Where,
x is an angle expressed in radians.
JBD
Computer Studies-9 225
Solved Examples
FOR I = 0 TO 90 STEP 10
Y = 3.14159 * I / 180
PRINT I; TAB(20); SIN(Y)
NEXT
END
SGN function
The SGN function returns the sign of a numeric expression. The general format
is:
SGN (x)
Where,
x is any numeric expression.
Solved Examples
X = 42 : y = 10 : z = -5
a = x – ( y * z)
b = (y + z) * 0
PRINT a, “SGN (A) = “; SGN(a)
PRINT b, “SGN (B) = “; SGN(b)
END
SQR function
SQR function calculates and returns the square root of a non-negative numeric
expression. It takes a non-negative numeric expression as argument.
The general format is:
SQR (x)
Where,
x is a numeric expression that is greater than or equal to zero.
Solved Examples
CLS
INPUT “Length of side a:”; A
INPUT “Length of side b:”; B
C = SQR(A ^ 2 + B ^ 2)
PRINT “The hypotenuse is=”; C
END
JBD
226 Computer Studies-9
TAN function
The TAN function is used to obtain the tangent of x. TAN is calculated in single
precision by default. When the numeric expression is double precision, the
TAN is computed as double precision. If the TAN overflows, the overflow error
message is displayed and execution continues. To convert degrees to radians, use
the formula: radians = degrees * (PI/180). The value of PI is 3.141593. The general
format is:
TAN (x)
Where,
x is an angle expressed in radians.
Solved Examples
REM “Demonstrates the TAN function”
PI = 3.141593:DEGREES = 60
PRINT TAN(DEGREES*PI/180)
END
String Functions
A string is a collection of alphanumeric characters specified within double quotes.
A string is also known as an alphanumeric constant. String functions operate
upon strings and manipulate them. These are called string manipulators, since
they manipulate or rearrange the values within a string.
ASC function
The ASC function returns the ASCII code corresponding to the character of
a string. ASCII is an acronym for American Standard Cord for Information
Interchange. ASCII code is a numeric value between-128 and 127 that is used to
represent a character internally in the computer. ASC function takes a string as
argument.
The syntax is as follows:
ASC (string)
Where,
string may be any string expression.
Solved Examples
Exp$ = “Prep”
For Cnt = 1 TO LEN (Exp$)
PRINT ASC (MID$(Exp$, Cnt, 1)) “ “;
NEXT Cnt
END
JBD
Computer Studies-9 227
CHR$ function
CHR$ function returns a character that corresponds to a specific ASCII values. It
takes a number between-128 and 127 as argument. The general format of CHR$
function is:
CHR$ (n)
Where,
n is a value from 0 to 255.
Solved Examples
FOR I = 1 TO 255
PRINT I “=” CHR$ (i) ;
NEXT
END
INSTR function
INSTR function searches for one string inside another and returns the position of
the first character of the former in the latter, if found. The general format is:
INSTR ([n,] x$ , y$)
Where,
n is an integer expression. n, if specified, sets the position for starting the search.
If n is not specified, BASIC uses the
default value of 1. If n is out of range, the “Illegal function call” error message
will be returned.
Solved Examples
Exp$ = “Prep”
For Cnt = 1 TO LEN (Exp$)
PRINT ASC (MID$(Exp$, Cnt, 1)) “ “;
NEXT Cnt
END
CHR$ function
CHR$ function returns a character that corresponds to a specific ASCII values. It
takes a number between-128 and 127 as argument. The general format of CHR$
function is:
CHR$ (n)
Where,
n is a value from 0 to 255.
JBD
228 Computer Studies-9
Solved Examples
FOR I = 1 TO 255
PRINT I “=” CHR$ (i) ;
NEXT
END
INSTR function
INSTR function searches for one string inside another and returns the position of
the first character of the former in the latter, if found. The general format is:
INSTR ([n,] x$ , y$)
Where,
n is an integer expression. n, if specified, sets the position for starting the search.
If n is not specified, BASIC uses the
default value of 1. If n is out of range, the “Illegal function call” error message
will be returned.
Solved Examples
FStr$=”12345.0909”
PRINT INSTR (FStr$,”.”)
PRINT INSTR (6,FStr$, “.”)
END
LEN function
LEN is a string processing function. LEN function counts and returns the total
number of characters in a string.
It takes one argument, a string whose characters are to be counted.
The general format is:
LEN (string expression)
or
LEN (variable)
Where,
string expression is a string expression or literal.
variable is a valid BASIC variable name, can be of any type.
JBD
Computer Studies-9 229
Solved Examples
INPUT “Enter a string”; s$
FOR i = 1 TO LEN(s$)
a$ = MID$(s$, i, 1)
PRINT a$, ASC(a$)
NEXT
END
LEFT$ function
LEFT$ function extracts and returns a specific number of characters from the left
of a string. The general format is:
LEFT$ (string expression, n)
Where,
string expression is a string constant, string variable or string expression.
n is an integer expression in the range
0 - 32767 that specifies the number of characters to be extracted from left-hand
side of the string. If n equals zero, the null string (length zero) is returned.
Solved Examples
CLS
A$ = “NEPAL”
FOR I = 1 TO LEN(A$)
PRINT LEFT$(A$, I)
NEXT I
END
RIGHT$ function
RIGHT$ function extracts and returns a specific number of characters from the
right of a string. The general format is:
RIGHT$ (string expression, n)
Where,
string expression is a string constant, string variable or string expression.
n is an integer expression in the range
0 - 32767 that specifies the number of characters to be extracted from the right-hand
side of the string. If n equals zero, the null string (length zero) is returned.
JBD
230 Computer Studies-9
Solved Examples
CLS
INPUT “Enter a string”; A$
FOR C = 1 TO LEN(A$)
PRINT RIGHT$(A$, C)
NEXT C
END
MID$ function
MID$ function extracts and returns a specific number of characters from within a
string. The general format is:
Syntax 1
MID$ (string expression, start, length)
Where,
string expression is the string from which the sub-string has to be extracted.
start is the starting position to extract from the string expression.
length is the number of characters to extract.
Syntax 2
MID$ (string variable, start, length) = string expression
Where,
string variable is the string whose characters will be replaced.
start is the starting position for replacement in the target string.
length is an optional parameter that specifies the number of characters to be
replaced. If not specified, the entire string expression is used.
string expression is the replacement string.
Solved Examples
CLS
INPUT “Enter the string:”; A$
C=1
FOR I = 1 TO LEN(A$)
IF MID$(A$, I, 1) = “ “ THEN C = C + 1
NEXT I
PRINT “No. of words in the string=”; C
END
JBD
Computer Studies-9 231
SPACE$ function
SPACE$ function returns a string of spaces of a specified length. The general
format is:
SPACE$ (n)
Where,
n is an integer expression in the range
0-32,767. Solved Examples
FOR I = 1 TO 5
X$ = SPACE$ (I)
PRINT X$ , I
NEXT I
END
STR$ function
STR$ function converts a numeric expression into a string and returns the
same.
It takes a numeric expression as argument. The general format is:
STR$ (x)
Where,
x is any numeric expression.
Solved Examples
CLS
REM “To demonstrate STR$ function”
LET n = (8 * 3)/6
PRINT STR$(n)
END
STRING$ function
STRING$ function returns a string of specified length constructed of a given
ASCII character. The general format is:
STRING$ (n, m | x$)
Where,
n is a numeric expression between 1 and 32767, specifying the length of the string
requested. m is the numeric expression between 0 and 255 for the character to be
used in building the string.
x$ is any string expression; the first character from the string expression is used
to construct the string.
JBD
232 Computer Studies-9
Solved Examples
FOR I = 1 TO 10
PRINT STRING$(I, “*”)
NEXT
END
VAL function
VAL function returns the numeric equivalent of the first character of a string. It
takes a string as an argument. Arithmetic operations are possible on the value
returned by VAL. If the first character of a string is not numeric, then VAL will
return a 0. The general format is:
VAL (x$)
Where,
x$ is any string expression.
LTRIM$ and RTRIM$ functions
The LTRIM$ and RTRIM$ functions remove leading and trailing blanks
respectively from the string expressions. The general format is:
LTRIM$ (string expression)
Where,
string expression can be any string
variable, string constant or an expression yielding a string.
Solved Examples
CLS
A$ = “ Fun with “
B$ = “Programming”
C$ = A$ + B$
PRINT “-Before LTRIM and RTRIM-”
PRINT C$
PRINT
PRINT “-After LTRIM and RTRIM-”
A$ = LTRIM$(A$)
A$ = RTRIM$(A$)
C$ = A$ + B$
PRINT C$
END
JBD
Computer Studies-9 233
LCASE$ and UCASE$ functions
The LCASE$ and UCASE$ functions convert string values to lowercase and
uppercase, respectively. The general format is:
LCASE$ (string expression)
UCASE$ (string expression)
Where,
string expression can be any string
variable, string constant or an expression yielding a string. These functions accept
both fixed and variable length strings as parameters.
DATE$ statement
The DATE$ statement is used to set or retrieve the current date. The general
format is:
Syntax
To set the current date
DATE$ = string
string is the current date that will be assigned to DATE$.
Syntax
To retrieve the current date
variable = DATE$
variable is a valid string variable to which the current date will be assigned.
Solved Examples
DIM M$(12)
FOR M = 1 TO 12
READ M$(M)
NEXT M
PRINT “The system date is = “; DATE$
D$ = DATE$
MON$ = M$(VAL(D$))
DAY$ = MID$(D$, 4, 2)
YEAR$ = MID$(D$, 7, 4)
PRINT “The modified date is = “; DAY$;_ “th”; “ “; MON$; “ “; YEAR$
DATA JAN, FEB, MAR, APR, MAY, JUN,_ JUL, AUG, SEPT, OCT, NOV, DEC
END
JBD
234 Computer Studies-9
TIME$ statement
The TIME$ statement is used to set or retrieve the current time. The general
format is:
Syntax To set the curent time
TIME$ = string
string is the current time that will be assigned to TIME$.
Syntax To retrieve the current time
variable = TIME$
variable is a string variable to which the current time will be assigned.
Solved Examples
KEY OFF:CLS
TOP:
LOCATE 25, 5
PRINT DATE$, TIME$
BOTTOM:
T$=RIGHT$(TIME$,2)
IF T$=”59” THEN GOTO TOP
GOTO BOTTOM
END
INKEY$ function
The INKEY$ function is used to read a character from the keyboard buffer. It reads
only one character even if there are several characters waiting in the keyboard
buffer. The value returned by INKEY$ is a zero-, one-, or two-character string.
The general format is:
INKEY$
Solved Examples
PRINT “Press any key to continue”
A$=INKEY$
top:
IF A$ = “ “ THEN GOTO top
END
The first line displays a message that calls for the user to press a key. In fourth
line, a character is read from the keyboard and is assigned to A$. Then A$ is
tested. If it is a null string, which means that no character has been pressed, the
program line is repeated. The fourth line will continue to be executed until a
character is read from the keyboard.
JBD
Computer Studies-9 235
C Dompu- ictionary
Function : A built-in formula to accomplish certain
task such as mathematical, statistical,
User Defined Function : financial, logical/data calculations, etc.
Built-in Function : The functions that are created by the
programmer to perform some operation as
per program requirements.
The pre-defined programs provided by
QBASIC to perform some routine and
repetitive tasks easily and conveniently.
Recap
• Built-in functions are pre-defined programs provided by BASIC to perform
some routine and repetitive tasks easily and conveniently.
• The DEF FN statement is used to define a function.
• The ABS function returns the absolute value i.e. the corresponding positive
value of a numeric expression.
• CINT function returns the integer nearest to a numeric expression.
• The COS function is used to obtain the cosine of x.
• INT function returns an integer that is smaller then or equal to a numeric
expression.
• The SIN function is used to obtain the sine of x.
• The SGN function returns the sign of a numeric expression.
• SQR function calculates and returns the square root of a non-negative numeric
expression.
• The TAN function is used to obtain the tangent of x.
• The ASC function returns the ASCII code corresponding to the character of a
string.
• CHR$ function returns a character that corresponds to a specific ASCII values.
• LEN function counts and returns the total number of characters in a string.
• LEFT$ function extracts and returns a specific number of characters from the
left of a string.
• The TIME$ statement is used to set or retrieve the current time.
JBD
236 Computer Studies-9
Review Yourself
1. Answer the following questions.
a. What is a function?
b. What is the difference between user-defined function and built-in
function?
c. What is a numeric function?
d. What are string manipulators? What purpose do they serve?
e. Write the function and syntax of the following QBASIC keywords.
i. SGN ii. CHR$ iii. RIGHT$
iv. MID$ v. DATE$ vi. INKEY$
2. Debug the following program. b.
a. s$ = “NEPAL”
D$=”Kathmandu” L = LEN (S$)
FOR i = 1 TO LEN(a$) FOR i = L TO 1
PRINT RIGHT$(s$, 1) C$ = LEFT$(S$, i, 1)
WEND R$ = R$ + C$
END NEXT i
PRINT C$
END
c. d.
INPUT s$ = “NEPAL” INPUT A$
FOR i = 1 TO LENGTHs$) C=1
PRINT MID$(s$, 5) FOR I = 1 TO LEN(A$)
NEXT IF MID$(A$, I, 1) = “ “ THEN
END C=C+1
NEXT I
PRINT C
END
JBD
Computer Studies-9 237
3. Write down the output of following programs.
a. b.
A$ = “NEPAL” s$=”Himalayas”
B = 0 FOR i = 1 TO LEN(s$)
FOR I = LEN(A$) TO 1 STEP -1 a$ = UCASE$(MID$(s$, i, 1))
PRINT TAB(B + 4); RIGHT$(A$, I) SELECT CASE a$
B = B + 1 CASE “A”, “E”, “I”, “O”, “U”
NEXT I c=c+1
END END SELECT
NEXT
PRINT “Number of vowels”; c
END
c. d.
p = 4 A$ = “NEPAL”
e = 1 FOR I = 1 TO LEN(A$)
t = 40 PRINT LEFT$(A$, I)
FOR i = 1 TO 4 NEXT I
PRINT TAB(t); MID$(a$, p, e) END
p=p-1
e=e+2
t=t-1
NEXT
END
1. Write a program to input a number and reverse it.
2. Write a program to input a number and find the sum of its individual digits.
3. Write a program to input a number and check whether it is palindrome or
not.
4. Write a program to input a number and check whether it is armstrong or not.
5. Write a program to input a number and check if the number is prime or
composite.
6. Write a program to input two numbers and find the greatest common divisor.
7. Write a program in BASIC to input a string and reverse it.
JBD
238 Computer Studies-9
8. Palindrome words are those which spell the same from both the sides. Write
a BASIC program to check whether input word is a palindrome or not.
9. Write a program to input a string and count the total number of vowels
present in an input string.
10. Write a program to input a string and print the alternate characters in
capital letters.(Hint: If your input is “kathmandu” then the output should
be “KaThMaNdU”).
11. Write a program to input sentence and count number of words and characters
in an input string.
12. Write a program to input a string and count the number of words in
it.
13 . Write a program to print the following patterns on the screen.
a. * b. N
* * * N E
* * * * * N E P
* * * * * * * N E P A
N E P A L
c. N E P A L d. N
E P A L E
P A L P
A L A
L L
e. P R O G R A M f. 1
R O G R A 121
O G R 12 321
G 1234321
14. Write a program using DEF FN statement to calculate simple interest for a
given principle, rate and time of interest.
15. Write a program to print a table of Sin x, Cos x and Tan x for the angles from
0° to 90° in step 5°.
16. Write a program to input a number (ASCII code) and print the ASCII
character of the same number.
JBD
Computer Studies-9 239
In the Lab
1. Write a program to evaluate the magnitude of a vector. The magnitude of a
vector is given below:
3x2 + y2 + z2
2. Write a program to generate the following number pattern on the screen:
1 2 3 4 5 4 3 2 1 L
1 2 3 4 3 2 1 A L
1 2 3 2 1 P A L
1 2 1 E P A L
1 N E P A L
3. Write a program to count the number of words in a sentence. And also find
the average length of a word in the sentence.
4. Write a program to input a sentence and print the position of the first vowel
if present in the string and print the message “No vowel” if the string does
not contain any vowel.
5. Write a program to input time in seconds and convert seconds into exact
number of hours, minutes and seconds.
6. Write a program in BASIC to input a string and reverse it.
7. Palindrome words are those which spell the same from both the sides. Write
a BASIC program to check whether input word is a palindrome or not.
8. Write a program to input a string and count the total number of vowels
present in an input string.
9. Write a program to count the occurrence of letters A and D in the supplied
sentence.
10. Write a program to input a string and print whether initial character is a
number or uppercase or lowercase characters.
11. Write a program to input a string and print the alternate characters in
capital letters.(Hint: If your input is “kathmandu” then the output should be
“KaThMaNdU”).
12. Write a program to input a number and reverse it.
13. Write a program to input a number and find the sum of its individual digits.
JBD
240 Computer Studies-9
Chapter 18
ARRAYS
IN
QBASIC
Objectives
After completing this chapter, you will be able to:
y Define an array and explain how to declare array in QBASIC.
y Explain the two types of array in QBASIC.
y Explain the function and syntax of DIM statement.
y Explain the process of searching and sorting an array.
C Ooncept verview
A variable can store only one data value at a time but if there is a need to store many
related data values simultaneously in the memory for the purpose of processing
them together, it is not a good programming practice to create separate variables
for storing each value. The solution to this kind of problem is an array. Arrays
play an important role in problem solving whenever a large number of variables
are used.
An array is a collection of variables of the same type that are referenced by a
common name. Each array element has a distinct position in the array. All the
elements of an array have the same data type. Each element of an array can be
referred by an array name and its subscript. The subscript number specifies the
position of an element within the array (also called the index of the element).
JBD
Computer Studies-9 241
The table given below shows the memory space requirements of arrays in
QBASIC.
Arrays Required Bytes of Storage
Integer 2 per element
Integer 2 per element
Single-precision 4 per element
Double precision 8 per element
String Number of characters in the string plus 3 bytes
per element.
Array Declaration
The DIM statement is used to declare an array and to establish the maximum
number of elements in an array. The general form of the DIM statement is:
DIM variable (subscripts) [, variable (subscripts)] …
Where,
Variable must be a valid variable name. It can be a string variable (to define a string
array), an integer variable, a single precision numeric variable, or a double precision
numeric variable.
Subscripts are any valid integer expressions which, when evaluated, will be rounded to
positive integer value. This positive integer value will then become the maximum number
of elements associated with that specific array name.
The maximum number of dimensions is 255. The maximum number of elements per
dimension is 32767.
An array can also be declared without the use of the DIM statement. When BASIC
encounters a subscripted variable that has not been defined with a DIM statement, it will
assume a maximum subscript of 10.
Option Base statement
The minimum subscript for an array element is assumed to be 0. Consequently, the
statement DIM A (10) actually established an 11 –element array, A (0)-A (10). The
OPTION BASE statements can be used to establish the minimum array subscript value as
0 or 1. The following example illustrates the use of the OPTION BASE statement to set
the minimum value of an array subscript to 1.
OPTION BASE 1
DIM A (10)
This example will establish a 10-element array, A (1)-A (10).
The OPTION BASE statements must appear before any DIM statement is executed or
before any subscripted variable is referenced. An attempt to use the OPTION BASE
statements after an array has already been established will result in a Duplicate
Definition error message.
JBD
242 Computer Studies-9
Types of Arrays
Arrays are broadly classified into different types based on the need of the
program. The classifications are based on the number of data elements required.
The different types of arrays that QBASIC uses are:
Single Dimensional Array
The simplest form of an array is a single dimensional array. An array whose
elements are specified by a single subscript is known as a single dimensional
array. Single dimensional arrays are used in order to process data items of the
same type.
The general syntax is as follows:
DIM <variable_name> (<dimension size>)
Memory representation of single dimension arrays
Single-dimension arrays are essentially list of information of the same type and
their elements are stored in contiguous memory location in their index order.
For instance,
DIM ar$ (5)
The above array declaration will create an array for storing six strings and will
assign six different storage locations for the variable ar$. Initially, all the elements
will have null string value. Here is a schematic representation:
arr$ (0) arr$ (1) arr$ (2) arr$ (3) arr$ (4) arr$ (5)
Solved Example Solved Examples JBD
DIM N(9) Computer Studies-9 243
FOR J = 1 TO 3
FOR K = 1 TO 3
READ N(K)
PRINT N(K),
NEXT
PRINT
NEXT J
DATA 2,4,6,3,6,8,4,7,9
END
Two-Dimensional Array
Two dimensional array is an array in which each element is itself an array. For
instance, an array DIM A(m,n) is an m by n table with m rows and n columns
containing m x n elements. The number of elements in a 2-D array can be
determined by multiplying number of rows with number of columns. For
example, the number of elements in an array DIM A(3,3) is calculated as 3 x 3 = 9.
Row 1 A (1, 1) A (1, 2) A (1, 3)
Row 2 A (2, 1) A (2, 2) A (2, 3)
Row 3 A (3, 1) A (3, 2) A (3, 3)
The general format is as follows:
DIM <variable_name> (<No.of rows, No. of columns>)
Memory representation of single dimension arrays
Two-dimensional arrays are stored in a row-column matrix, where the first index
indicates the row and the second indicates the column. This means the second
index (i.e., column) changes faster than the first index (i.e., row) when accessing
the elements in the array in the order in which they are actually stored in memory.
Solved Examples
DIM N(3, 4)
REM outer loop for rows
FOR J = 1 TO 3
REM inner loop for columns
FOR K = 1 TO 4
READ N(J, K)
PRINT N(J, K),
NEXT
REM to move cursor to the next line
PRINT
NEXT
REM to find sum
PRINT “========================”
FOR J = 1 TO 4
REM inner loop for columns
SUM = 0
FOR K = 1 TO 3
SUM = SUM + N(K, J)
NEXT
END
JBD
244 Computer Studies-9
Searching
Once information is stored in a list or table, it can be searched to look for a
particular piece of information. For example, if you have your friend’s name and
phone number stored in an array. This array can be searched on name to find
the phone number of a particular friend. This process of searching an array for
a particular data is called “table lookup”. The item you search for (e.g. friends
name) is called the “search key” and the data (name) which contain the key is
called the “table key”.
The two common algorithm for searching the contents of an array are:
Serial search
Serial search scans all the data from top to bottom, one by one, until a match for
the required data is found or the end of table is reached. If a match is found then
all the required information of that row is printed otherwise a message is printed
that the required data is not found in the table.
Solved Examples
DIM size(10)
FOR i = 1 TO 10
INPUT size(i)
NEXT
POSITION = -1
INPUT “Element to be searched”; X
FOR I = 1 TO 10
IF (SIZE(I)) = X THEN POSITION = I
NEXT
IF (POSITION > -1) THEN
PRINT “The position is “; POSITION
ELSE
PRINT “Unsuccessful search”
END IF
END
JBD
Computer Studies-9 245
Solved Examples
OPTION BASE 1
DIM NAM$(5), TEL$(5)
FOR T = 1 TO 5
READ NAM$(T), TEL$(T)
NEXT
TOP:
INPUT “Enter friend’s name”; N$
IF N$ = “end” OR N$ = “END” THEN_ GOTO AA
MIN = 1: MAX = 5: I = INT(MAX / 2)
WHILE MIN <= MAX
IF N$ > NAM$(I) THEN MIN = I + 1
IF N$ < NAM$(I) THEN MAX = I - 1
IF N$ = NAM$(I) THEN GOTO LAST
I = INT(MIN + MAX) / 2
WEND
PRINT “Sorry, no match found...”
GOTO BOTTOM
LAST:
PRINT “Friend’s number is=”; TEL$(I)
BOTTOM:
PRINT “Press any key to retry....”
X$ = INPUT$(1)
PRINT : GOTO TOP
AA:
END
DATA Suren, 4233233, Kiran, 4223443_
Pritam, 4248773, Dinesh, 4222277, Hari,_ 4267722
JBD
246 Computer Studies-9
C Dompu- ictionary
Array : A collection of variables of the same type
that are referenced by a common name.
Subscript number : The position of an element within the array
(also called the index of the element).
Single Dimensional Array : An array whose elements are specified
by a single subscript is known as a single
dimensional array.
Two Dimensional Array : An array in which each element is itself an
array.
Recap
• An array is a collection of variables of the same type that are referenced by a
common name.
• The DIM statement is used to declare an array and to establish the maximum
number of elements in an array.
• The subscript number specifies the position of an element within the array
(also called the index of the element).
• The OPTION BASE statements must appear before any DIM statement is executed
or before any subscripted variable is referenced.
• An array whose elements are specified by a single subscript is known as a
single dimensional array.
• A two dimensional array is an array in which each element is itself an array.
• Two-dimensional arrays are stored in a row-column matrix, where the first
index indicates the row and the second indicates the column.
• Once information is stored in a list or table, it can be searched to look for a
particular piece of information.
• Serial search scans all the data from top to bottom, one by one, until a match
for the required data is found or the end of table is reached.
• Binary search is little complicated compared to a serial search but the time
required to search for a particular information is greatly reduced when the
binary search is used.
JBD
Computer Studies-9 247
Review Yourself
1. Answer the following questions.
a. What is an array?
b. What is meant by single dimensional array and multidimensional array?
c. How are arrays defined in programs? Give the syntax with suitable examples.
d. What is the function and syntax of DIM statement?
e. What is serial search? How does it differ from binary search?
f. What do you mean by bubble sorting?
2. Write the output of the following programs.
a. CLS
OPTION BASE 1
DIM X$(7)
FOR T=1 TO 7
READ X$(T)
NEXT T
FOR A=1 TO 7
PRINT TAB(40-(A));
FOR B=1 TO A*2
PRINT X$(A);
NEXT B
PRINT
NEXT A
DATA Q,-,B, A, S, I, C
b. DIM N(9)
FOR J = 1 TO 3
SUM = 0
FOR K = 1 TO 3
READ N(K)
SUM = SUM + N(K)
PRINT N(K),
NEXT
PRINT “=”; SUM
NEXT J
DATA 2,4,6,3,6,8,4,7,9
END
JBD
248 Computer Studies-9
c. CLS
DIM A(10)
FOR C = 1 TO 10
READ A(C)
NEXT C
DATA 23, 45, 23, 67 , 4 , 5 , 6 , 2 , 9 , 57
FOR X = 1 TO 10
FOR Y = 10-X
IF A(Y) < A (Y+1) THEN
SWAP A(Y), A(Y+1)
ENDIF
NEXT Y
NEXT X
FOR J = 1 TO 10
PRINT A(J);
NEXT J
END
3. Read the following program and answer the given questions.
a.
CLS
DIM A(15)
INPUT N
FOR I = 1 TO N
INPUT A(I)
NEXT I
FOR I = 1 TO N
FOR J = 1 TO N-1
IF A(J) >= A(J+1) THEN
TEMP = A (J)
A(J) = A(J+1)
A(J+1) = TEMP
END IF
NEXT J
NEXT I
FOR I = 1 TO N
PRINT A(I)
NEXT I
END
JBD
Computer Studies-9 249
a. How many numbers is the program able to process?
b. What happens if you type 16 number?
c. What modification is required in the program to accept 16 numbers?
d. If the input numbers are 7 , 23 , 6 , 8 , 1 and 12, write down the output?
b.
CLS
DIM A(3,4)
FOR I = 1 TO 3
S= 0
FOR J = 1 TO 4
READ A(I,J)
S = S+ A(I,J)
PRINT A(I,J);
NEXT J
PRINT “=” ; S
NEXT J
DATA 10 , 20 , 30 , 40
DATA 20 , 30 , 40 , 50
DATA 30 , 40 , 50 , 60
a. Write down the output of the above program.
b. Count the number of variable declared in the above program.
c. What is the meaning of DIM A(3,4)?
d. What is the purpose of READ...DATA statement?
4. Write down the program for the following problems.
a. Write a program in BASIC to accept marks of five students and display
them using an array.
b. Write a program in BASIC to input the age of 5 students. Print the
total number of students whose age is less than or equal to 18 and
greater than 18 using DIM statement.
c. Write a program to read 10 numbers and print their sum.
d. Write a program to read 5 numbers using single dimension and count
the even numbers separately.
e. Write a program to read 10 numbers using single dimension and find
the sum of odd and even numbers separately.
JBD
250 Computer Studies-9