Approved by Curriculum Development Centre 201 Oasis Radiant Computer Science, Book 9 CLS INPUT “Enter Your percentage”; Per SELECT CASE Per CASE IS >= 90 PRINT “You Got A+” CASE 80 TO 89 PRINT “You Got A” CASE 70 TO 79 PRINT “You Got B+” CASE 60 TO 69 PRINT “You Got B” CASE 50 TO 59 PRINT “You Got C+” CASE 40 TO 49 PRINT “You Got C” CASE ELSE PRINT “Sorry, very low grade” END SELECT END LOOP Structure: Looping is the repeated execution of a statement or block of statements many times without recording them. The loop is repeated as long as the given conditional is satisfied. It is terminated when the given condition is not satisfied. A loop becomes an infinite loop if it never terminates. In QBASIC, there are three looping statements. They are: i) FOR…NEXT ii) WHILE…WEND iii) DO…LOOP
Oasis Radiant Computer Science, Book 9 202 Approved by Curriculum Development Centre i) FOR…NEXT Loop. It repeats a statement or a block of statements for a specified number of times. The statements are written in between FOR and NEXT. Syntax: FOR <counter>=<Initial value> TO <Sentinel value> <Step value> Statement(s) NEXT <counter> Here, counter is a numeric variable that controls the loop. It is also called control variable. The execution of the loop begins by specifying the initial, sentinel and step values. If step value is not defined, QBASIC assumes STEP as ‘1’ by default and will increase the value of computer variable by 1. Example 1: Programme to print first 20 natural numbers horizontally. CLS FOR I = 1 to 20 PRINT I; NEXT I END Example 2: Programme to print all Odd numbers from 49 to 5. CLS FOR I = 49 to 5 step -2 PRINT I; NEXT I END Example 3: Programme to print your school’s name 20 times. CLS INPUT “Enter your school’s name”; N$ FOR I = 1 to 20 PRINT “My school’s name is”; N$ NEXT I
Approved by Curriculum Development Centre 203 Oasis Radiant Computer Science, Book 9 END EXIT FOR Statement This statement exits a FOR loop Syntax: EXIT FOR Example:- FOR A= 1 TO 20 STEP 1 PRINT A; IF A= 14 THEN EXIT FOR NEXT A ii) WHILE…WEND Loop. WHILE…WEND looping structure executes a series of statement as long as the given condition is true. If the condition is false, the loop terminates and other statements following WHILE…WEND statements are executed. The ‘WHILE’ keyword is followed by the condition. Syntax: <Initial Value> WHILE < Condition> <statement> <step Value> WEND Example 1: Programme to print even numbers from 2 to 50. CLS I = 2 WHILE I<=20 PRINT I; I= I+2 WEND END Example 2: Programme to generate the series 7, 14, 21………….70 CLS
Oasis Radiant Computer Science, Book 9 204 Approved by Curriculum Development Centre I = 7 WHILE I<= 70 PRINT I; I=I+7 WEND END Example 3: Programme to print sum of 1 to n numbers. CLS INPUT “Enter any number”; N I= 1 S= 0 WHILE I<=N S=S+I I=I+1 WEND PRINT S END iii) DO…LOOP It repeats a statement or a block of statements while a condition is true or until a condition becomes false. The WHILE or UNTIL keyword (any one of them) is used with DO…LOOP. If we used ‘WHILE’, the loop terminates when the given condition evaluates to false whereas if we use ‘UNTIL’, the loop terminates when the given condition evaluates to true. Syntax: DO {WHILE/UNTIL} Statement or statements block LOOP OR DO Statement or statements block LOOP {WHILE /UNTIL}
Approved by Curriculum Development Centre 205 Oasis Radiant Computer Science, Book 9 EXIT DO Statement This statement ends a DO loop. Syntax: N= 1 DO PRINT N; IF N=8 THEN EXIT DO N= N+1 LOOP WHILE N<=10 Example 1: Programme to print first 20 odd numbers. a. Using DO WHILE…LOOP b. Using DO…LOOP WHILE CLS CLS I = 1 I = 1 A= 1 A= 1 DO WHILE I <=20 Do PRINT A; PRINT A; I=I+1 I=I+1 A=A+2 A=A+2 LOOP LOOP WHILE I<=20 END END c. Using DO UNTIL…LOOP d. Using DO…LOOP UNTIL CLS CLS I=1 I=1 A=1 A=1 DO UNTIL I> 20 DO PRINT A; PRINT A; I=I+1 I=I+1 A=A+2 A=A+2
Oasis Radiant Computer Science, Book 9 206 Approved by Curriculum Development Centre LOOP LOOP UNTIL I >20 END END NESTED LOOP A loop within a loop is called a nested loop. One kind of looping statement can contain another same or different type of looping statement. The looping statement can be nested at any level deep. Syntax: FOR <counter1>=<Initial value> TO <Sentinel value> [step value] [statement block] FOR <counter2>=<Initial value> TO <Sentinel value> [step value] [statement block] NEXT [counter2] [statement block] NEXT [counter1] Example: Programme to print the following series. 5 4 4 3 3 3 2 2 2 2 1 1 1 1 1 CLS FOR I= 5 TO 1 STEP -1 FOR J= 5 TO I STEP -1 PRINT I; NEXT J PRINT NEXT I END Sample programmes. REM programme to find the perimeter of a rectangle. CLS
Approved by Curriculum Development Centre 207 Oasis Radiant Computer Science, Book 9 INPUT “Enter length of a rectangle”; l INPUT “Enter breath of a rectangle”; b p= 2 *(l + b) PRINT “Perimeter of rectangle=”; p END REM to find the simple interest and amount. CLS INPUT “Enter principle”; p INPUT “Enter rate”; r INPUT “Enter time”; t si= (p* t* r) / 100 a= p + si PRINT “Simple interest=”; si PRINT “Amount=”; a END REM Programme to enter any three numbers and print the middle number. CLS INPUT “Enter first number”; A INPUT “Enter second number”; B INPUT “ Enter third number”; C IF (A>B AND A<C) OR (A<B AND A>C) THEN M=A IF (B>A AND B<C) OR (B<A AND B>C) THEN M = B IF (C> A AND C<B) OR (C<A AND C>B) THEN M = C PRINT “The Middle number is”; M END REM Programme that will read the percentage and display the position. CLS INPUT “Enter your percentage”; P IF P>= 80 THEN
Oasis Radiant Computer Science, Book 9 208 Approved by Curriculum Development Centre PRINT “You passed with Distinction” ELSEIF P >= 60 THEN PRINT “You passed with First division” ELSEIF P >=45 THEN PRINT “You passed with Second division” ELSEIF P>=32 THEN PRINT “You passed with Third division” ELSE PRINT “You Failed” END IF END Programme to generate the following series. 3 33 333 3333 33333 Solution: CLS A=3 FORI=1TO5 PRINT A; A=A*10+3 NEXT I END Programme to generate the following series. 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 Solution: CLS A= 5
Approved by Curriculum Development Centre 209 Oasis Radiant Computer Science, Book 9 DO UNTIL A <1 B= A DO UNTIL B < 1 PRINT B; B= B-1 LOOP A= A-1 PRINT LOOP END Programme to generate the following series. 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 Solution: CLS A=5 FORI=1TO5 PRINT A A=A*10+5 NEXT I END Programme to generate the following series. 1 4 9 16 25………….up to 10th term. Solution: CLS A= 1
Oasis Radiant Computer Science, Book 9 210 Approved by Curriculum Development Centre WHILE A< =10 PRINT A ^ 2 A=A+1 WEND END Programme to generate the following series. 1 1 0 1 0 1 1 0 1 0 1 0 1 0 1 Solution: CLS FOR I = 1 TO 5 FOR J = 1 TO I PRINT J MOD 2; NEXT J PRINT NEXT I END Functions IN QBASIC. Functions are ready-made programmes which take some data, manipulate them and return either numeric or string value. They are the programmes that calculate or manipulate data and return a value. In other words, a function is a built-in formula to perform a certain task. Once a function is written, it can be used again and again. There are two types of functions supported by QBASIC. They are: a. User defined functions b. Library or built-in functions
Approved by Curriculum Development Centre 211 Oasis Radiant Computer Science, Book 9 a) User defined functions: This function is written by the programmer to do specific tasks. We can use FUNCTION…END FUNCTION statement to create a user defined function. b) Library or built-in functions: Library functions are functions provided by the QBASIC to do a specific task. Library function can be called (used) by the user according to the requirement. Some common examples of library functions are LEN, LEFT$, SQR and so no. Library functions are classified into two types. They are: a. String manipulation functions b. Mathematical calculation functions a) String manipulation Functions: Strings functions are used to manipulate or compute string type of data and return a single value. Some of the string functions are explained below. I) ASC FUNCTION This function returns the ASCII code for corresponding specified character. Syntax: ASC(String Character) Example: PRINT ASC(“A”) II) CHR$ FUNCTION This function returns the character corresponding to a specified ASCII code. Syntax: CHR$(ascil-code%) Example: PRINT CHR$(65) III) LEFT$ FUNCTION This function is used to extract or return the specified number of characters from the left side of the given string. Syntax: LEFT$ (String expression, number) Example: PRINT LEFT$(“Nepal”, 4)
Oasis Radiant Computer Science, Book 9 212 Approved by Curriculum Development Centre IV) RIGHT$ Function This function is used to extract or return the specified number of characters from the right side of the given string. Syntax: RIGHT$(String expression, number) Example: PRINT RIGHT$ (“Pokhara”, 3) V) MID$ FUNCTION This function is used to extract the specified number of characters from the given position of the string. Syntax: MID$ (String expression, position, number) Example: PRINT MID$ (“KATHMANDU”, 3, 4) VI) LEN FUNCTION This function is used to find the length of the given string by counting the numbers of characters that are enclosed in quotes or assigned to string variable. Syntax: LEN (String expression) Example: PRINT LEN (“TECHNOLOGY”) VII) LTRIM$, RTRIM$ FUNCTIONS Remove leading and trailing spaces from a string. Syntax: LTRIM$ (Stringexpression$) RTRIM$ (stringexpression$) Example: N$= “ SWARNIM “ PRINT “*” + N$ + “*” PRINT “*” + LTRIM$(a$) + “*” PRINT “*” + RTRIM$(a$) + “*” VIII) VAL FUNCTION This function is used to charge the string representation of a number into a numerical value. If the first character of the string is non-numeric, it returns 0.
Approved by Curriculum Development Centre 213 Oasis Radiant Computer Science, Book 9 Syntax: VAL (String expression) Example: PRINT VAL (“061 POKHARA”) PRINT VAL (“NEPAL” 977”) IX) STR$ FUNCTION STR$ returns a sting representation of a number. Syntax: STR$ (numeric-expression) Example: PRINT STR$(41) X) STRING$ FUNCTION Returns a string of a specified length made up of a repeating character. Syntax: PRINT STRING$ (length%, stringexpression$) Example: PRINT STRING$(5, “*”); PRINT “SWARNIM”; PRINT STRING$(5, “*”) XI) SPACE$ FUNCTION Returns a string of spaces. Syntax: SPACE$(n%) Example: FOR i% = 1 TO 5 x$ = SPACE$ (i%) PRINT x$; i% NEXT i% XII) UCASE$ FUNCTION This function is used to convert the given string into upper case.
Oasis Radiant Computer Science, Book 9 214 Approved by Curriculum Development Centre Syntax: UCASE$ (String expression) Example: PRINT UCASE$ (“Microsoft Corporation”) Output: MICROSOFT CORPORATION V$= “NePalGuNj” PRINT UCASE$(V$) XIII) INSTR Returns the position of the first occurrence of a string in another string. Syntax: INSTR ([start%,] stringexpression1$, stringexpression2$) Example: a$= “Microsoft QBasic” PRINT “String position=”; INSTR (1, a$, “QBasic”) XIV) LCASE$ FUNCTION This function is used to convert the given string into lower case. Syntax: LCASE$ (string) Example: PRINT LCASE$ (“FEWALAKE”) XV) DATE$ FUNCTION The DATE$ function returns the computer’s current system date. Syntax: DATE$ Example: PRINT DATE$ XVI) TIME$ FUNCTION The TIME$ function returns the computer’s current system time. Syntax: TIME$ Example: PRINT TIME$ TIME$ = “10:55:38”
Approved by Curriculum Development Centre 215 Oasis Radiant Computer Science, Book 9 ‘Note: The new system time remains in effect until’ you change it again. PRINT “Time set to”; TIME$ b. Mathematical Calculation Functions:- Numeric functions are used to manipulate numeric type of data and return a single value. They are used for mathematical computations. Some mathematical functions are explained below: I) ABS FUNCTION It returns the absolute value of a numeric expression. Syntax: ABS (numeric expression) Example: PRINT ABS (-53.6) PRINT ABS (4-9) II) SIN FUNCTION It returns the sine value of an angle. Syntax: SIN (numeric expression) Example: PRINT SIN (45) III) COS FUNCTION It returns the cosine value of an angle. Syntax: COS (numeric expression) Example: PRINT COS (45) III) TAN FUNCTION It returns the tangent value of an angle. Syntax: TAN (numeric expression) Example: PRINT TAN (45) IV) SQR FUNCTION It returns the square root of a positive numeric expression. Syntax: SQR (numeric expression) Example: PRINT SQR (81) PRINT SQR (49)
Oasis Radiant Computer Science, Book 9 216 Approved by Curriculum Development Centre V) INT FUNCTION It returns the integer part of a number after removing the decimal part of given numeric expression. It rounds down the number. Syntax: INT (numeric expression) Example: PRINT INT (37.3) PRINT INT (99.999) PRINT INT (-6.3) VI) SGN FUNCTION It returns a value that indicates the sign of the given numeric expression. It returns 1 for the positive numbers, -1 for the negative numbers and 0 for the number 0. Syntax: SGN (numeric expression) Example: PRINT SGN (7 + 5) PRINT SGN (3 - 8) Points to remember • Statements are the group of commands given to the computer to perform some actions. • Input/ Output statements give data to the computer and get results from the computer. • Declaration statements declare a variable in the programme. • The statements which are used to assign a numeric or sting value to a variable are called assignment statements. • The statements which are used to control the flow of execution of the programme statement(s) are called control flow statements. • Branching and jumping take the programme from one location to another within a programme. • The term looping means repeated execution of a sequence of statements in a programme. • A loop inside another loop is called a nested loop. • Logical operators are used to combine two or more expressions containing relational operators. • An expression can be a variable or constant or combination of constants, variables and operators.
Approved by Curriculum Development Centre 217 Oasis Radiant Computer Science, Book 9 Exercises 1. Fill in the blanks. a. IF…THEN statement is………………………..statement. b. FOR…NEXT is……………..….statement. c. READ statement is followed by………………..statement. d. DIM statement is especially created to declare…………variables. e. A loop inside another loop is called a…………………………….. 2. Write whether the following statements are True or False. a. The WHILE or UNTIL keyword can be used in DO…….LOOP. b. LET is an optional statement. c. A loop repeats statements till the given conditional is satisfied. d. DATA is an be executable statement. e. ? sign can be used in place of PRINT statement. 3. Write the use and syntax for the following statements. a. DIM statements: b. IF….THEN statement c. GOTO d. DO….LOOP e. READ…DATA statement f. LET statement g. FOR…NEXT statement 4. Answer the following questions. a. In how many groups are the QABSIC statements categorised? List them. b. Show declaration statements with examples. c. Can the number of data in the DATA statement be more than the number of variables in READ statement? Explain. d. Define control statement. Give some examples. e. What is looping? Write the types of loop used in QBASIC. f. What is a nested loop? g. A loop becomes endless, if it is not terminated. Why? h. Write the syntax, use and function of the following. i. INT() ii. CINT() iii. LEFT$() vi. MID$() v. VAL() vi. UCASE$() vii. RTRIM$( ) viii. SPACE$( ) ix. CHR$( ) x. LTRIM$( )
Oasis Radiant Computer Science, Book 9 218 Approved by Curriculum Development Centre i. What is the difference between Dates and function and Date$ Statement. j. Differentiate between Tiimes$ function and statement. 5. Write programmes to do the following. a. Input three different numbers and print their sum and product. b. Input length and print the perimeter of a square. c. Input Nepali currency and convert it into Indian currency. d. Input a number and check whether the input number is a palindrome or not [a number which is read same from both sides is a palindrome number. For example: 12321]. e. Input a number and check whether the input number is Armstrong number or not. [if the sum of cubes of each individual digit of a number is equal to the original number itself, then it is called Armstrong number. For example: 153=13 + 53 +33 . So, the number 153 is Armstrong number.] f. Input a string and check whether the input string is palindrome or not. [a word which is read same from both the sides is palindrome. For example: NAYAN]. g. Check whether the input number is Prime or Composite. h. Display “ New Nepal” 10 times using WHILE…WEND. i. Print the first 25 even numbers using DO… LOOP. j. Find out the factorial of a given number using FOR…NEXT. k. Input marks of all your subjects and print total, percentage, result and division. l. Find the area of a cube [Hints A=6l2]. m. Find the curved surface area of a cylinder. [Hints A=2rh]. n. Find the total surface area of a cylinder. [Hints A=2r(r+h)]. o. Calculate the distance travelled by body. [Hints S=ut+1/2at2]. p. Input the temperature in degree Fahrenheit and display in degree Celsius. [Hints F=9C/5+32]. q. Input a number and check whether it is a perfect square or not. r. Find the occurrence of character in another string. s. Input sales amount and calculate commission on the following basics: Sales Amount Commission <=5000 10% >5000 15%
Approved by Curriculum Development Centre 219 Oasis Radiant Computer Science, Book 9 6. Write a programme to generate the following series. a. 2, 4, 6, 8……………..up to 10th term. b. 1, 8, 27, 64…………..up to 10th term. c. 100, 98, 96, 94…………….up to 10th term. d. 1, 4, 9………….up to 10th term. e. 5, 25, 125…………..up to 5th term. f. 1, 2, 3, 6, 11, 20, 37,…………….up to 10th term. g. 5, 16, 8, 4, 2, 1, 4, 2, 1, 4. h. 66666, 6666, 666, 66, 6. i. 2, 8, 18, 32,…………….up to 10th term. 7. Write a programme to display the given output. a. 54321 b. 11111 c. 12345 4321 2222 1234 321 333 123 21 44 12 1 5 1 d. 5 e. 1 f. 5 54 13 44 543 135 333 5432 1357 2222 54321 11111 8. Write the output for the following. a. CLS b. CLS A= 15 LET C= 1 B= 20 WHILE C<= 5 C= 30 PRINT C; SWAP A, B C= C+1 PRINT A, B, C WEND END END c. CLS d. CLS A= 1 FOR I= 5 TO 1 STEP -1 X= 1 FOR J= 5 TO I STEP -1 DO WHILE A<=3 PRINT J;
Oasis Radiant Computer Science, Book 9 220 Approved by Curriculum Development Centre PRINT X NEXT J X=X*10+1 PRINT A=A+1 NEXT I: END LOOP END e. CLS N$, = “COMPUTER” A$, = LEFT$, (N$, 2) B$, = RIGHT$ (N$,3) PRINT A$;B$, END 9. Debug the following programmes. a. CLS REM Program to sum given two numbers INPUT “Enter first number”; t TYPE “Enter second number”; p SUM= t + z Display SUM End b. REM to display the sum given equivalent of decimal number CLS INPUT “Enter a decimal number’; d WHILE d=0 r= d MOD 2 s$= VAL (r) +s$ d= d\ 10 WEND x= STR$(s$) PRINT “The equivalent binary is”; x END c. CLEAR N= 365 WHILE N>0 R= N/10 X= X * 10+R N= N\10 NEXT DISPLAY X END
Approved by Curriculum Development Centre 221 Oasis Radiant Computer Science, Book 9 d. CLS A$= “LIRIL” FOR S= L TO LENGTH (A$) B$= A$= MID$ (A$, I, 1) WEND IF A$= B$ THEN PRINT “ Palindrome” ELSER PRINT “NOT” END IF THE END 10. Study the given programme and answer the following questions. a. CLS FORJ=5TO1 PRINT J, PRINT NEXT J END i. What is the Iteration statement used in the above programme? ii. If we replace comma sign with semi column, what type of output will we get? b. CLS M$= “COMPUTER” C= LEN (M$) B= 1 WHILE B<C PRINT MID$(M$, B, 1); B=B+2 WEND END i. List out the numeric and string variables used in the above programme. ii. What will happen if the statement B=B+2 is removed from the programme?
Oasis Radiant Computer Science, Book 9 222 Approved by Curriculum Development Centre Chapter 13 Arrays in Basic ffl Programming with Arrays ffl The DIM statement ffl Some projects with array THIS CHAPTER COVERS :
Approved by Curriculum Development Centre 223 Oasis Radiant Computer Science, Book 9 Arrays in Basic 13 Chapter In all our programmes so far, a single variable (one storage location in internal memory) has been associated with each variable name. In this lesson, we will discuss the concept of an array: a collection of variables, all of which are referenced by the same name. We will discuss one-dimensional arrays (lists) and two-dimensional arrays (tables), concentrating on the former. Each item of data in an array does not have a unique variable name, on the other hand, a group of similar data is given one name. The smallest component of an array is called an element of the array. Advantages of an Array. • Use of array reduces the number of variables used in the programme. • Once we enter data in a programme using array, we can use them many times without reentering them. • Using array, programmes can be made more efficient. • Searching and sorting of data can be done easily. Example 1: Suppose we want to represent five numbers (10,12,42,91,7,) which represent the marks of five students. Solution: We can use an array name M(I) which is also called the subscripted variable and I is the subscript which varies from 1 to 5. M is the name of array and M(1) is an element of the array M. In the memory it is stored as, M(I) Cells Quantities M(1) 10 M(2) 12 M(3) 42 M(4) 91 M(5) 7
Oasis Radiant Computer Science, Book 9 224 Approved by Curriculum Development Centre Problem 1: Write a programme to read the above data into the memory. Program 1 DIM M(5) FOR I = 1 TO 5 READ M(I) NEXT I DATA 10,12,42,91,7 END Let us go back to the above example. M is an array of 5 numbers 10,12,42,91,7, where under the array name M the five different elements M(1),M(2), M(3), M(4), M(5), are given one subscript I. This M(I), with a single subscript I, is an example of a one-dimensional array. Let us study a practical example of one-dimensional array. Example 2: We have an item, that is, biscuit in a shop. We have prices for 10 different biscuits as 60, 45.5, 32.6, 19.5, 52, 49,53.75, 29, 43, 38.6. We write a programme to print these different values or we want to know the price of any type of the above biscuits. We will do it by using an array. Solution: Since they are similar items, we give them a single name BISCUIT or in short BIS. Since we know only one specification i.e. price we have a single subscript, say I. So the array is now BIS(I). Since there are 10 prices for 10 types of biscuits I varies from 1 to 10 i.e. BIS(1), BIS(2)…….BIS(10). If we want to know the price for the biscuit of type 4, we will print BIS(4) which will give us the required price. Program 2 DIM BIS(10) FOR I = 1 TO 10 READ BIS(I) NEXT I
Approved by Curriculum Development Centre 225 Oasis Radiant Computer Science, Book 9 PRINT “THE PRICES OF TEN DIFFERENT BISCUITS” FOR I =1 TO 10 PRINT BIS(I) NEXT I DATA 60,45.5, 32.6, 19.5, 52,49,53.75 DATA 29,43,38.6 END OUTPUT THE PRICES OF TEN DIFFERENT BISCUITS 60 45.5 32.6 19.5 52 49 53.75 29 43 38.6 DIM BIS(10) is compulsory. This informs the machine that we are giving an array with single subscript having 10 elements. So, 10 cells in the memory location will be kept for the variable name BIS. If we want an array of strings instead of numeric value, see the following example: Example 3 To store the names of six motor cars in any array (table) such as: REM DECLARE THE NAME AND SIZE OF THE TABLE DIM C$(6) REM… USE THE READ/DATA TECHNIQUE FOR J = 1 TO 6 READ C$(J) NEXT J DATA “FORD”, “MARUTI”, “AMBASSADOR” DATA “FIAT”, “STANDARD”, “VAUXHALL” END
Oasis Radiant Computer Science, Book 9 226 Approved by Curriculum Development Centre C$(1) = “FORD” C$(2) = “MARUTI” C$(3) = “AMBASSADOR” C$(4) = “FIAT” C$(5) = “STANDARD” C$(6) = “VAUXHAULL” Example 4 Let the 10 data values are given as 4, -6, 7, 2.3, - 6.1, 5. 3 -1, 0, - 2.7, 9. We give this set of values the name, say VAR (I) where I is the subscript. If I = 1, then VAR (1) has the value 4 I = 5, then VAR (5) has the value -6.1 I = 8 then VAR (8) has the value 0, and so on. The program for adding all the 10 numbers. Program 4 REM ADDING 10 NUMBERS IN A ONE DIMENSIONAL TABLE DIM VAR (10) LET SUM = 0 FOR I = 1 TO 10 READ VAR (I) LET SUM = SUM +VAR (I) NEXT I DATA 4, -6,7, 2.3, -6.1, 5.3, -1, 0, -2.7,9 PRINT SUM END The DIM Statement When subscripted variables are used in a programme, certain information about them must be supplied to the computer before it is used. These are: (a) Which variables are subscripted? (b) What is the maximum size for each subscript?
Approved by Curriculum Development Centre 227 Oasis Radiant Computer Science, Book 9 DIM is the short form of DIMENSION. By using this statement in line number 10 of the programme 1 above, the array whose name is M has been allotted 5 cells in the memory location. Syntax for the DIM statement is Line number DIM array name (unsigned integer) The unsigned integer specifies the size of the array variable. If we write 10 DIM A(100), X(10), then 100 locations are reserved for the array name A and 10 locations for the array name X. DIM should be the first statement in the programme barring REM statement. Problem 5 Suppose we want to read the roll number of a student and his marks obtained in five subjects in the board examination. Now print the roll number and average marks secured by him. DIM M(5) INPUT ROLLNO LET TOT = 0 FOR I = 1 TO 5 READ M(I) LET TOT = TOT + M(I) NEXT I LET AVERAGE = TOT/5 PRINT ROLLNO, AVERAGE DATA 60,52,49,80,72 END On the execution of line number 30, initially the control variable I becomes 1 and line number 40 reads M(I), i.e. the first mark from line number 90, that is 60 and adds to the variable TOT which is initially zero. So for I = 1 line 50 gives TOT = 0 +60 = 60, control then goes to line number 60 and back to 30. Now I becomes 2 and line number 40 reads M(2), i.e. 2nd mark from DATA, i.e. 52. In line number 50 TOT = 60 + M(2), i.e. TOT = 60+52 = 112 and so on. So line number 30 to 60 is executed five times. Thus finally in the variable name TOT we have TOT =
Oasis Radiant Computer Science, Book 9 228 Approved by Curriculum Development Centre 60+52+49+80+72=313. So, when line number 70 is executed AVERAGE = 313/5 =62.6. Line number 80 will print the ROLLNO which is entered in line number 20 and the AVERAGE as 62.6. If we want to apply this process for a large number of students say 10 we have to give more data in DATA statement, i.e. 45 more data values and put another loop to repeat the process for ten students. Programme DIM M (5) FOR J = 1 TO 10 INPUT ROLLNO LET TOT =0 FOR I = 1 TO 5 READ M (I) LET TOT = TOT + M(I) NEXT I LET AVERAGE = TOT/5 PRINT ROLLNO, AVERAGE NEXT J DATA 60,52,49,80,72,98,69,72,80,75 DATA 88,61,54,48,60,52,92,86,81,65 DATA _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ DATA _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ DATA _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ END Double-Subscripts or two-dimensional arrays A subscripted variable name in BASIC can have up to three subscripts. The use of two subscripts has very wide applications, especially manipulation of tables or
Approved by Curriculum Development Centre 229 Oasis Radiant Computer Science, Book 9 any such things, which has rows and columns both in it. Example: Represent subscripted variable or two-dimensional array having name TABLE(I.,J) where I indicates row and J indicates column. Where, TABLE (I,J) = 2 4 8 10 1 3 5 7 3 7 13 17 Thus we see TABLE (I,J) has 3 rows, i.e. I = 1 TO 3 and 4 columns, i.e. J = 1 TO 4. Problem We want to read and print the values of TABLE (I,J) as given above Programme DIM TABLE (3,4) FOR I = 1 TO 3 FOR J = 1 TO 4 READ TABLE (I,J) PRINT TABLE (I,J) NEXT J NEXT I DATA 2,4,8,10,1,3,5,7,3,7,13,17, END Programme DIM TABLE (3,4) FOR J =1 TO 4 FOR I =1 TO 3 READ TABLE (I, J) NEXT I NEXT J DATA 2, 1, 3, 4, 3, 7, 8, 5, 13, 10, 7, 17 END
Oasis Radiant Computer Science, Book 9 230 Approved by Curriculum Development Centre More applications relating to subscripted variables will be shown in the last section. We have shown you how to store numeric data in a table (array) with row and column subscripts. Now, you will see how string data is stored in a two-dimensional array. Example The following are data values (names), which are to be stored in the table form with rows and columns. HARIOM DINESH RAJESH PANKAJ BIMLA UPMA SANJU ANAMIKA The programme is as follows: Programme REM DECLARE THE NAME AND SIZE OF THE TABLE 20 DIM N$ (2,4) REM SET UP AN OUTER LOOP TO CONTROL THE ROW SUBSCRIPT FOR M = 1 TO 2 REM…..SET UPAN INNER LOOPTO CONTROLTHE COLUMN SUBSCRIPT FOR P = 1 TO 4 REM .. USE A READ/DATA STATEMENT TO STORE DATA AS REM .. SHOWN IN DIAGRAM READ N$ (M, P) NEXT P NEXT M DATA “HARIOM”, “DINESH” “RAJESH” DATA “PANKAJ”, “BIMLA” DATA “UPMA”, “SANJU”, “ANAMIKA” END
Approved by Curriculum Development Centre 231 Oasis Radiant Computer Science, Book 9 Example: REM read the data from DATA statement and print them in tabular form 1 2 3 4 5 6 7 8 9 10 11 12 DIM N (3, 4) AS INTEGER FORI=1TO3 FORJ=1TO4 READ N (I, J) NEXT J NEXT I PRINT “Printing data in tabular form” FORI=1TO3 FORJ=1TO4 PRINT N (I, J); NEXT J PRINT NEXT I DATA 1,2,3,4,5,6,7,8,9,10,11,12 END Single Dimensional Array. An array having a single subscript is known as single dimensional array that represents series of the same type of data. The data may be of numbers or strings arranged in single row or single column. For example DIM Pal(5). Elements of array Pal (1) Pal (2) Pal (3) Pal (4) Pal (5) Data stored 10 40 20 5 30 Array Declaration. DIM statement is used to declare an array variable. An array variable can also be used without using DIM statement. But, it can store maxi-mum of 11 elements (0 to 10).
Oasis Radiant Computer Science, Book 9 232 Approved by Curriculum Development Centre DIM statement. The DIM statement is used to declare an array variable or simple vari-able. The syntax of DIM statement is: DIM variable_name (subscripts) [AS Data-type] Where, Variable_name is the name of array variable. Subscripts are numeric variables or numeric constants to declare the maximum elements of an array. [AS Data-type] declares the data type of an array variable. Examples: Example 1 : REM Simple program to print the values of any five variables REM The following program does not use array CLS A= 2 B= 4 C= 6 D= 8 E= 10 PRINT A, B, C, D, E END The output will be. 2 4 6 8 10 Example 2 : REM above program using array CLS DIM N (5) N(1)=2 N(2)=4 N(3)=6 N(4)=8
Approved by Curriculum Development Centre 233 Oasis Radiant Computer Science, Book 9 N(5)=10 PRINT N (1), N (2), N (3), N (4), N (5) END The output will be; 2 4 6 8 10 Example 3: REM Program using array to print five integer values DIM Num (5) AS INTEGER CLS Num (1) = 10 Num (2) = 15 Num (3) = 50 Num (4) = 2 Num (5) = 19 PRINT Num (1) PRINT Num (2) PRINT Num (3) PRINT Num (4) PRINT Num (5) END The output will be: 10 15 50 2 19 Example 4 : REM Program using array to printer five string values DIM Names (5) AS STRING CLS Names (1) = “Rohit”
Oasis Radiant Computer Science, Book 9 234 Approved by Curriculum Development Centre Names (2) = “Santosh” Names (3) = “Aashish” Names (4) = “Krishna” Names (5) = “Puskal” PRINT Names (1) PRINT Names (2) PRINT Names (3) PRINT Names (4) PRINT Names (5) END The output will be: Rohit Santosh Aashish Krishish Puskal Example 5 : REM Program to input any 10 numbers and print their sum using array. CLS DIM Num (10) Sum = 0 FORI=1TO10 INPUT “Enter a number:”; Num (I) Sum = Sum + Num (I) NEXT I PRINT “The sum is:”; Sum END OPTION BASE Statement. OPTION BASE statement is used to define the lower bound value for an array. This statement is used before declaring array.
Approved by Curriculum Development Centre 235 Oasis Radiant Computer Science, Book 9 Syntax: OPTION BASE n Where, n is a number whose value is either 0 or 1. By default, the lower bound is 0 Example 6: REM program to print the biggest and smallest numbers among 10 input numbers. OPTION BASE 1 DIM Num (10) FORI=1TO10 INPUT “Enter a number:”; Num(I) NEXT I LET BIG = Num (1) LET SMALL = Num (1) FORJ=2TO10 IF Num (J)>BIG THEN BIG = Num(J) IF Num (J)<SMALL THEN SMALL = Num(J) NEXT J PRINT “Biggest number is:” BIG PRINT “Smallest number is:”; SMALL Data sorting using Array. Sorting is the process of arranging data either in ascending or descend-ing order. The sorted data are more meaningful as compared to unsort-ed data. We use several sorting techniques to sort the elements of an array. For example: an array named symbol number contains the five symbol number as follows. Symbol numbers: 2054 2052 2053 2051 2055 tersorting the above symbol numbers in ascending order, the values of the array will be as follows:
Oasis Radiant Computer Science, Book 9 236 Approved by Curriculum Development Centre Sorted symbol numbers: 2051 2052 2053 2054 2055 There are many method for sorting the data of an array like: i. Bubble sorting. ii. Selection sorting. i. Bubble Sorting. In this method of sorting, data are sorted by comparing the adjacent val-ues and putting in ascending or descending order. This method is suit-able for easier and quicker sorting for less number of items. If we want to sort the items in ascending order, the first value is compared with the second value. If the first value is greater than the second, then the val-ues are interchanged. If the first value is smaller than the second, then they are left as they are. In the second step, the current second value is compared with the third value. If the second value is greater, interchange will be done otherwise they are left as they are. This process continues until the second last value is compared with the last value. At the end of all these first round of steps, the last values would be sorted. In the next round, comparison is done for the rest of the values. In this round, the third last value is sorted. In this way, all the values are sorted in n-1 round where n is the number of items to be sorted. SWAP Statement. SWAP statement is used to exchange the values of any two same vari-ables of the same type. Syntax: SWAP var1, var2 Example 7 : REM program to sort the numbers in ascending order DIM Num (10) FOR I= 1 TO 10 READ Num (I) NEXT I FOR I= 1 TO 10
Approved by Curriculum Development Centre 237 Oasis Radiant Computer Science, Book 9 FOR J= 1 TO 10-I IF Num (J)>Num (J+1) THEN SWAP Num (J), Num (J+1) NEXT J NEXT I FOR P= 1 TO 10 PRINT Num (P) NEXT P DATA 20, 25, 14, 84, 99, 47, 1, 54, 65, 4 END String Sorting. String sorting is done by comparing the first character of the string with the first character of another string. If the first character of both the string are same, the second characters are compared. Computer uses the AS-CII value of characters to compare strings. Example 8 : REM program to sort string in descending order. DIM Num (10) AS STRING FOR I= 1 TO 10 READ Num (I) NEXT I FORI=1TO10 FOR J = 1 TO 10-I IF Num (J) <Num (J+1) THEN TEMP$= Num(J) Num (J) = Num (J+1) Num (J+1) = TEMP$ END IF
Oasis Radiant Computer Science, Book 9 238 Approved by Curriculum Development Centre NEXT J NEXT I CLS REM to print sorted strings FORP=1TO10 PRINT Num (P) NEXT P DATA YAM, KRISHNA, GAJENDRA, KABITA, MINA, UMESH, DATA SAGAR, SIRJANA, RAJU, RICHA b. Selection sort. In selection sort method, in order to sort the numbers in an ascending order, first the smallest number is selected from the array and it is stored in the first location of the array. In next step, the smallest number among the rest is selected and is stored in the second location of the array or not. The basic search techniques are sequential search and binary search. Example 9 : REM search name in the list OPTION BASE 1 DIM Num (10) AS STRING FOR P= 1 TO 10 READ Num (P) NEXT P DATA SAMIKSHYA, PRATIKSHYA, JYOTI, UTSAV, ROSHAN, PRAKASH DATA GOVINDA, BIDIT, SUBIN, SISHIR INPUT “Enter a name:”; Name$ FOR P= 1 TO 10 IF UCASE$(Name$) = Num(P) THEN FOUND= 1 PRINT “The name is found in the list” EXIT FOR END IF NEXT P
Approved by Curriculum Development Centre 239 Oasis Radiant Computer Science, Book 9 IF Found “SORRY, name is not found in the list” END Double Dimensional Array. An array using two subscripts to store the data in the form of table ma-trix is called double dimensional array. Two subscripts are used for de-claring double dimensional array; one for row and another for column. Syntax: DIM Array_name (row, column) [AS TYPE] Where, row and column specify the number of rows and columns in the table. For example: DIM N (3, 4) AS INTERGER This defines a two dimensional array with 3 row and 4 columns and stores altogether 12 data. The value to the double dimensional array can be done as follows: N(1,1)=10 N(1,2)=15 N(1,3)=20 N(1,4)=25 N(2,1)=30 N(2,2)=35 N(2,3)=40 N(2,4)=45 N(3,1)=50 N(3,2)=55 N(3,3)=60 N(3,4)=65
Oasis Radiant Computer Science, Book 9 240 Approved by Curriculum Development Centre Example 10 : REM read the data from DATA statement and printing them in tabular from OPTION BASE 1 DIM N (3, 4) AS INTEGER FORI=1TO3 FORJ=1TO4 READ N (I, J) NEXT J NEXT I PRINT “Printing data in tabular form” FORI=1TO3 FORJ=1TO4 PRINT N (I, J); NEXT J PRINT NEXT I DATA 1,2,3,4,5,6,7,8,9,10,11,12 END The output will be Printing data in tabular from 1 2 3 4 5 6 7 8 9 10 11 12 Example: CLS REM to read numbers and print matrix addition DIM A (2, 2), B(2, 2), C(2, 2) PRINT “FIRST MATRIX” FOR I=1TO 2 FOR J= 1 TO 2 READ A(I,J) PRINT A(I,J) NEXT J
Approved by Curriculum Development Centre 241 Oasis Radiant Computer Science, Book 9 PRINT NEXT I PRINT “SECOND MATRIX” FOR I=1 TO 2 FOR J= 1 TO 2 READ B(I,J) PRINT B(I,J) NEXT J PRINT NEXT I PRINT “SUM MATRIX” FOR I= 1 TO 2 FOR J= 1 TO 2 C(I,J)=A(I,J)+B(I,J) PRINT C(I,J); NEXT J PRINT NEXT I DATA 1,2,3,4,5,6,7,8 END
Oasis Radiant Computer Science, Book 9 242 Approved by Curriculum Development Centre Points to remember • An array reduces the number of variables in a programme because a single array can store large numbers of data. • An array is the collection of similar data items that can be represented by a single variable name. A subscript or index value is used to identify the position of a particular element in the array. • The DIM statement is used to declare an array variable in the programme. • By using arrays, we can access any data item efficiently just by specifying the index of that item. • Array variable stores data of the same data type. • Array variable may be of numeric or string type. • Array variable name should be unique in a program. • Variables, Constants or expressions can be written as subscript Exercises 1. State whether the following statements are true or false: a. An array is the collection of different types of data items. b. A subscript is used to identify the position of a particular element in the array. c. The REM statement is used to declare an array variable in the programme. d. The maximum number of dimensions allowed in a DIM statement is 50. e. Every data item of an array is called array element. 2. Answer the following questions: a. What is an array? Write its importance in a programme. b. What are the advantages of using array in the programme? 3. Write QBASIC programmes to solve the following problems by using arrays. a. Find the smallest number among the 5 numbers entered by a user. b. Find the largest number among the 10 numbers entered by a user. c. Store the names of SAARC countries and their capital city and print them. d. Input age of 15 persons then count the number of persons having the age of more than 15 years and less than 25 years, more than 25 years and upto 50 years and beyond 50 years.
Approved by Curriculum Development Centre 243 Oasis Radiant Computer Science, Book 9 Full Forms ABBS = Any Branch Banking Service ABC = Atanasoff Berry Computer Al = Artificial Intelligence ALU = Arithmetic and Logic Unit AMD = Advance Micro Devices ANSI = American National Standard Institute ASCC = Automatic Sequence Controlled Calculator ASCU = American Standard Code for Information Interchange ATM = Automated Teller Machine BASIC = Beginners All Purpose Symbolic Instruction Code BCD = Binary Coded Decimal BCR = Bar Code Reader BIOS = Basic Input Output System BIT = Binary Digit BPO = Business Process Outsourcing Byte = Binary Digit Eight CAD = Computer Aided Design CAI = Computer Aided Instructions. CAL = Computer Aided Learning CAN = Computer Association of Nepal CBT = Computer Based Training CCTLD = Country Code Top Level Domain CDC = Control Data Cyber CD-ROM = Compact Disk Read Only Memory
Oasis Radiant Computer Science, Book 9 244 Approved by Curriculum Development Centre CD-RW = Compact Disk Read and Write CISC = Complex Instructions Set Computing COBOL = Common Business Oriented Language. CUM = Control Program for Microcomputer CPU = Central Processing Unit CRT = Cathode Ray Tube CU = Control Unit DOR = Double Data Road DOS = Device Driver Software DEC = Digital Equipment Corporation DRAM = Dynamic. Random Access Memory DVD-RW = Digital Versatile Disk Read and Write EBCDIC = Extended Binary Coded Decimal Interchange Code E-commerce = ELectronic Commerce EDSAC = Electronic Delay Storage Automatic Computer EDVAC = Electronic Discrete Variable Automatic EEPROM = Electrically and Erasable Programmable ROM EHTP = Electronic Hardware Technology Park E-mail = Electronic Mail ENIAC = Electronic Numerical Integrator And Calculator EPROM = Erasable and Programmable Read Only Memory FAT = File Allocation Table FMC = Flight Management Computer FORTRAN = Formula Translation GiGO = Garbage In Garbage Out GIS = Geographical Information System GPL = General Public License
Approved by Curriculum Development Centre 245 Oasis Radiant Computer Science, Book 9 GUI = Graphical User Interface HLCIT = High Level Commission of Information Technology HLL = High Level Language HRef = Hypertext Reference HTML = Hyper Text Markup Language IC = Integrated Circuit ICT = Information Communication Technology ICU = Intensive Cam Unit IDE = Integrated Development Environment INGO = International Non Government Organization IPM = Information Processing Machine LCD = Liquid Crystal Display LED = Light Emitting Diode LSB = Least Significant Bit LSD = Least Significant Digit MBR = Master Boot Record MCP = Master Control Program MIPS = Millions of Instruction Per Second MODEM = Modulator and Demodulator MOST = Ministry Of Science and Technology MSE = Most Significant Bit MSD = Most Significant Digit MSDOS = Microsoft Disk Operating System MSI = Medium Scale Integration NEC = Nippon Electronics Company NITC = National Information Technology Center NITDC = National Information Technology Development Council
Oasis Radiant Computer Science, Book 9 246 Approved by Curriculum Development Centre NRN = Non-Resident Nepalese OSS = Open Source Software Operating System Software PC = Personal Computer PCB = Printed Circuit Beard PDA = Personal Digital Assistance POS = Point of Sale PPP = Public Private Partnership PROLOG = Programming Logic PROM = Programmable Read Only Memory QBASIC = Quick Beginners All Purpose Symbolic Instruction Code RAM = Random Access Memory RISC = Reduced Instruction Set Computing ROM = Read Only Memory SMPS = Switch Mode Power Supply SRAM = Static Random Access Memory SSI = Small Scale Integration ULSIC = Ultra Large Scale Integrated Circuit UniVAC = Universal Automatic Computer URL = Uniform Resource Locator USB = Universal Serial Bus VLSI = Very Large Scale Integration WORM = Write Once Read Many WTO = World Trade Organization
Approved by Curriculum Development Centre 247 Oasis Radiant Computer Science, Book 9 Word Meaning Abacus : The first calculating device using beads on string known as counting board. Algorithm : Stepwise instructions to solve any problems using simple English language. Arithmetic and Logic Unit: Part of CPU which performs mathematical calculations and logical operations. Artificial Intelligence: The capability of computer which deals with natural language understanding, reasoning and analyzing as human beings. Assembler : Language processor converts assembly code to machine code Attribute : Additional information with HTML tags Byte : A collection of eight binary digits or two nibbles. CD-ROM : An optical disk on which large amount of data and information can be stored. Compiler : Language processor converts whole source code of HLL to machine code at once Constant : Fixed value or notation which remain same during program execution Control Unit : Part of CPU which controls and coordinates all the activities of computer system. CPU : The processing device also known as electronic brain of computer that controls all the other parts of the system. Data : Individual facts or unprocessed mean of information that do not give meaning. Desktop computer: A computer with keyboard, mouse, monitor and system unit that fits on a desk. Digital computer: The computer works on discontinuous data. DVD : An optical disk on which large amount of data and information can be stored. Firmware : The program stored in ROM chips Flowchart : Diagrammatic representation using common symbols to solve any problems. Garbage In Garbage Out: The computer terminology in which output will be desirable (accurate) if the input is correct. Hardware : Physical parts or electro mechanical equipment which make computer system. High level language: Problem oriented programming language which uses English word or phrase. Home page : Very first page or index page of web site HTML : Markup language used to design web pages Hybrid computer: The computer which works on both continuous and discontinuous data Hyperlink : Special feature used to link documents, pages or URL Input : The act of putting data and information into a computer. Integrated Circuit: Main electronic component of third generation computer. Interpreter : Language processor which converts the source code of HLL machine code line by line
Oasis Radiant Computer Science, Book 9 248 Approved by Curriculum Development Centre Laptop computer: A small sized computer that can work with battery and be easily carried. Microprocessor: A small unit of computer that contains all the functions of central processing unit. Minicomputer: The medium sized computer smaller than mainframe and bigger than microcomputer. Nibble : The collection of four binary digits (bits). Operating system: Type of system software which acts as an interface between user and computer and manages all the resources for smooth operation of computer system. Operator : Symbol indicating an operation between expressions. Output : An information or result produced by a computer after processing data. Pascaline : The calculating machine developed by Blaise Pascal Pen drive : A small pen like portable external storage device used to transfer data from one computer to another. Programming language: An artificial language used to develop computer programs. Pseudo code : Simple program design tool using English phrases to describe processing steps RAM : Volatile memory in which data can be stored for temporary purpose d. Recycle bin : Special program icon on windows Operating system which contains the deleted files or folders from hard disk and can be restored when required. Register : Temporary storage device which holds data and instructions as long as it is being interpreted and executed. ROM : Non-volatile memory that contains instructions or data that cannot be changed or removed. Scanner : A device which copies images or printed text so that can be stored on the computer. Speaker : A device which gives output in the form of sound. Statement : Set of codes and commands used to write program. System software : Type of software which control and manage the overall operation of the computer system. Tag : HTML commands used to code document Tailor software: Software designed to meet the specific requirement of an organization or individual. Touch screen : A computer screen which allows to give instructions to the computer by touching area. Transistor : Main electronic component of second generation computer. Utility software: The service programs used for maintenance and smooth functioning of computer. Vacuum tube : Main electronic component of first generation computer. Web cam : A video camera that is connected to a computer so that what it records can be seen on a website. Web page : World Wide Web document containing hypertext including plain text, graphics, sound, animation etc.