The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Oasis Publication, 2023-10-01 05:56:31

Computer 8 New

Computer 8 New

Approved by Curriculum Development Centre 251 Oasis Radiant Computer Science, Book 8 When you are working with Windows system, Open QBASIC Folder on Windows. Double click over the QBASIC.EXE icon. You will get the QBASIC System as below. Press ESC key and get the programming window of the QBASIC and type the program on the working window of QBASIC. Structure of Basic To construct the QBASIC program we have to arrange some standard elements. The elements are ● Character set ● Variables & constants ● Arithmetic expressions ● Relational or logical expressions ● Keywords ● Syntax ● Library functions The Character Set QBASIC has the character set consisting of the following elements: a. Alphabet: A, B, C, ----. Z b. Digits: 0,1,2, ----, 9 and c. Special characters: + - * / ( ) . , $ ; : = > < " ^ The symbol ^ (caret) is used to denote exponential operation, the symbol * (asterisk) is used to denote multiplication and the other symbols have their usual meanings.


Oasis Radiant Computer Science, Book 8 252 Approved by Curriculum Development Centre Constants and Variables A quantity in a computer program which does not change its value during the execution of the program is called a constant and the quantity which may change its values during the execution of the program is called a variable. QBASIC allows the following constants: a. Numeric constant b. String constant Numeric constant is one that is formed by a sequence of digits 0,1,2, ---, 9 and may include a decimal point. A numeric constant known as number may be as integer or a real number. 383, + 57, 0, - 6.2 and 6.15E4 are valid numeric constants. The number 6.15E4, in fact, represent 6.15 ´ 104 . The notation E is used to represent exponential form. The number after E is the exponent which can be positive or negative. However, its length cannot exceed two digits. It is also important to keep in mind that a. QBASIC does not distinguish between an integer and a fraction. b. Commands are not allowed in a numeric constant c. The limit on the number of digits that can be used varies from computer to computer. Normally, a numeric constant can have up to a maximum of eight digits. A string constant consists of a sequence of characters. It must be enclosed by a quotation mark. This may contain blank space as a character but it should not include the quotation mark. String constants are used to represent non-numeric quantities such as names, addresses, etc. For example, "SUYASH ADHIKARY", "SUM = Rs 75", "162" are a few valid string constants. In QBASIC, variables are also of two types. They are a. Numeric variable b. String variable Numeric variable can assume numeric value and is represented by an alphabet or an alphabet followed by another alphabet or a digit. For example, A, C, A2, ABC, A6 etc, represent numeric variables. A string variable is represented by an alphabet followed by dollar ($) sign. It should be kept in mind that while constructing the string variable, dollar ($) should be the last character. For example, B1$, NAME$, BOOK1$, etc., are valid string variables.


Approved by Curriculum Development Centre 253 Oasis Radiant Computer Science, Book 8 Arithmetic Expressions A QBASIC system can handle arithmetic expressions involving the five arithmetic operators + (addition), - (subtraction), *(multiplication), / (division) and ^ (exponentiation). The hierarchy of operations is as follows: a. Exponentiation b. Multiplication and division c. Addition and subtraction Thus, in a particular arithmetic expression, the order of execution is as per this hierarchy, i.e. all exponentiation operations are performed first, and then multiplication/division and the addition/subtraction operations are the last to be carried out. Note that within a particular hierarchical group, the operations are executed form left to right. Normal hierarchy of operations can be altered by use of parentheses. The operations within the innermost parentheses are performed first and then the second innermost and so on. In addition to this hierarchy of operations, the following rules must be kept in mind in arithmetic expression: a. Two operations must not appear together. For example, C+-D, A/-C, etc are not permitted. b. String constants and string variables should not be used in arithmetic expressions. For example, P+P$ is wrong. c. When brackets are used, they must be used in pairs, i.e., every left bracket must be matched with a right bracket. d. Denominator of an expression should not be zero. e. Within a given pair of parentheses, the natural hierarchy of operations will apply. Let us take an example where we give QBASIC equivalents of a few algebraic expressions Algebraic Expression QBASIC Equivalent 2A+B 2*A+B A + BC + D (A+B)/ (C-D) A(B+C) A*(B+C) B2 -4AC B^2-4*A*C


Oasis Radiant Computer Science, Book 8 254 Approved by Curriculum Development Centre Relational or Logical Expressions A relational expression is formed by using any of the following relational operators: Relational Operator Meaning = Equal to > Greater than < Less than < = Less than or equal to > = Greater than or equal to < > Not equal to In the execution of programs, it is sometimes desired to compare two numerical quantities (or sometimes string quantities) and take decisions on achieving certain conditions. For example, we may be interested to check the number of repetitive calculations performed or to find out whether the denominator of an arithmetic expression has become zero or if a particular quantity is negative, and so on. Expressions written to compare two quantities using certain relational operators are known as relational expressions. These expressions take only one of the two values, namely, TRUE or FALSE, For instance, the relational expression A > B will be true if A is greater than B, otherwise FALSE. This test result is used to change the sequence of execution of statements in a programme. The general form of a relational expression is as follows: Constant or Variable Relational operator Constant or Variable When expressions are used on either side of the relational operators, the expressions will be evaluated first and then the results of expressions compared. This means that relational operators come last in the hierarchy of operators. Logical expressions are used in IF---THEN statements to determine the course of action of a running programme. Logical Operators Like relational operators, QBASIC also supports logical operators to perform logical operation on numerical values. Logical operators are used to connect two or more relations and return a TRUE or FALSE value to be used in a decision.


Approved by Curriculum Development Centre 255 Oasis Radiant Computer Science, Book 8 The common logical operators are: AND Conjunction OR Disjunction NOT Logical Negation For example, the expression A > 50 AND B > 150 is TRUE when A is more than 50 and at the same time B is more than 150. Logical operators return results as indicated in the following tables. T indicates a TRUE and F indicates a FALSE. X and Y are relational expressions. AND Operator X Y X AND Y T T F F T F T F T F F F OR Operator X Y X OR Y T T F F T F T F T T T F NOT Operator X NOT X T F F T Keywords Specific words which are not applicable to use as variable in computer program are Keywords. These are also called reserved words. For example, INPUT, GOTO, PRINT, etc.


Oasis Radiant Computer Science, Book 8 256 Approved by Curriculum Development Centre Syntax A set of rules and regulations that must be followed to construct the programme structure is called Syntax. It is one type of grammar to use the command and statement of computer program structure. Library Functions in Basic The word `library' stands for collection. In the context of computer languages, a library is essentially a collection of useful programs. These programmes are used by the programmers to simplify their task of program development. These programmes are often referred as subroutines. The programmer does not have to know the details of the sub-routine. Most of the programming languages are offered with a number of sub-routines called sub-routine library or library functions. These built-in library functions are used to simplify some useful common functions like calculation of square root, log of a number or cosine of an angle. QBASIC's library is rich with mathematical functions. For example, suppose you want to calculate the square root of a numeric variable A. In simple mathematics, square root of A, i.e., can be written as A½. Thus in QBASIC it can be written as: LET B = A^0.5 The value of B will be the square root of A. Using a library function the operation can be performed as LET B = SQR(A) Of course, from the example, it appears that there is hardly any benefit in using the library function. But imagine, the problem is little more complicated like calculation of the sine value of an angle or logarithm of a number. The programming algorithm to calculate these is not so simple. To find the logarithm of C by using LOG function you write LET Y = LOG (X), The variable Y will store the LOG value of X. From this example, we may deduce the rules, governing the use of a function. a. Each function is assessed by the function name (LOG, SQR, etc.) followed by the function argument placed within the parenthesis. b. The function argument is the information you supply to the function to act upon it. For mathematical factions, it has to be a numeric constant or variable. Listed below are some examples of mathematical functions in BASIC.


Approved by Curriculum Development Centre 257 Oasis Radiant Computer Science, Book 8 Function Name Purpose Example SIN Sine Calculate the Sine SIN(X) value of an angle (in radians) SIN(44/7) LOG LOG Calculate the natural LOG(X) logarithm of a number LOG(100) SQR Square root Calculate the square SQR(A) root of a number SQR(100) c. The function name is to be written exactly as given. No deviation is permitted. d. You cannot have a blank space between function names (SIN, LOG, etc.) and the beginning of the opening parenthesis enclosing the argument. It should be noted that a library function programme would produce the result faster than a QBASIC programme that has been written to perform the same task. For example, calculation of square root by the SQR function will be faster than writing in the form of a programme. This is due to the fact that library functions are optimised for the particular QBASIC interpreter provided by the supplier. Input/Output and Programme Control Statements We have studied about the constants, the variables and the arithmetic operation used in the QBASIC language. We also saw how these constants, variables and the arithmetic operations may be combined to form expressions and statements. Now we shall learn how the complete program in QBASIC language can be written using the basic principles we have learnt so far. For a computer program to be executed using a computer, we should give some values to the computer. Once the computer completes the required computation work, we should ask the computer to produce the results in a proper format that can be understood by the common man. The INPUT/OUTPUT statements of the QBASIC language achieve these two important functions. Besides these, we shall also discuss the use of repetitive and branching statements used in QBASIC language. Getting Data into Memory As stated earlier, one of the basic features of a programming language is the input/ output facility offered by it. QBASIC offers three such kinds of input statements. They are LET, INPUT and READ-DATA. These statements are basically used to assign values to various variables.


Oasis Radiant Computer Science, Book 8 258 Approved by Curriculum Development Centre LET Statement Syntax LET (variable name)=(Constants or Variables or expression) Example of LET statement LET X =5.32 ---> This is numeric constant LET A = 6+9/3.2 --> This is an arithmetic expression LET Y = X+A --> This is also an arithmetic expression LET I =I+Y --> I and Y are variable names LET A$ = "LAMJUNG” --> String variable LET F$ = "99983" --> String variable LET A = 50 --> Numeric variable These are all valid LET statements. The value of the variable on the left hand side of the equal to sign is assigned the value given in the right hand side of the equal to sign Example LET A =10 LET B =5 LET A = A+B The example shows A is the variable name, which is assigned the value 10 and B is the variable name assigned the value 5. In the memory the line number 15 gives an instruction by which A will be the address or name of a cell/location where the value 10 will be stored. Similarly, B will be name or address of a cell/location where 5 will be stored. Line number 35 instructs that the values in the address A and B be added and the resulting value be kept at the cell/location whose address is A. INPUT Statement Syntax INPUT Variable, List... Example INPUT A,B,X INPUT A$,F$,N$ INPUT Y1,F$,C2,NB


Approved by Curriculum Development Centre 259 Oasis Radiant Computer Science, Book 8 Whenever the computer reads a line with the keyword INPUT it displays a sign? on the VDU and waits for the data. We have to give the values of the variable at this prompt through the keyboard. READ-DATA Statement Syntax READ Variable, List.... DATA Constant, List.... READ....DATA Statement REM PROGRAM EXPLAINING READ....DATA STATEMENT READ X2,Y,Z1,K READ A,B3, C4, L DATA 8,9,13,15,16,51,30,92 END When the machine encounters the READ statement followed by the variables X2,Y,Z1,K it will collect from the DATA statements the values for these variables in the same order. A one-to-one correspondence exists in READ-DATA statement, i.e. X2=8, Y=9, Z1=13, K=15. In the next READ statement we have four more variables A,B3,C4,L. These values will follow in the same order and one-to-one correspondence after the earlier READ variable values, i.e., after 8,9,13,15, i.e., A=16, B3=51, C4=30, L=92. Since all the values in the DATA here are exhausted, another i.e. third, READ statement cannot be used until another DATA statement is included or more DATA is included in the above DATA. A DATA statement can be anywhere in the program but must be before the END statement. It is a normal practice to keep all DATA statements together at the end of the program before END statement, so that in case you want to alter any data at the end it will be easy. Print Statement The PRINT statement of QBASIC provides limited methods of controlling the alignment and spacing of printout in terminals. The general from of the PRINT statement is


Oasis Radiant Computer Science, Book 8 260 Approved by Curriculum Development Centre PRINT (Variable) separator (variable) separator or item...... The separation may be comma (,) or semicolon (;) The Semicolon (;) Control Programme LET S =1175.50 PRINT "TOTAL SALARY =";S; " RUPEES" END The output of the program will be T O T A L S A L A R Y = 1 1 7 5 . 5 0 R U P E E S Using semicolon in a print statement, the items are close to each other, and as a result more items can be printed in one line, The Comma (,) Control PRINT "NUM","TEMP","SIZE", REMARK" PRINT 65,-15.56,36,34 These two lines will be printed as follows NUM 65 TEMP -15.56 SIZE 36 REMARK 34 Print Using Statement The PRINT USING statement is included in most versions of microcomputer QBASIC. It allows printed output to be formatted, giving the appearance of each data item. This PRINT USING statement can specify both string and numeric data. There are several different ways to format. The most commonly used are given below: PRINT USING "##. ##"; A,B,C, PRINT USING Format String Numeric Variables The format string "##. ##", which is a numeric field containing a decimal point with not more than two digits on each side. What will be the output of the following program? LET A =17.32


Approved by Curriculum Development Centre 261 Oasis Radiant Computer Science, Book 8 LET B = -5.38 LET C =40 PRINT USING "##. ##",A,B,C, END OUTPUT 17.32 -5.38 40.00 If string values are used instead of numeric values, the format string for PRINT USING will be as follows: PRINT USING "!!!!!!" ; N$ If N$ ="UNITED" Then the above PRINT USING statement will give output as: UNITED Tab Function The TAB (abbreviation of TABULATION) function is a very important function because it enables the user to exercise exact control over the print positions. The use of a COMMA and a SEMICOLON to space out the output is not as flexible as the TAB function. TAB (N) moves the printer head to the Nth column and printout of any data starts from that column. Syntax: PRINT TAB (N); X Where N is a positive number, a variable or an expression having positive value and X shows output data The execution of TAB function is explained below:- a) If N is an integer, the printer head moves to the Nth column and printing of the value of X starts from that column b) In case N is a variable, not having the internal value, it is rounded and the printer head moves according to this value. For example, X = 12 K = 5.3


Oasis Radiant Computer Science, Book 8 262 Approved by Curriculum Development Centre PRINT TAB (k); X c) On the other hand, if N is an expression then first of all, the expression is evaluated and rounded, if necessary. The printer head moves based on the value of this expression. The backward movement of the printer head is not allowed. For example, consider the statement PRINT TAB (25); "SUYASHA" Here TAB (25) instructs the computer to start printing SUYASHA from column number 25 onwards. PRINT TAB (25); "SUYASHA"; "ADHIKARY" Unconditional Go To Statement GOTO statement is used to transfer control from a statement, say S1 to another statement, say S2, generally, S2 does not follow S1 immediately in sequence. Syntax: GO TO n n is the line number of the statement where control will be transferred. Example CLS 10: PRINT "first" GOTO 30: 20: PRINT "third" GOTO 40: 30: PRINT "second" GOTO 20: 40: END


Approved by Curriculum Development Centre 263 Oasis Radiant Computer Science, Book 8 Some Examples 1. Write a program to calculate the sum of two numbers. REM "to calculate the sum of two numbers CLS INPUT "Enter the first number"; a INPUT "Enter the second number"; b sum = a + b PRINT "The sum is :"; sum END 2. Write a program to calculate simple interest and amount. CLS INPUT "enter the principal amount"; p INPUT "enter the rate"; r INPUT "enter the time"; t i = (p * t * r) / 100 PRINT "The simple interset is:"; i a = p + i PRINT "The total amount to be paid is Rs:"; a END


Oasis Radiant Computer Science, Book 8 264 Approved by Curriculum Development Centre 3. Write a program to calculate surface area and volume of a cone. CLS INPUT "Enter the value of Pi"; pi INPUT "enter radius"; r INPUT "enter slant height"; l INPUT "enter height"; h A = pi * r * l V = 1 / 3 * pi * r ^ 2 * h PRINT "The area is"; A PRINT "The volume is"; V END 4. Write a program to find out total marks and percentage of any five subjects. CLS INPUT "enter marks for Computer"; C INPUT "enter marks for Science"; S INPUT "enter marks for Social"; So INPUT "enter marks for English"; E INPUT "enter marks for Nepali"; N Total = C + S + So + E + N


Approved by Curriculum Development Centre 265 Oasis Radiant Computer Science, Book 8 PRINT "The total marks is"; Total AVG = Total / 5 PRINT "The percentage is"; AVG END 5. Write a program to accept a temperature in centigrade and converts it into Fahrenheit. CLS INPUT “Enter the temperature in centigrade”, C F=C*(9/5)+32 PRINT “The Fahrenheit temperature is “, F END 6. Write a program find the area and perimeter of circle. CLS INPUT “Enter the radius of circle”, R A=3.1416 *R*R P=2*3.1416*R PRINT “ Area and perimeter is “, A,P END 7. Write a program to find the sales amount of a computer according to following conditions. Purchase Amount, Profit = 20% CLS INPUT “ Enter purchase amount “, PAMT PROFIT=PAMT *20/100 SAMT=PAMT+PROFIT PRINT “ Sales Amount is “, SAMT END 8. Write a program to find the area and perimeter of a square . CLS


Oasis Radiant Computer Science, Book 8 266 Approved by Curriculum Development Centre INPUT “Enter Length”, L A=L^2 P=4*L PRINT “Area and perimeter “, A,P END 9. Write a program to find the distance between two points (Coordinates). CLS INPUT “Enter coordinate of first point”, X1, Y1 INPUT “Enter coordinate of second point”, X2, Y2 D=SQRT ((X1-X2) ^2 + (Y1-Y2) ^2) PRINT” Distance between two points is”, D END 10. Write a program to find the slope of a given line. CLS Input “ Enter Y Intercept”,y Input “Enter X Intercept”,X Input “Enter Constant “, C M=(Y-C)/X Print “Our Slope is “,M End The Branching Statement IF... THEN The IF...THEN is a decision making statement. Depending upon the decision, it can change the order of execution. It helps the computer to check whether a relation is TRUE or FALSE. Syntax: Line number IF (relational expression) THEN n where n is a line number or an instruction itself. If the relation expression is true, then n will be executed otherwise the statement following this IF...THEN statement will be executed. Example Evaluate the expression Y =X2 for X =1,2,3...


Approved by Curriculum Development Centre 267 Oasis Radiant Computer Science, Book 8 Programme 1 LET X = 1 → 20 LET Y = X*X PRINT Y LET X = X+1 → 50 GO TO 20 END In this process we see each time the line number 50 is executed the control is transferred to line number 20 unconditionally. Thus we have an infinite loop which is never ending. Computer goes round and round and never reaches the END. To stop the infinite loop we can add a condition, i.e. say if X is greater than or equal to 31 (X >=31) then the program ends, otherwise it keeps on printing the value of expression Y = X2 for X =1,2,3....30. Programme 2 LET X = 1 → 20 LET Y = X*X PRINT Y LET X = X+1 → 50 IF X> = 31 THEN 70 GO TO 20 → 70 END Thus we see that IF-THEN is one of the powerful statements which can stop or get the computer out of an infinite loop. Example Problem Write a program to find out the auto fare depending on the kilometers traveled. The minimum fare charged is Rs. 3.00. This minimum fare remains for 2 kms or less of travel. After 2 kms, the charges are 75 Rs per kilometer.


Oasis Radiant Computer Science, Book 8 268 Approved by Curriculum Development Centre Programme 1 INPUT "KILOMETER", K IF K < = 2 THEN PRINT "RS.3”: END LET CHARGE =3+ (K-2) *.75 PRINT CHARGE END If K is less than or equal to 2 (i.e., K<=2) then it will print Rs. 3 and (: END) means END Otherwise if K is not less than or equal to 2 then it will print calculated change. The Branching Statement IF...THEN...ELSE Another important statement is IF ...THEN...ELSE. Syntax: Line number IF (condition or relational expression) THEN (line number or Instruction) ELSE (line number or Instruction) The IF...THEN...ELSE statement is a decision making statement as it decides the path of the programme. It helps in making comparisons and testing whether a condition is true or not. IF is always followed by a valid BASIC condition or expression. If the condition is found true then the line number or Instruction after THEN is performed otherwise line number or instruction after ELSE is performed. Example Problem Ages of different students appearing in the Board examination are taken. If the age is below 17 the student is not eligible, otherwise he can appear in the Board examination. We are asked to write a program for this problem. → 10 INPUT “AGE”; A IF A>= 17 THEN PRINT “WELCOME FOR BOARD EXAMINATION” ELSE


Approved by Curriculum Development Centre 269 Oasis Radiant Computer Science, Book 8 PRINT “YOU ARE NOT ELIGIBLE FOR BOARD EXAM.” INPUT “WANT TO INPUT AGAIN (Y/N)”; Y$ IF Y$ = “Y” THEN 10 END We will get the message AGE? We input the age through the keyboard, say 18. It tests whether A>17 or not. Since A=18>17 it prints WELCOME FOR BOARD. We get a message WANT TO INPUT AGAIN (Y/N)? We input either Y or N. If input is Y then control goes to line number 10. Otherwise, if input is N then control goes to the END. If input is yes or Y then control will pass again line number 10, we give another age, say 13 Value of A (i.e. 13) is not greater than 17, therefore ELSE part will be executed and control will print YOU ARE NOT ELIGIBLE FOR BOARD EXAM. Problem To find the greatest number among any three numbers. 10 INPUT A,B,C → 20 IF A>B AND A>C THEN 50 ELSE 30 → 30 IF B>A AND B>C THEN 60 ELSE 40 → 40 IF C>A AND C>B THEN 70 50 PRINT "A IS THE LARGEST NUMBER": GO TO 80 60 PRINT "B IS THE LARGEST NUMBER": GO TO 80 70 PRINT "C IS THE LARGEST NUMBER" 80 INPUT "WANT TO INPUT AGAIN (Y/N)" ; Y$ 90 IF Y$ = "Y" THEN 10 100 END In line number 20, 30, 40 comparisons are made among the values of A,B, and C. AND is a logical operator which combines A>B and A>C. If both the relational expressions preceding and following AND are true then the line number following THEN will be executed otherwise if one of the relational expression, A>B or A>C is true then the line number following ELSE will be executed. Same procedure


Oasis Radiant Computer Science, Book 8 270 Approved by Curriculum Development Centre follows for the next two IF statements also. If expression at 20 is found true, the line number 50 will print A is THE LARGEST VALUE and then GO TO 80 will be executed as the next statement to line number 50. If it is found false the control passes to statement 30 and the expression at that statement is checked. This part of the program can also be written as follows: 50 PRINT "A IS THE LARGEST NUMBER" 55 GO TO 80 60 PRINT "B IS THE LARGEST NUMBER" 65 GO TO 80 Thus line number 50 and 60 in earlier program of problem 2 is equivalent to line numbers 50, 55, 60, 65 in the above program statement. Syntax: For IF...THEN...ELSE with AND is given as; → IF (Condition 1 or Relational expression) AND (Condition 2 or Relational expression) THEN (Instruction 1) ELSE (Instruction 2) Like AND another logical operator is OR. Syntax: for IF…. THEN...ELSE with OR is: IF (Condition 1 or Relational expression) OR (condition 2 or Relational expression) THEN (Instruction 1) ELSE (Instruction 2) This means if either of the conditions (or relational expression) followed or preceded by OR is true then the instruction 1 is executed. If neither of them is true then instruction 2 is executed. Some Examples 1. Write a program to accept a number and check if it is a positive or negative number. CLS INPUT “ Enter a number ”,N IF N<0 THEN PRINT “Negative Number” ELSE IF N>0 THEN PRINT “Positive number”


Approved by Curriculum Development Centre 271 Oasis Radiant Computer Science, Book 8 ELSE PRINT “ Zero Number” END IF END 2. Write a program to accept a day code and display the name of the days according to day code. CLS INPUT “ Enter day Code ”, DC IF DC=1 THEN PRINT “ Sunday” ELSE IF DC=2 THEN PRINT “Monday” ELSE IF DC=3 THEN PRINT “Tuesday” ELSE IF DC=4 THEN PRINT “Wednesday” ELSE IF DC=5 THEN PRINT “Thursday” ELSE IF DC=6 THEN PRINT “Friday” ELSE IF DC=7 THEN PRINT “Saturday” ELSE PRINT “Invalid Code” END IF END 3. Write a program to calculate the tax according to the income as below: (Sno, Name, Income)


Oasis Radiant Computer Science, Book 8 272 Approved by Curriculum Development Centre If Income>=50000, tax= 15 % If Income>=25000 and less than 50000, tax= 10 % Else No Tax CLS INPUT “Enter the Serial No, Name and Income”, SNO, NAME$, I IF I>=50000 THEN TAX= I*15/100 ELSE IF I>=25000 THEN TAX = I*10/100 ELSE TAX= 0 PRINT “Serial No, Name and Tax: “, SNO, NAME$, TAX END IF END Loops "Loops" make it easier to do an action multiple times. There are at least four types of loops: Loop is defined as the repeated execution of the statement that performs the work until the condition will satisfy. Popular loops are FOR...NEXT, IF...GOTO, WHILE...WEND and DO...LOOP FOR..NEXT LOOP We have already seen that a loop can be built in QBASIC by using the IF-THEN and GOTO statements. When it is known in advance how many times the loop must be repeated the statement FOR...NEXT is the most effective statement. A loop is built up by FOR and ended by NEXT. Syntax: Line number FOR I = M TO N STEP J Loop - - - - - - - - - - - - Line number NEXT I


Approved by Curriculum Development Centre 273 Oasis Radiant Computer Science, Book 8 The numeric variable name following FOR is called the control variable or loop variable. M and N are numeric constants where M gives the initial or starting value of the loop and N gives the final value, J followed by keyboard STEP gives the increment in M till N is reached. The increment can be negative also. M,N,J can be numeric variable names. In such cases their numeric values should be assigned before the starting of the loop, i.e. before coming to FOR-TO statement. The key word NEXT should have the same control variable I followed by it. Thus one loop can be started with FOR-TO and ended with NEXT. Inside one FOR-TO ...NEXT loop there can be more FOR-TO...NEXT loop. But once a FOR-TO...NEXT is inside another FOR-TO...NEXT, it should remain completely inside the former loop. Such FOR-TO...NEXT loops are called Nested loops. In the absence of the STEP clause, the increment is assumed to be 1. Example REM display the first ten natural umbers CLS FOR I = 1 TO 10 PRINT I NEXT I END Output 1 2 3 4 5 6 7 8 9 10


Oasis Radiant Computer Science, Book 8 274 Approved by Curriculum Development Centre Example REM display odd numbers upto 20 CLS FOR I = 2 TO 20 STEP 2 PRINT I NEXT I END Note: STEP 2 is used to step up the number with the value 2 like 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 IF...GOTO LOOP This program uses IF...GOTO to create a loop: x = 10 start: PRINT x x = x + 1 (This adds 1 to x) IF x < 15 THEN GOTO start Output: 10 11 12 13 14 WHILE...WEND. The WHILE...WEND commands continue a loop until a specified expression is false. To use WHILE...WEND: Place an expression after WHILE Enter a list of commands Place WEND at the end Run the following: x = 10 WHILE x < 15 PRINT x x = x + 1


Approved by Curriculum Development Centre 275 Oasis Radiant Computer Science, Book 8 WEND Output: 10 11 12 13 14 DO...LOOP DO...LOOP is exactly the same as WHILE...WEND, except it has at least two slight advantages. With DO...LOOP you can: Loop until an expression is true Loop at least one time regardless of whether the expression is true or not. To use DO...LOOP: Specify whether the loop continues "while" the expression is true or "until" the expression is true, using the WHILE and UNTIL statements, respectively. Place an expression after WHILE/UNTIL Enter a list of commands Place LOOP at the end. The following uses the WHILE statement: x = 10 DO WHILE x < 15 PRINT x x = x + 1 LOOP This program uses the UNTIL statement: x = 10 DO UNTIL x = 15 PRINT x x = x + 1 LOOP END They both output: 10 11


Oasis Radiant Computer Science, Book 8 276 Approved by Curriculum Development Centre 12 13 14 If you place the expression at the end of the loop instead, the program goes through the loop at least once. x = 32 DO PRINT x x = x + 1 LOOP WHILE x < 5 This is the output because the loop was only gone through one time: 32 Solved Examples 1. Write a program to find the sum of first ten natural numbers REM sum of first ten natural umbers CLS SUM = 0 FOR I = 1 TO 10 sum = sum + I NEXT I PRINT "The sum is"; sum END 2. Write a program to print first 10 odd numbers. REM to print first 10 odd numbers CLS FOR I = 1 TO 20 STEP 2 PRINT I NEXT I END 3. Write a program to print the odd numbers and sum upto a given number. REM "to print the odd numbers and sum upto a given number" CLS INPUT "Enter any number"; n sum = 0


Approved by Curriculum Development Centre 277 Oasis Radiant Computer Science, Book 8 PRINT "The odd numbers are"; FOR I = 1 TO N STEP 2 PRINT I; sum = sum + I NEXT I PRINT PRINT "The sum of odd numbers is:"; sum END 4. Write a program to display the series 2, 4, 8, 16, 32 ....10 terms: REM to display the series 2, 4, 8, 16, 32 ....10 terms: CLS LET a = 2 FOR x = 1 TO 10 PRINT a LET s = s + a LET a = a + 2 NEXT x PRINT "The sum is:"; s END 5. Write a program to find the area of a triangle. REM to find the area of a triangle CLS INPUT "Enter the first side:"; a INPUT "Enter the second side:"; b INPUT "Enter the third side:"; c IF (a + b < c) OR (a + c < b) OR (b + c < a) THEN PRINT "A triangle is not possible" ELSE PRINT "A triangle is possible" END IF s = (1 / 2) * (a + b + c) area = SQR(s * (s - a) * (s - b) * (s - c))


Oasis Radiant Computer Science, Book 8 278 Approved by Curriculum Development Centre PRINT "The area of a triangle is:"; area END 6. Write a program to find the cube of the first 20 numbers REM to find the cube of the first 20 numbers CLS FOR I = 1 TO 20 PRINT I ^ 3 NEXT END 7. Suppose we want to print the output in the following format: * * * * * * * * * * * * * * * FOR S=5 TO 1 STEP-1 FOR X=1 TO S PRINT "*" ; NEXT X PRINT NEXT S END 8. Suppose we want to sum the following series: 1,2,3,4_ _ _ _ 100. LET S=0 FOR I=1 TO 100 LET S=S+I NEXT I PRINT " SUM OF SERIES =" ; S END


Approved by Curriculum Development Centre 279 Oasis Radiant Computer Science, Book 8 Exercise Key Points ● QBASIC is most popular high level programming language developed by Microsoft Company. ● QBASIC has two basic files QBASIC.EXE and QBASIC.HLP. ● QBASIC is applicable to all types of applications so these are called general purpose programming language. ● Basic components of QBASIC are: character set, variables and constants, logical expression keywords, syntax and library functions. ● Mathematical operation performs mathematical work using +,-,*,^ etc. and logical operation performs the work using OR and AND operators. ● Read – Data statement is used to store and display data. ● Functions are built in operator that performs the work like a command. ● To perform work according to logic and condition we have to use IF THEN ELSE condition. ● Repeated logic that performs the expressions until the condition will satisfy is called Loop. 1. Answer the following questions. a. What is QBASIC? b. Write the files used in QBASIC? c. What is variable? d. What are operators? Write its types. e. Write the use of logical and mathematical operators. f. What is loop? g. List any three types of looping structure with syntax. h. What is keyword? i. Write the advantages of QBASIC. j. How to start QBASIC on MSDOS?


Oasis Radiant Computer Science, Book 8 280 Approved by Curriculum Development Centre 2. Write short notes on: a. Key word b. Character set c. Loop d. Control statement e. Library function. 3. Differentiate between: a. Variable and constant b. General word and keyword c. Loops and general logic d. Read and Input e. While .. Wend and For I Loop 4. Write a program for the following. a. To calculate area of circle. b. To find simple Interest and total amount. c. To find volume d. To find perimeter of square. e. To find area of rectangle. f. To display even numbers from 10 to 100. g. To write a program to calculate tax according to income. (Input Income, If Income>=15000, Tax= 20% else tax=5%) h. To display your name twenty times using the FOR … Loop. i. To accept rollno and name using Read and Data statement. j. To convert the temperature from Fahrenheit to centigrade 5. Class Activity and Project Work. a. Make a list of command to handle input and output of QBASIC application. b. Prepare a result analysis using standard conditions. (Use Rollno, Name and five subjects marks) c. Make a project report by collecting any twenty programmes and show it to your teacher.


Click to View FlipBook Version