You are on page 1of 29
Most of the times, we depend on a device with a particular function todo v ‘our work. It saves us from the burden ¥ of knowing the exact process and S executing them manually. We can simply delegate our job to the ‘function box’ and get our things done 7 Se FUNCTIONS AND SUBROUTINES iy QBASIC has several functions and wv ‘oe subroutines that help to write programs in a much efficient manner. Subroutine A subroutine, a module ora procedure, is a small sub program that is written within a program. This subroutine can hold a collection of commands according to a particular logic and can be executed anywhere in the program. Function A function, on the other hand,.is the same as a subroutine, except it returns a value. While calling, the CALL keyword need not be written. You may ‘call’ the function directly by the name. To retum a value, set a variable with the same name as the function. Teacher's Note: This is an Optional Chapter. _-¥ Series Programming Functions and Subroutines Built-in Functions Numeric Functions—ABS. INT, SOR, SGN, FIX, cInT Sering Functions —CONCATENATION, LEN, LEFTs, RIGHTS, MIDS, LCASE$, UCASES, STRINGS, SPACES, TAB and INSTR Conversion Functions—CHRS, ASC, STR$ and VAL Loop Utilities While-Wend Loop Nested Loop Patterns with Spaces mn Create « Subroutine. Click on Edit ® New Sub. Enter Display os name for. the subroutine. Type the following commands between SUB and END SUB: SUB Display (num). PRINT num*num END_SUB. Now press F2. Select ‘Untitled’. Press Enter to return te'the main program that will cll your | Subprogram. Now, in this program, type CALL Display (5). Press FS to run this program. You get 25.as the | output. This is because the main program calls the subroutine Display that is declared before sending avalue 5. This value of 5 is stored by the \ Be a Techie! 3 Variable num in the Display subroutine. It thus oe Square of the number, that is, 25 ~ tou_may use this concept to write similar Shain ee qocreate anew function (knoy r: own a: . as us define "ned function), go to th \¢ Edit menu. Select New ter the following Now € (SION Square (num) sq Square ~ go FUNCTION Fe = hunt num ‘ster moving to the main pr will be 25, am, enter er the cod ode PRINT S, quare (5), The nerated output pere, the function name and the y es ariable ariable name. So, a function retur that is supposed to return the v e TS a value whereas a s DR csce et subroutine does nc S) BASIC provides some read - ean Beis acy tales aed functions that are frequently res f ee . The user can call these f ly required within a program quer docs not have to write the logic for these fen that are already present. So, the ace written, it can be called ea es functions. Another benefit of functions is that ly whenever require: ofthe program and the length of the program as eer) ee gram can be shortened. alue have the same Dt return a value. The built-in functions in QBASIC can be classified into the fi 1, Numeric functions—These functions eee eer: nintioneiiees ea a on numbers and return a number . © functions work upon a string and may be use extract or manipulate a string. iS y be used to join, extract 3, Conversion functions—These functions are used to convert one type of data to another. NUMERIC FUNCTIONS (OR MATH FUNCTIONS) 1. ABS ()—This function displays the absolute value of a number the function is ABS (n), where ‘n’ is an integer. For example, BE ierianss (C5) wilirctamt 5 oP PRINTABS ©) Wil also return 5 between two numbers. Program 1: Write a program to displa 1. The general syntax of y the absolute difference 3 ABS () function REM To display absolute aifrerence between E¥0 numbers using ‘0 display REM [5-3) = 2 and 13-5! = 2 i Reticmercr TES FIRST SOE PRINT “THE ABSOLUTE DIFFERENCE va avoid With the help of this function, one aan ae | theneed to check the greater of two a ae nd then subtract the lesset number higher number. eger, not greater Beeeetirevonetirns hearse (oy nd iefition. The general syntax of the [UNS c For example, re: a. 147) PRINT INT (4.2) will return 4. PRINT a ea ce oo PRINT INT (-4.2) will return ~5 PRINT I ¢ so Program 2: Write a program to display all the factor Ee 5 = ger (.) functior sor a ae me . Spi Sereres tue woMEER 1 GET THE FACTORS — a PRINT “THE FACTORS ARE é Fo Peres 8 se é RI IF N / I = INT (N / I) THEN PRINT I NEXT SEER ot rors 47 Pro END « of a number excluding the number its Program 3: Write a program to display all the factor fa number , r. using INT () funetion, se cus rece feeicing the vember S80 E weirs 3. (.) function INPUT “ENTER THE NUMBER 10 GET THE FACTORS:" | PRINT “THE FACTORS ARE:” 4 FOR T= 1 TON /2 7-1 = INT (N / 2) THEN PRINT I NEXT T IF N END Fig, 9.3 Output of Program 4: Write a program to accepta number and display whether itis a perfect number factors excluding the number is equal to the not. A perfect number is a number whose sum of number itself, For example, 6(1+2+3=6) and 28(1+2+4+7+14 28) are perfect numbers. cLs REM To check whether a number is a perfect number or not INPUT “ENTER THE NUMBER TO CHECK:”, N Bt oe re em: suM = 0 FORI=1T0N/2 IF N / I = INT (N / I) THEN SUM = SUM + I NEXT I PRS ores Pat ar 1S) A PERFECT wommeR” ELSE PRINT “IT 15 nor END Mies L Fig. 9.4 Output of Program 4 5; Write a program to ram 5° accept A prime num ; a Aber has no Dumber an, CLOTS exe fper of 10t whether = ‘nimben 2 Prine ENTER THE NUMBER 10 CHpeg me not ction paz 270 i IT 1s an a A PRIME NUMBER” ELSE PRIN? m2 T itself = Nes The factor of a number can also be checked by the MOD operator that gives the remainder of a division. Thus, IF NA=INT (NA) may also be written as IF N MOD I= 9 J INT 3. SQR ()—This function returns the Square root of a number. The function is SQR (nm), where n>=0. The square root of ( is 0 For example, SQR (9) will retum 3. Ifnisa negative number, then it displays iu error message—Illegal Function Call, 4. SGN ()—This function retums the sign of the number that is passed. The general syntax of the function is SGN (n) Paks Ifn is a positive number, that is, »°0 hen : general syntax of the zi =I tis, <0 then this returns ror Ifn isa negative oe ae Beare 0 Fe canoe the Ifn is equal to 0, that's, 1, PRINT SGN (5) will return | ill return! PRINT SGN (-5) will iil return 0. ber is negative or not, especially before SGN (0) will re! era number is negative or not, especially before PRINT a ‘eo to check ner. For example, IF SGN (n)>-1 THEN PRINT It is generally root of 4 = ware : finding out the $4 uns the truncated integer part of any numeric SQR (n). sanction that wofie function is FIX (numeric express a 5. FIX ()—Iti53 eral s¥™ eeietien ye Be pRINT FIX (4.7) will return 4, 4 (—4.7) re For examle yi ti 4, PRINT FIX (4.7) will retum —4 ; | PRINT FIX eal will yew meee = PRIN ae is he by ve nis ral nd nd the the is a function that takes ina ‘PRINT -4.7, INT (-4.7), CINT (-4.7), ‘END Note: The difference between FIX () and INT ( ) is that in ¢: will return the first negative integer that is great return the first negative integer less than the number. CINT () is different from FIX () ai simply truncates the value. STRING FUNCTIONS 1. CONCATENATION—You have already studied that the “+” operator behaves in different ways when placed between numbers and strings. When ‘+’ is placed between two numeric values, then it adds up the two numbers. However, when it is placed between two strings, it concatenates or joins the two strings. For example, the part of code: AS= "Computer ” BS = “Science” C$=A$+BS PRINT CS Vee Seana Science as the output. (Note one mputer in AS), Program 7: Write a program to acc: r ‘ept the firs e, and display the full name of the person, . Since, CINT () a ase of a ne; er than the given numbe: nd INT () as CINT () rounds-off whereas the other tc middle name and surname separate!) 6. CINTO—Hti eee i 7 off the fractional f r Bntege by om T7768 to 32767 reports an overflow ST F, value outside the range ~32 : : jam to show the difference between INT (), ¢ : e Program 6: Write 9 pros! = functions. of Es the differences between INT ( ) INT ( ) and FIX ; REM To show i Beers cn”, “cme on”, FIX (Qn) PRIN’ Soper (4.3), CENT (4.3), FIX (4.3) eer ce se G5), Cor (4.5), FIX (4 5) ey er (4-7), CINE (4.7), FAX (4-7) Peeeesy arr (4.3), cur (-4.3), FIX C4 3) Fig. 9.6 Output of Program 6 Beye scam (4.5), cur (-4.5), FIX (-4-5) FIX (-4.7) ative number, FIX () whereas INT () will a 5 Info Hub The ‘+ operator cannot work with one numeric and one string value. For example, the following string concatenction ‘operations are invalid ond will result in errors— PRINT 23 + “MOORE AVENUE” PRINT “491” + 9830197772 PRINT 23 + “+91” a os auspley the full name o: Sid £ a person peor “ENTER THE FIRST NAME:", F§ Wenn ; si a out ENTER THE MIDDLE NAME MS cr i Pe pot “ENTER THE SURNAME: ”, S$ qn “THE FOLL NAME TS Fig, 9.7 Output of Program 7 m (+ F wR $4 «hoe es LEN (This functi f 2. LEN () ‘unction returns the length of the current string including the leading trailing and embedded s| ie Se ean nie It accepts a string as a parameter and returns the number of characters present between the double quotes of that string, The general LEN (string). syntax is For example, the part of code: aS = “Computer Science” PRINT LEN (A$) will display 16. It is essential to count the length of a string when the input has been given by the user during runtime as all the other operations are based on the length of the string. 3, LERTS ()—This function extrac the specified number of characters from the lef of the string. The general syntax of this function is LEFTS (source string, number of iGuaaeters), Thus, ths TuRCNOn reads and extracts the mentioned number of characters from the left of the string : the part of code: es Eg (PEABSON EDUCATION”,7) will display PEARSON PRINT U se ot aes the specified number of characters from the right y __This function ext of this function is RIGHTS (source string, number of the string. The 27° 'Fnction reads and extracts the mentioned number of of characters): i peat of the string: However, the extracted string is displayed from re ane rig! characters from left to right ihe code For example: the aes RSON EDUCATION”. 9) will display EDUCATION, pRINT RIG! to display the Program 9: Write a program to display the een program vat: following sample pattern of output: Program & ple pate™ gow? ee = mn} following S* REM Pattern Out zn Output cus outs Ee INPUT “ENTER A STRING:”, S$ 2 28 é pem Parte goRIne?”' LET L = LEN ae (ss) ant (9) eo 3 FoR I = 1 PRINT RIGHTS PRINT LEFrs (s$, 1) NEXT T END ie Fig, 9.9 Output of Program 9 Fig. 9.8 Output of Program 8 d number of characters from the middle of 5. MIDS ()—This function extracts a specific g. m,n). Here the string. The general syntax of this function is MIDS (source str refers to the starting place of extraction and “n’ refers to the number of characters to be extracted beginning with that character. If ‘n’ is excluded, then it extracts till the last character. For example, the part of code: PRINT MIDS(“PEARSON EDUCATION”, 5, 7) will display SON EDL MIDS() can also be used to change a portion of the string variable. For example, the part of code: A$ = “ASSESSMENT” PRINT AS MID$ (A$, 2, 5) = “TTACH” PRINT AS will display— ASSESSMENT ATTACHMENT Passwords can be stored inside a program by using the MIDS () function. Thus, any person who does not know programming would not be able to find out the exact password that is stored within the program. The MIDS ( ) function is a very versatile function. One can simulate the LEFTS () and the RIGHTS ( ) functions with the help of the MIDS () function. : For example, LEFT$ (A$, 5) may be written asMID$ (A$, 1, 5) and RIGHT (a$, 3) maybe written asmrDs (aS, (LEN (as)-341)) ~~. LET B = LEN (A$) NOV = 0 FORI=1708 LET C$ = MIDS (A$, I, 1) PRINT “THE NO.OF VOWELS IN TH Program 14: Write a program to accept @ name and display initials of the name. cis REM To display name initials INPUT “ENTER YOUR NAME:”, NS INITS = *” INIT$ = INITS + LEFTS (N$, 1) FOR I = 1 TO LEN (NS) A$ = MIDS(N$, I, 1) IF A$ =“ ” THEN INIT$ = INITS + *.” + MID$ (N$, I + 1, 1) NEXT I INITS = INIT$ + >.” PRINT INIT$ END Scan eer as Fig, 9.14 Output of Program 14 es C$ = UCASE$ (C$) eee gor cs ie Reticence = “2” on co = “I” OR CF ~ +1 NEXT T E STRING 18”; NOV a program to Program 15: Write accept g name and display the name in the short form cus. REM To display name in short form INPUT “ENTER YOUR NAME:”; NS SHNM$ = ~” SHNM$ = SHNM$ + LEFT$ (NS, 1) FOR I = 1 TO LEN (NS) A$ = MID$ (NS, I, 1) IF AS =“ ” THEN SHNMS = SHNMS + + MIDS(N$, I + 1, 1) IFAS =“ ” THEN C = 1 +1 NEXT I D = LEN (N$) - c SHNM$ = SHNMS + RIGHTS (NS, D) PRINT SHNMS END emt a te ae ane oa Fig. 9.15 Output of Program |5 i = Noy pt a orm, 6. LCASES ()—This function helps to convert general syntax of the function is LCASES (4 command, Any other ch: a string into all lowercase letters. The ). Only capital letters are aff oe fected by this aracter remains unch: For example, the part of code ABC DEF ghi 123 @ PRINT LCASES (AS) will display abe def ghi 123 @. UCASES ( )—This function is just the reverse of LCASES ( ) and helps to convert a string into all UPPERCASE letters. The general syntax of the function is UCASES (A$). Only small letters are affected by this command. Any other character remains unchanged. For example, the part of code: AG= “abc def GHI 123 $” PRINT UCASES (AS) will display— ABC DEF GHI 123 S. : bi acei: SASE 2 may be used to perform “case-insensitive” tests ee oa ee ee Thus, there is no need to check for both uppercase and lowerease when comparing wo sings For example, the part ofa program: Bieipus and wo to stop”, CHOICES INPUT “TYPe ae es” THEN vr genses conorce’) = “¥ IF LAs in ee oor g (cnorces) = “A ‘THEN Exsev coro Tt colt!” use PP wrong oe EI goro start eND TF see y ean TDEPE To sg VES, Yes, yes, Yes or YES, tll its first converted to yes ere, even if Pee eeeil Inputs are validated. Otherwise we would have to check for al then cheek rue for checking ‘no’ ane om serorael: Same ist o Program 16: Predict the output of the following code: cps ps FOR I = 0 to 10 PUTER re PRINT SPACE$ (I); “COMPUTER” ota et Sa Beer't cata ihe END a Thus, it may be used for generation of patterns. 10. TAB ()—This function returns the number of spaces that is passed to the function. il. STRINGS ( )—This function helps to print * A ‘The general syntax of this function is SURINGS (uum to be displayed), For example, the part of code: a”) will display PRINT STRINGS (15 @@OG@O@OQDAQQOU This could have been done by the command —PR™T a FOR loop. But STRINGS () is much more efficient in doing the same, It can al display a particular pattern or display a particular screen 1 SPACES (- modification of the STRINGS () which help: of the function is SPACES (number of utive spaces. The general syntax display cons: occurrences). For example, the part of code PRINT “PROGRAMMING IN”; SPACE$ (15) will display PROGRAMMING IN QBASIC, that is, 15 spaces are present b “PROGRAMMING IN” and “QBASIC”. ‘QBASIC en See a ma Fig. 9.16 Output of Program 16 s. For The general syntax of the function is TAB (n), where ‘n’ is the number of spa example, the part of code: PRINT TAB (10); “SUHINA RAY” will display— SUHINA RAY after 10 blank spaces, INSTR ()—This function helps to search one string within another string. The gene! syntax of the function is INSTR (source string, search string). This returns the inde number of the first occurrence of starting position of the search string, if found. If mt found, it returns 0. ys grat 10: Write a program to Accept 1 wae THEW ao cee aes cee PRINT “THE GREATEST NUMBER IS”, MAX END Fig. 9.19 Output of Program 19 This program finds the largest of N numbers. First, the total numbers to be keyed in is asked from the user. The first number is taken from the user separately and is stored as the maximum number MAX. The FOR loop is then used to run the loop N — 1 times. Each time, if the number entered by the user is greater than the previous MAX value, then it is r is displayed after the end of the FOR loop eplaced by the new maximum, Finally, the MA) SERIES PROGRAMMING Exponential Series with ONE Unknown Term Program 20: Write @ program to find the sum of the following series: 1x2? + 232 <3 ---N terms. [N needs to be entered by the user] i: pee te 2 S862 +N TeRUs CLS TERM = 0 SUM = 0 pypot ENTER THE 2110" oS fe = ek (DA) 2 ERs 17 TERM PRINT TE aaa suM = SUM + TERM ext I cae paint “THE SUM OF THE SERIES 18”, sum Fig 9.20 Output of Program 20 =xD In this program, first the unknown value ‘N’ is taken from the user. The loop is run from 1 to Nand the term is generated by multiplying I and the square of the next value of I. The term so generated is displayed. The SUM stores the addition of these terms. Finally, the SUM is displayed. Exponential series with TWO unknown terms Program 21: Write a program to find the sum of the following series: X + X° +X’ + X'+ ...N terms. [X and N needs to be entered by the user] REM X + XA2 + X03 + M4 N TERMS cis TERM = 0 sum = 0 ue OF N”, N Fig. 9.21 Output of Program 21 INPUT “ENTER THE VALI INPOT “ENTER THE VALUE OF X7% FOR I = 1 TON erm = x * I % jc except that the second unknown term is also accepted. ith the same log! This series works with nes used fo generate the term. This term raised ¢© the Power rence im tofind the sum of the following series: 10 + 20+ 40 + 80 + 160 entered by the user] NumberSeries witha 7 Program 22: MictesE™ roe . [N needs 10 + Nem oe REM crs TERM eno. suM = 0 INPUT “ENTER THE VALUE OF N”,W FOR I = 170 N PRINT TERM SUM = SUM + TERM TERM = TERM * 2 NEXT I PRINT “THE SUM IS”, SUM ad i Tt Pere the fret terms taken as the starting value of TERM and displayed. The next term ig generated by doubling the previous term, Program 23: Write a program to find the sum of the following series 10 +20 + 40 + 70 + 110 + ...N terms. [N needs to be entered by the user ] REM 10 + 20 + 40 + 70 + 110 +.N terms cis TERM = 10 SUM = 0 DIFF = 10 Piece usiecked INPUT “ENTER THE VALUE OF N”, N FOR I = 1 70 N PRINT TERM SUM = SUM + TERM TERM = TERM + DIFF DIFF = DIFF + 10 NEXT I Fig. 9.23 Output of Program 23 PRINT “THE SUM IS”, SUM Factorial Series A factorial ofa Positive number is defined as the product of all natural numbers till that number By convention, factorial of zero is taken to be 1. For example, 5!= 5 x 4.x 3x2 |= 120. Program 24: Write a program to find the sum of the follow: ing series: |! +21 +3144!+..N! [N needs to be entered by the user] pecuies: 112! + 3! + 41 Method 1: gem FACTORIAL SERIES Pepe 2 + St + ae tnt som = 0 yact = 2 qweur “ENTER THE VALUE OF N”, y yoRI=1 TON FACT = FACT * I PRINT FACT SUM = SUM + FACT NEXT I PRINT “THE SUM IS”, SUM END In this method, the factorial is found within a single FOR loop and used as a term. As FACT = Lis present outside the loop, so each and every time the previous stored value of the FACT is multiplied with the new value of Ito give the next factorial value. thod | (a) Output ‘of Program 24 Met Series with 2 8 Es cont he following series CO Be tbe used to dea! Wi (75: Write a Proet Progra: 2 #4 to be ente’ by! [N net these series: a the usetl ofind the sum ofthe following series: 124.3 44 Method 2; REM FACTORIAL SERIES REM 1! + 214 3! 4.n1 SUM = 0 INPUT “ENTER THE VALUE OF N’, N FOR I = 1710 FACT = 1 FOR J = 1701 FACT = FACT * 3 NEXT 3 PRINT FACT SUM = sum + FACT NEXT 1 PRINT “THE SUM IS”, SUM END In this case, the factorial logic is isolated and kept inside a NESTED FOR loop. This TED FOR loop finds out the factorial separately each and every time. So, the FACT initialised inside the outer FOR loop [ne nad (b) Output of Program 24 Method 2 Fig. 9.24 alteanate positive and negative signs, The following two ways N terms, Method 2 ‘Method 1: REM SIGN TOGGLE 9 \ Rena -2+3- 4 +....N TERY al : ENPOT “ENTER THE VALUE OF N ay INPUT “EN i TERM = 0 sun = 0 ‘a ; FORI=1 70 ee 3 TERM = SIGN * I ae = PRINT TERM; oes | SUM = SUM + TERN ELSE T = END IF SIGN = SIGN * -1 NEXT I PRINT PRINT “THE SUM OF THE SERIES IS”, SUM END In this case, the term is generated separately SUM = SUM + T PRINT T NEXT I PRINT “THE SUM IS”, suM END as the previous examples. But the term is multiplied with a variable called SIGN, each and every time. The SIGN variable is toggled by multiplying itself with every time. Thus, it becomes | for the first time and —1 for the next time. When this is multiplied with the term, the entire term becomes positive or This method performs the same checks the position of the term. If the pos is odd, then —1 is multiplied, whereas if th term is even, the term is kept the : ne negative. Se a yaw: (@) Output of Ey cieeam2s Method 1 (b) Output of Program 25 Method 2 Fig, 9.25 Fibonacci Series A fibonacci series is a speci i : ee ne Ce of series where the third and subsequent terms are generated is. The series begins with 1 and 1 as the first two terms. Program 26: Write a entered by the user], splay first Nt go 4isP ems of eM Fibonaco; gs First = 1 gecoND = 0 qatRD = 0 ywpur “ENTER THE NUMBER OF TEpys, nN a” pe THIRD = FIRST + sEconp PRINT THIRD FIRST = SECOND SECOND = THIRD NEXT I END Mechanism of working (Dry Run) (For N ip exists in a Fibonacci series. So, FIRST is As seen in the dry run, Be ah by back calculating. Each and every time the initialised as 1 and SECON FIRST and SECOND. The terms are then reformed by third term is displayed byes TaFIRST and THIRD in SECOND sequentially. In the above storing the value ot a his series starts with 1 and 1, However, in some references, this example, it is assumed tks the initial terms of the series. Then, using the same diagonal series starts with © and’ gulated thatthe first erm should be initialised with 1 and the second relationship. ie sth | (instead of 1 and O respectively) to use the same logie and term shoul code. site Numbers po: fect, primeand e {asa number which is equal tothe sum of its factors, excluding the ‘a rect muaber is On Mramiber is defined as a number which is divisible only by 1 and the Apert aselt: A PPM. ce mumber is a non-prime number m to determine whether Program 27: Write a prog ‘or ‘composite’ in nature, REM To determine whether an en| FACTCOUNT = 0 SUMFACT = 0 INPUT “ENTER THE NUMBER”, tered number N FORI=170N/2 IF N MOD I = 0 THEN FACTCOUNT = FACTCOUNT + 1 SUMFACT = SUMFACT + I END IF NEXT I PERFECT NUMBER ay Ta emt Ree ay eo Output of Program 27 run multiple ti IF SUMFACT = N THEN PRINT EF PACTCOONT = 1 THEN PRINT “PRIME NUMBER” ELSE PRINT “COMPOSITE NuwpER END ‘After the number is entered, the loop is run from I to half of the number (N/2) as a number then divided by the loop control variable | cannot have a factor more than N/2. The numbet to find out the remainder. If the remainder is 0, it proves that it is a factor. If I is a factor then, the count of factors is increased by | and the value of I is added to the sum of factors, Ifthe sum of factors excluding the number is equal to the number itself then it is considered to bea perfect number. For a prime number, the count of factors is always 1 if the number itself is not considered to be a factor. So, the count of factors is checked and accordingly computed. If the count of factors is more than 1, it is a composite number. WHILE-WEND LOOP Program 28: Write a program to find the HCF of two numbers, DAC uan ena m fa Seats as oi TE ELSE NRE z0 Enrotisiiren rin scom women. 9 eed WHILE A <> B i ie ae ee 8 a ie len ai PRINT “THE HCF 8”, a ‘ i Ee rN f Fig. 9.28 Output of Program 28 run multiple times «two numbers are taken. A loop is run till than the second, then the sec The final value of the both the numbers cond number is subtracted r first number is the HCF pirst umber iS greatcl reverse is done are equal. If the first repeatedly. Otherwise, the 29; Write a program to displ Preven 2 ay the number of digits gits an entered number contains, qu to display the number of digits of a number gem LEFT TO RIGHT ywpur “ENTER THE NUMBER”, N copy = ABS (N) NoORDIGIT = 0 Pinaceae ag eu: copy = copy / 10 be A ade THE NUMBER aye ean naa WHILE COPY > 0 NOOFDIGIT = NOOFDIGIT + 1 WEND Fig 9.29 Output of Program 29 run PRINT “NUMBER OF DIGIT”; NOOFDIGIT multiple times END In this program, the absolute value of ‘N’ numbers. Then, the digits are chopped from # Each and every time, a counter is incremented. This gives till the number has no digits left. is taken so that the logic works also for n he right, one ata time and the number is curtailed isthe required result as this continues oa number whose sum of cubes of the individual digits is equal to the An Armstrong number 6 a determine whether an entered number is an Armstrong Program 30: Write # program {© number or not. mine ered number is Armstrong or not eeeses = on PR re Oat aes REM To dete? = ‘yOMBER”, wgnrer THE os INPUT TEs LU aly eiea IC MO LUSH SD oun sum = ° Pea Ca ase x MMC Meee cor’ = ee, aaa ass od saan Tem ya waite se copy MoD 10 (pea eM) ed POMBE eM Un) aes corer * >) Ai Oem al a _ ie Fig. 9.30 Output of Program 30 run multiple times END IF END Here exh digit found by chopping the digits from the right (similar t9 Program 21) be ofthe digit. This is added to the sum. If it is equal to the a D453 to the power 3 to find the cul imstrong number. For example, 15 number, then it is considered to be an Ar ts of a number from left t left to righ Program 31: Write a program to display the individual digi Few Wo display the individual digits from left to right cs INPUT “ENTER THE NUMBER”, N COPY = N NOOFDIGIT = 0 WHILE COPY > 0 Paci Copy = Copy / 10 NOOFDIGIT = NOOFDIGIT + 1 Fig. 931 Output of Program 31 WEND corr = WHILE COPY > 0 DIGIT = rN? (copy / (10 * (NooFDIGIT - 1))) PRINT DIGIT cory = cor PY MOP (10 * (NoOFDIGIT - 1)) NOOEDIGIT. = NOOFDIGIT - 1 WEND END In this program, fist first the number of digits j integer value of the division cia 's found. Then, the digits are extracted by taking the remainder in the same logic er by 10%oFs-1 The number is reformed by taking [D LOOPS ay be present inside NESTE! 13 mi anothey 00? her loo, or loop are known as ne another loop n aS nested loops, one FOR-NEXT loop may be place sarables Should be given unique name Mrested 1oop, the inner loop should end the nested for loop is as follows: FOR I = 1 TO 10 FOR J = 1 TO 10 [-FOR K = 1 70 19 NEXT J NEXT I Patterns Using Nested For P: These types of loops th p PS that contain one Jo "OP inside The NESTED FOR loops may be used to make interesting patterns. Generally, in a pattern, the outer loop denotes the number of rows to be displayed whereas the inner loop denotes the number of elements to be printed in each row. Program 32: Write a program to display the following pattern. REM PATTERN CLS INPUT “ENTER THE NUMBER OF ROWS", FOR I= 1 TO N FOR J = 1 TO I PRINT NEXT J PRINT NEXT 1 END In this pattern, ‘I” number of rows that aie in the outer lo0P pene the user Wan! es 1 thei decides the 1 and every is ee ie aves Note ee jn this 698° time J displays 1 poe patter Thus, it displays # i Program 33: Write a program to display the following pattern. REM PATTERN CLS ENPUT “ENTER THE NUMBER OF FOS”, poRT=170N yor J = 170 2 PRIN? J; Next J PRINT NEXT I END ‘This pattern is similar tothe previous pattem gs the combination of ‘T and ‘J* generates a triangular pattern The oaly difference is that it prints the value of J” instead of the fixed value of 1. Fig. 9.32 Output of Program 32 Program 34: Write a program to display the following REM PATTERN cs. qeeUT “ENTER THE NUMBER OF ROWS”, N FOR I =10N FOR J=1 701 PRINT I; ig. 9.34 Output of Program 34 NEXT J PRINT NEXT I END Inthis pattern, the combination of ‘I’ and ‘J” it prints the value of ‘I’ instead of the fixed value of 1. Note that the program runs fine till the 9th row. Since there are 2 digits in each term in the 10th row, the pattern is not formed properly This could have been eliminated by adding a comma or a tab space after the term. But this takes the output to the next line. Thus, the behaviour of the pattern also depends on the sereen size and the number of elements it can support. generates a triangular shape. Unlike Program Program 35: Write a program to display the following pattern. REM PATTERN eee C:DOCUME- 1\ughosarDeskto... TD INPUT “ENTER THE NUMBER OF ROWS”, N IME FOR I = N T0 1 STEP -1 FOR J = 1701 Fig. 9.35 Output of Program 35 pot ort gD H patter - ine value of ‘I’ starts from N and goe goes to 1. Th us, it gen generates a ‘rey a “reverse tr 80S’ prin and every time, the value of 9, Each , decreases by | cm m less than th paTTERN WITH SPACES program 36: Write a program to generate the Py 7: ae re 37: Write a program to generate th following pattern: ee (Remus Fig. 9.36 Output of Program 36 Fig. 9.37 Output of Program 37 REM PATTERN REM PATTERN cus cLs N INPUT “ENTER THE NUMBER OF ROWS”, N INPUT “ENTER THE NUMBER OF ROWS", FOR I = NTO 1 STEP-1 FOR I = 170 N FOR J 1 Torr ens Bf0.F ee: pRINt “*” eure Next J Son Secreto ae) ae PRINT PRINT ~ ” ext SPACE NEXT SPACE mong = 1 70 7 FOR J = 1 TO It print “*" PRINT “*"7 NEXT J NEXT J PRINT PRINT NEXT I next END END. ——— 48, the terms are printed twice, with spaces jn shown in Programs 27 and 28, Be, cenerstng ca The space increases from 1 to [(N ~ 2) -( er blank « Fibonacci series: a special series where the third term is a sum of the first two terms Factorial of a number: the product ofall ‘the natural numbers till that number “Armstrong number: a number whose sum of cubes of the digits is equal to the number iber which has only number itself be ASSESSMENT ZONE Choose the correct answer. _ What function returns 0 ifthe first character ofthe string is not a digit? Oa (VAL 2. Which of the following does not return a number? (qd) INSTR, ieee WSs (Asc (d) CHRS annot extract one js function © FAC fj a LEFTS ORiGHts "Ne string ¢ nction returns a positive y wien st P : tive Value for both» ©) MIDS SGN (INT POSTE ad nepaive INSTR wich fnction eUCAES THE Value ofan jn SQR ee @nt (6) CINT iat ans (©) FIX sue ter the fOlIOWINE Statements gee 4? operator helps to concatenate Ue OF False {Gone otha a : Ie WO strings be F spe LEFTS function extracts characters fom ye 2 Mhidate of string function is # group of statements that must rn ji tbe UCASES converts all the characters present ant 4 he CALL statement i used 10 call a function The LEN statement does not count the leading spaces + tsing 2 NESTED for loop is compulsory for writing» ‘thin a str String to capital teters, string, factorial series program, yillin the blanks using the words given in the box, VAL 2 1S Lowercase =14 INSTR i is a conversion function, 2, The LCASES function converts a string into 3, CINT (14.2) will return 4 gives the absolute value of a number. 5, INT (-14.2) will return —___. function searches for a string within another string. 6, The , Answer the following questions. 1. Differentiate between: : (@) Subroutine and Function (b) INT and FIX (@)INTand CINT (d) LEFTS and RIGHTS (e) UCASES and LCASES (f) TAB and SPACES (g)ASC and CHRS (h) VAL and STRS 2. Describe the following functions: - (@ABS (0) SQR © so NS (LEN (e) TAB i) 3. Why is the CALL keyword used? 4, How can you use the MIDS to simulate LEFTS? | 5. Wite a statement to extrac ‘put’ from ‘COMPUM «te by B 6 Using Iv, write a statement 1 display WHEE 7. What is the output of the statement PEND ee 8. What type of values can the + operator ee wt ares BES "5. Wats the range of values supported ty CN"” ue is notin range? By Goive tne crossword using the sive” < ines. Ez ae fone ee = 3. This function truncate: 5. This function displays the cha cat ASCII code 6. This function returns ~ 1 if the number negative {0 display prime numbers till 100. program to accept a string and display the number of words present in that string. program to accept a string and display the numberof digits present in that string Wirite a program to display all the ASCH eodes from 0 0 127 and thei equivalent characters

You might also like