Approved by Curriculum Development Centre 251 Oasis Radiant Computer Science, Book 10 READ N PRINT MID$(S$, N, 1) NEXT I END SUB i) What is missing in the above programme? ii) What will be the output if we change the data by 3,7,5,7,8 b) DECLARE FUNCTION CELL$(W$) W$= “CYBER” PRINT CELL$(W$) END FUNCTION CELL$(W$) S= LEN(W$) FOR K= S TO 1 STEP-2 M$=M$+MID$ (W$,I,1) NEXT I CELL$=M$ END FUNCTION i) Why is $ sing given with function name? ii) What is the name of sing “+” used in the above programme and what operation does it perform. c) DECLARE SUB TEST(A,B) INPUT “Enter tow numbers”; X, Y CALL TEST (X, Y) PRINT X END SUB TEST (S, K) FOR I = S TO K P=P+3 NEXT I PRINT P END SUB i) What will be the output of the programme if user inputs 3, 4 for the variables X, Y respectively? ii) List the local variable used in the above programme.
Oasis Radiant Computer Science, Book 10 252 Approved by Curriculum Development Centre d) DECLARE FUNCTION BIG(A) PRINT BIG(A) DATA 5,7,21,2,3,34,59 END FUNCTION BIG(A) B=0 FOR K=1 TO 8 READ X IF A>B THEN B=X NEXT K BIG=B END FUNCTION i) List local variables from function procedure. ii) List loop structure from the programme. e) DECLARE SUB SERIES (X, Y) CLS CALL SERIES (4, 4) END SUB SERIES (S, K) C=0 FOR R=1 TO 5 PRINT S; C=S+K S=K K=C NEXT R END SUB i) List the actual and formal parameters used in the above programme. ii) What will be value of C when loop completes fourth time. f) DECLARE FUNCTION Result(N) PRINT Result (16) END FUNCTION Result (N) WHILE N<>0 A= N MOD 2
Approved by Curriculum Development Centre 253 Oasis Radiant Computer Science, Book 10 N=N\2 E$=STR$(A) F$=E$+F$ WEND RT=VAL(F$) Result= RT END FUNCTION i) Write the output of the above program. ii) What happens if we write the statement F$=E$+F$ as F$=F$+E$ g) DECLARE FUNCTION Factorial (N) CLS INPUT “Enter a number”; N END FUNCTION Factorial(N) FOR I= 1 TO N S=S+I NEXT I Factorial=S END FUNCTION i) What will be the output of the programme, if the user supplies 5 as the value of N? ii) Re-write the same programme using DO…LOOP UNTIL statement.
Oasis Radiant Computer Science, Book 10 254 Approved by Curriculum Development Centre Chapter 10 File Handling ffl Processing files in QBASIC ffl Closing a file ffl Reading data from a file ffl Accessing a random file THIS CHAPTER COVERS :
Approved by Curriculum Development Centre 255 Oasis Radiant Computer Science, Book 10 File Handling 9 Chapter Processing Files in Basic Introduction We have so far discussed programmes where data is supplied either through READ... DATA statements or through INPUT statements. But it is difficult to handle large volume of data with the help of these statements. Moreover, data stored in one programme cannot be shared by other programmes. The above limitations can be overcome by placing the data into a separate storage area called a data file. A data file forms an essential framework of a data processing system. It is a collection of data organised in a specific format and for a specific purpose, which is kept somewhere in external memory. A file can be described as a collection of records where a record consists of number of data values, which are either produced by a computer as per the instructions of a programme or given to the computer as a data. A typical data processing system may consist of many files. Many records in a file contain detailed information about some aspect of the system. For example, a “pay file” may contain one record for each employee containing all the particulars such as Employee Code, Name, Address, Basic pay, HRA, DA, CCA, Designation, Sex, etc. Each partition is a data item and is referred to as a field. A number of BASIC Programmes can use this file as input. File handling methods differ widely from system to system. In this lesson, we will discuss the methods that are currently used in most of the IBM compatible systems. Types of Files Depending on the way in which the data is stored and accessed, files are categorised as: • Sequential access files • Direct (Random) access files
Oasis Radiant Computer Science, Book 10 256 Approved by Curriculum Development Centre Sequential Access Files These files may be created on a magnetic tape or disk. Data from these files is read sequentially, item after item, starting at the beginning. Though sequential access file is easy to handle, yet it has a serious disadvantage. In the sequential file we cannot change the existing entry or insert a new entry. To do this, we should copy the entire content to another file making the changes on the way and then copy the correct data back in to the original file. Another disadvantage is that we cannot simply locate or go back to read a particular data item. A disk consists of a number of concentric circles known as tracks. The data items are stored on these tracks sequentially. Random Access Files Random access files are created on disks to allow us to read or write from the files in random order. Random access files allow more flexible access than the sequential files. You can read or write any record directly in a random file without searching through all the records that precede it. Thus, reading and writing of data is faster. Handling of Sequential Files Using data files would require the incorporation of statements in your programme to perform the following functions: • Giving a name to the file • Opening the file • Writing to or reading from the file • Closing the file Naming a File A file is identified by its file specifications. It is of the form: Device name: File name The device name tells the system which device to look for the file and the file name tells which file to look for on that device. The device name should be followed by a colon as indicated. Examples are: A: SUYASHA C: STUDENT.TXT The device names A and C indicate the floppy and hard disk drives respectively
Approved by Curriculum Development Centre 257 Oasis Radiant Computer Science, Book 10 File names can have a maximum of eight characters. However, the files stored on disks may have a file name extension in the following form. SUYASHA.TXT The extension consists of a period and is followed by three letters. When you use longer file name, one of the following conditions may occur. File Name Result 1. Extension is longer than three characters. 1. Extra characters are truncated. 2. Name is longer than eight characters. 2. A period is inserted after the eighth character and extra characters (up to three) are used as the extension. 3. Name is longer than eight characters and extension is included. 3. Gives an error. Opening a File It is necessary to establish a line of communication between a programme and a file that is to be used before data can be read from or written to that file. This is achieved by using the OPEN command as shown below: OPEN [“Mode”, #file number, “file name”] Mode is a string constant and takes one of the following three forms: • O for sequential output file • I for sequential input file • R for random input/output file It should be noted that the mode is enclosed in quotation marks. File number is an integer number and can be any number between 1 and 15. It is a unique number associated with the actual physical file. A file number may be a number, variable, or expression. File name specifies the particular file to be used. This should conform to the specifications of the file when it was created. File names must be enclosed in quotations.
Oasis Radiant Computer Science, Book 10 258 Approved by Curriculum Development Centre Examples of opening sequential files for input and output operations are: OPEN “I” # 1, “ SUYASHA.TXT” OPEN “O”, # 3, “SUYASH” These can also be written as OPEN “SUYASHA.TXT” FOR INPUT AS# 1 OPEN “SUYASH” FOR OUTPUT AS #3 If a file opened for input operation does not exist, a “FILE NOT FOUND” error will be shown on the screen. If a file, which does not exist, is opened, in that case file will be created. It is important to note that opening a file for output destroys the existing data in that file. Closing a File A previously opened file can be closed using the CLOSE statement as follows CLOSE [# file number, #file number, ......] The file number is the number used in the OPEN statement. For example, the statement. CLOSE #1, # 3 Causes the files with file numbers 1 and 3 to be closed. The CLOSE statement is used when you have finished processing data from a file. A CLOSE statement with no file numbers specified causes all files that have been opened to be closed. You should also note that execution of END and RUN statements also causes all open sequential files to be automatically closed. However, STOP does not close any files. Writing Data to a File We may write data to a sequential file using either of the following two statements. PRINT [# file number, list of variables] WRITE [ #file number, list of variables ] File number refers to the file designator used when the file was opened for output. List of variables specifies the data that is to be written to the file. The difference between PRINT # and WRITE # Statements is that WRITE # inserts commas between the data items and quotation marks for strings while PRINT # causes data to be written without any delimiters (commas, etc.). For example, consider the statement
Approved by Curriculum Development Centre 259 Oasis Radiant Computer Science, Book 10 PRINT #1 N $, AMT In case N $ = “ Sampada” and AMT = 2000, the Statement would write the following image to the file 1: Sampada 2000 The statement WRITE # 1, N $, AMT would write the following image to the file 1: “Sampada”, 2000 The delimiters are useful when we try to read the data with an INPUT # statement. Let us take an example for proper understanding of the use of “WRITE” and “PRINT” statement. Example REM *** PROGRAM INVENTI *** REM -- PNM$ PART NAME REM -- PN PART NUMBER REM -- P PRICE REM -- QTY QUANTITY OPEN “O”, # 1, “SUYASHA.TXT” FOR I =1 TO 3 INPUT “NAME” ; PNM$ INPUT “NUMBER” PN INPUT “PRICE” P INPUT “QUANTITY” ; QTY WRITE # 1, PNM$, PN, P, QTY PRINT NEXT I CLOSE #1 END
Oasis Radiant Computer Science, Book 10 260 Approved by Curriculum Development Centre Output NAME? AAAA NUMBER? 101 PRICE? 8 QUANTITY? 100 NAME? BBBB NUMBER? 102 PRICE? 10 QUANTITY? 200 NAME? CCCC NUMBER? 103 PRICE? 12 QUANTITY? 300 Reading Data from a File Data can be read from a sequential file using the INPUT # statement. It takes the form INPUT [ # file number, list of variables ] The following INPUT # statement can be used to read data from the file SUYASHA. TXT: INPUT #1, PNM$, PN, P, QTY The type of data in the file must match the type specified in the list. Unlike INPUT, no question mark is displayed with INPUT #. The following example will illustrate clearly the use of INPUT # statement. Example Write a programme to read inventory data stored in the file SUYASHA.DAT inventory and print the table with the value of each product. REM ** PROGRAM INVENT 2 **
Approved by Curriculum Development Centre 261 Oasis Radiant Computer Science, Book 10 OPEN I”,#1, “SUYASHA.TXTT” PRINT “PRODUCT NAME”,”NUMBER”, “ PRICE”, “QUANTITY”, “ VALUE “ PRINT CH: INPUT #1 PNM$, PN, P, QTY LET V= P* QTY PRINT PNM$, PN, P, QTY, V GOTO CH CLOSE END Output PRODUCT NAME NUMBBERPRICE QUANTITY VALUE AAAA 101 8 100 800 BBBB 102 10 200 2000 CCCC 103 12 300 3600 This programme reads sequentially, every item in the file. When all the data have been read, line 5 causes an “Input past end” error. This can be avoided by using the EOF function. This function tests for end of file and the control is directed appropriately. The end of the file is indicated by a special character in the file. We can modify the above programme as follows: REM ** PROGRAM INVENT 2** OPEN “I”, #1 “SUYASHA.TXT” PRINT “PRODUCT NAME”,”NUMBER”, “ PRICE”, “QUANTITY”, “ VALUE “ PRINT CH: IF EOF (1) THEN 100 INPUT #1, PNM$, PN, P, QTY LET V = P*QTY PRINT PNM$, PN, P, QTY, V GOTO 50 CLOSE END
Oasis Radiant Computer Science, Book 10 262 Approved by Curriculum Development Centre Reading Lines from a File The LINE INPUT # statement may be used to read an entire line, ignoring delimiters, from a sequential file and assign to a string variable. It is of the form LINE INPUT [ #file number, string variable ] File number is the number under which the file was opened and string variable is used to store a line of string constant. LINE INPUT # reads all characters in the sequential file up to a carriage return which was inserted by the PRINT # statement. The next LINE INPUT # reads all characters up to the next carriage return. Example below illustrates the use of LINE INPUT #statement. Example Write a programme to input employee addresses from the keyboard, store them in a file named ADDRESS, and read back to produce a list. REM ** PROGRAM EMPLOYEE ** REM ** INPUT EMPLOYEE ADDRESS THROUGH KEYBOARD ** OPEN “O “, #1 “ADDRESS” FOR I = 1TO 3 LINE INPUT “TYPE IN ADDRESS” ADDR$ PRINT # 1 ADDR$ NEXT I CLOSE 1 PRINT OPEN : “I” # 1, “ADDRRESS” FOR I= 1 TO 3 LINE INPUT # 1, ADDR$ PRINT ADDR$ NEXT I CLOSE 1 END Output TYPE IN ADDRESSES? Shankar Adhikary, Bhorletar, Lamjung TYPE IN ADDRESSES? Suyash Adhikary, Manamaiju, Kathmandu TYPE IN ADDRESSES? Suyasha Adhikary, Samakhusi, Kathmandu Shankar Adhikary,
Approved by Curriculum Development Centre 263 Oasis Radiant Computer Science, Book 10 Bhorletar, Lamjung Suyash Adhikary, Manamaiju, Kathmandu Suyasha Adhikary, Samakhusi, Kathmandu Adding Data to a Sequential File To add any data to a sequential file that is already residing on a disk, you cannot just open the file and write data to it. You must note that when a sequential file is opened for output, its current contents are lost. In such cases, you should open the file with APPEND. For example, the statements FILE = “ A: TEMP” OPEN FILE FOR APPEND AS #1 will open the file named TEMP on the disk in drive A and position the file pointers at the existing data. Now we can add records to the file, which has been numbered as 1. Following example will illustrate the use of Append Example Write a programme to add two more products to the file “SUYASHA.TXT” created earlier in Example 1. DDDD 104 20.0 200 EEEE 105 30.0 300 FILES = “SUYASHA.TXT” OPEN FILES FOR APPEND AS #1 FOR I=1 TO 2 INPUT PNM$, PN, P, QTY WRITE #1, PNM$, PN, P, QTY NEXT I CLOSE # 1 REM ** DATA INPUT FROM FILES ** OPEN “I”, #1, “INVENT. DTA PRINT HH:
Oasis Radiant Computer Science, Book 10 264 Approved by Curriculum Development Centre IF EOF (1) THEN E INPUT #1, PNM$, PN, P, QTY PRINT PNM$, PN, P, QTY GOTO HH CLOSE # 1 E: END Output ? DDDD, 104, 20, 200 ? EEEE, 105, 30, 300 AAAA 101 8 100 BBBB 102 10 200 CCCC 103 12 300 DDDD 104 20 200 EEEE 105 30 300 Handling of Random Access Files Unlike sequential files, random files cannot be created so easily. Random files require more programming steps and skills. However, since random access files effectively retrieve or write individual data items anywhere in the file they are often preferred. Creating a Random File Following are the steps required to create a random file: Open the file Allocate space in the random buffer for variables that will be written to the file Move the data into the random buffer Write the data from the buffer to the disk
Approved by Curriculum Development Centre 265 Oasis Radiant Computer Science, Book 10 Step 1: Like sequential files, we may open random files using the OPEN Statement. OPEN [“R”, #File number,”File name”,Record length] The character R indicates that the file to be opened is a random access file. Record length is a number that specifies the length of records. The length may range from 1 to 32767. The default record length is 128 bytes. For examples, OPEN “R”, #2, “SUYASH’,100 OPEN “R”,#3, “LACHHIMA”,120 These statements can also be written as OPEN “SUYASH” AS#2LEN =100 OPEN “LACHHIMA” AS #3 LEN = 120 Step 2: Space in the random buffer is allocated by the FIELD statement in the form FIELD [#file number, w1 AS u1, w2 AS u2...] File number is the number of the concerned file just opened; w specifies the number of character positions to be allocated to the string variable and so on. A FIELD statement defines variables that are used to put data into or get data out of a random buffer. For example, the statement FIELD #2, 20 AS A$ 10 AS B$ defines two string variables A$ and B$ and allocates first 20 bytes to the variable A$ and next bytes to B$. Note that FIELD is a declaration statement and does not actually place data into the random buffer. Unlike sequential files, random files cannot be created so easily. Random files require more programming steps and skills. However, since random access files effectively retrieve or write individual data items anywhere in the life, they are often preferred. The total number of bytes allocated in a FIELD statement must not exceed the record length specified in the OPEN statement. For instance, the statements OPEN “R”,#2 “CHAP1”,40 FIELD #2,20 AS A$, 5 AS B$, 10 AS C$, 10 AS D$ open a file named CHAP1 as a random file and allocates character positions as follows:
Oasis Radiant Computer Science, Book 10 266 Approved by Curriculum Development Centre First 20 bytes to A$ Next 5 bytes to B$ Next 10 bytes to C$ Next 10 bytes to D$ Note that the total number of bytes allocated is 45, which is more than 40, the record length as defined in the OPEN statement in line 10. In this case, a “Field overflow” error will appear on the screen. Step 3: Placing data into the random file buffer is done by the LSET and RSET statements. They take the form: LSET u$ = x $ RSET u$ = x $ Where u$ is the name of a string variable that is defined in a FIELD statement and x$ is a string variable representing the data to be placed into the field identified by u$. Examples of these statements are: LSET A$ = F1$ RSET B$ = F2$ LSET statement left-justifies the string in the field, and RSET statement right justifies the string. Let us suppose F1$ represents CONNECTING-PROD and F2$ represents 5000. If the character positions allocated to A$ is 18 and B$ is 5, then the field represented by A$ and B$ in the random buffer are filled like this: C O N N E C T I N G - P R O D 5 0 0 0 Since all the fields in a random buffer are defined as string fields, any number value that is to be placed in a random file buffer must be converted to string value before it is LSET or RSET. This can be done using the following `convert’ functions. MKI$ converts an integer to a 2-byte string. MKS$ converts a single-precision number to a 4-byte string. MKD$ converts a double-precision number to an 8-byte string. LSET A$ MKI$ ( integer variable) or RSET A$ MKD$ (double-precision variable) Where A$ is the string variable defined in the FIELD statement. For example LSET A$ - MKI$(RN) RSET B$- MKS$ (PAY) Step 4: Moving of data from a random buffer to a random file is done by the PUT statement. Each time a PUT statement is executed, a record is written to the file. PUT {# file number, record number]
Approved by Curriculum Development Centre 267 Oasis Radiant Computer Science, Book 10 File number refers to the number under which the file was opened. Record number is the number of the record to be written and expressed as an integer constant or variable. If record number is omitted, the record will have the next available number. For example, the statement PUT #2, 1 will write the information contained in the buffer to the first record of the random file numbered 2. It can also be written as PUT #2,K Where K is an integer variable. The value of K must be defined before using the PUT statement. Each time a PUT statement is executed, a record is written to the file. Let us take an example to clarify various statements discussed for creating a random file. Example Write a programme to open a random and record salary file statement of employees with the following details: Name Basic Pay D.A. H.R.A. C.C.A. Assume the following data: Name Basic Pay D.A. H.R.A. C.C.A. UPAMA 25,000 5000 8000 2000 SHREEYA 20,000 4000 7000 1500 ALINA 15,000 3000 6000 1000 REM ** CREATION OF RANDOM FILE ** OPEN “ R”,#1,”SALARY” 60 FIELD #1,20 AS N$, 10 AS B$ 10 AS D$, 10 AS H$, 10 AS C$ F: INPUT “RECORD NUMBER”; I IF I=0 THEN GOTO E INPUT “NAME “; A$ INPUT “BASIC PAY”; P INPUT “ DEARNESS ALLOWANCE”; Q INPUT “HOUSE RENT ALLOWANCE”; R INPUT “ COMPENSATORY CITY ALLOWANCE”; S LSET N$ = A$
Oasis Radiant Computer Science, Book 10 268 Approved by Curriculum Development Centre LSET B$ = MKS$ (P) LSET D$ = MKS$ (Q) LSET H$= MKS$ (R) LSET C$ = MKS$ (S) PUT # 1, I GOTO F E: CLOSE # 1 END Output Record Number? 1 Name? UPAMA Basic pay? 25000 Dearness Allowance? 5000 House Rent Allowance? 8000 Compensatory city Allowance ? 2000 Record Number? 10 Name? SHREEYA Basic pay? 20000 DA? 4000 HRA 7000 CCA? 1500 RECORD NUMBER? 40 Name? ALINA Basic Day? 15000 DA? 3000 HRA? 6000 CCA? 1000 Accessing a Random File Like creation, accessing a random file includes the following points: Open the file for random access Allocate space in the random buffer for variable using the FIELD statement that will be read from the file.(Remember that if a program performs both the input and output on the same random file, you may use only one OPEN statement and one FIELD statement)
Approved by Curriculum Development Centre 269 Oasis Radiant Computer Science, Book 10 Bringing data from the file to the buffer for processing Access and use data in the program Step 1: Follow the procedure of step 1 in creating a file. Step 2: Follow the procedure of step 2 in creating a file. Step 3: Bringing data from the file to the buffer is done by the GET statement. This is similar to the PUT statement. GET [#file number, record, number] Record number is optional and, if it is omitted, the next record (after the last GET ) is read into the buffer. For example, GET #2, 10 Will transfer the content of the record number 10 from the file number 2 to the buffer. Step 4: After a GET statement, the data available in the buffer can be used by the program for further manipulation and printing outputs. Remember that the numeric values are recorded as string values in the buffer and therefore all numeric values must be converted back to numbers for performing any arithmetic operations on them: This is done using following “convert” functions: CVI converts a two-byte string to an integer. CVS converts a 4-byte string to a single-precision number. CVD converts an 8-byte string to a double-precision number. These functions are written in the form: x = CVI (u$) x = CVS (u$) x = CVD (u$) u$ is the name of a string variable containing numeric values in the buffer and x is a numeric variable representing the data to be used in the program. The following program segment illustrates the use of GET and convert functions: FIELD #2, 10 AS A$, 6 AS B$, 3 AS C$ GET #2 LET N$ = A$ LET M1 = CVS (B$) LET R1 = CVI (C$) PRINT N$, M1, R1
Oasis Radiant Computer Science, Book 10 270 Approved by Curriculum Development Centre This program uses a random file numbered 2, which has fields as defined in line 4. Line 5 reads a record from the file. Line 6 converts the contents to a singleprecision numeric value and assigns it to the variable MI. Similarly, line 7 converts the contents to an integer number and assigns the value to the variable R1. Line 80 writes the vales of N, MI and R1 on the screen. In this case, N$, M1 and R1 may represent student names, marks and class rank. Note the conversion functions do not change the actual data. They only change the way the data is interpreted. Remember that B$ and C$ were originally numbers which would have been written to the file using the MKS$ and MKI$ functions. Example below will help us in understanding the technique of accessing data stored in random file. Some Examples 1. A data file “salary.txt” contains the information of employees regarding their name, address and salary. Write a programme to copy all the information of employees to the new data file named “newSalary.txt” whose salary is greater than 8000 and less than 12000. OPEN “salary.txt” FOR INPUT AS #1 OPEN “newSalary.txt” FOR OUTPUT AS #2 DO WHILE NOT EOF(1) INPUT #1, A$,B$,S IF S>8000 AND S<12000 THEN WRITE #2,A$,B$,S END IF LOOP CLOSE #1,#2 END 2. Write a programme which reads records from the file “Result. DAT” having the fields Name, and marks of three different subjects and display only those records whose percentage is greater than 60 and less than 80. Also count the total number of records presenting in that data file. OPEN “Result. Dat” FOR INPUT AS #1 DO UNTIL EOF(1)
Approved by Curriculum Development Centre 271 Oasis Radiant Computer Science, Book 10 INPUT #1, A$, B, C, D C=C+1 P= (B+C+D)/3 IF P>60 AND P<80 THEN PRINT A$, B, C, D LOOP PRINT “Total number of records:”; C CLOSE #1: END 3. A sequential data file “DATA.DAT” contains 100 records having fields student’s ID, name, address and class. Write a programme to display from 81st to 90th record from the file. CLS OPEN “DATA.DAT” FOR INPUT AS #1 FOR i = 1 TO 90 INPUT #1, id, n$, a$, c IF i >= 80 THEN PRINT id, n$, a$, c NEXT i CLOSE #1 END 4. Write a programme to display all the records from “records.dat”. Also count how many records have been displayed. CLS OPEN “records.dat” FOR INPUT AS #1 WHILE NOT EOF(1) LINE INPUT #1, s$ PRINT s$ c = c + 1 WEND CLOSE #1 PRINT “No. of records displays = “; c END
Oasis Radiant Computer Science, Book 10 272 Approved by Curriculum Development Centre 5. Write a programme to display all the records from data file “INFO.DAT” whose date of birth is in the current system month. The data file consists of name, date of birth, phone and address as the required fields. OPEN “”INFOR.DAT” FOR INPUT AS #1 SysDate$=MID$(DATE$,1,2) WHILE NOT EOF(1) INPUT#1, NAME$, DOB$, PH$, ADD$ UserDate$=MID$(DOB$,1,2) IF SysDate$=UserDate$ THEN PRINT NAME$,DOB$,PH$,ADD$ WEND CLOSE #1 END 6. Write a programme that asks a name of the employee and displays his/her records from the sequential data file “ABC.REC” having fields name Name, Post, Dept and Salary. CLS OPEN “ABC.REC” FOR INPUT AS #2 INPUT “ENTER YOUR NAME::”;N$ WHILE NOT EOD (2) INPUT #2, NAME$, POST$, DEPT$, SAL IF NAME$=N$ THEN PRINT NAME$, POST$, DEPT$, SAL END IF WEND CLOSE #2 END 7. A sequential data file “information.dat” contains name, address and phone number. Write a programme to display all the information whose address is either Dhading or Kathmandu. CLS
Approved by Curriculum Development Centre 273 Oasis Radiant Computer Science, Book 10 OPEN “information.dat FOR INPUT AS #1 DO WHILE NOT EOF(1) INPUT #1 , n$, a$, p IF a$ = “Dhading” or “s$ = “Kathmandu” THEN PRINT “Name=”; n$ PRINT “Address=”; Ad$ PRINT “Phone No=”;p END IF LOOP CLOSE #1 END 8. A sequential data file “result.dat” contains name and marks secured by students in 3 subjects. Assuming that pass marks of each subject is 40, write a program to count the number of passed students. OPEN “result.dat” FOR INPUT AS #1 DO WHILE NOT EOF(2) INPUT #1, n$, e, m, c IF e>= 40 and m>= 40 and c>=40 THEN P= P+1 END IF LOOP CLOSE#1 PRINT “Total Number of Passed Students=”;P END 9. WAP TO ASK THE PERSONAL DETAIL AND STORE IN A FILE RECORD. DAT OPEN “RECORD.DAT” FOR OUTPUT AS #1 ‘Create a file named as RECORD.DAT START: ‘Is used to rewrite the data. INPUT “ENTER YOUR NAME “;NAME$ INPUT “ENTER YOUR CITY”;CITY$ INPUT “ENTER YOR AGE “;AGE WRITE #1, NAME$, CITY$, AGE ‘#1 is the buffer name of the file and all input records are store in record.dat
Oasis Radiant Computer Science, Book 10 274 Approved by Curriculum Development Centre i.e #1. INPUT “DO YOU WANT TO ADD MORE RECORD (S) Y/N “;ANS$ ‘Asking for more records or not. IF ANS$=”Y” OR ANS$=”y” THEN GOTO START: ‘To check if the user type small ‘y’ or capital ‘Y’ CLOSE #1 ‘Closing the file handling operation. END 10. WAP TO DISPLAY THE RECORDS TORED IN A FILE RECORD.DAT OPEN “RECORD.DAT” FOR INPUT AS #1 ‘Create a file named as RECORD. DAT DO WHILE NOT EOF(1) ‘ To read the data until it reach to the end of the file INPUT #1, NAME$, CITY$, AGE PRINT “NAME : “;NAME$ PRINT “CITY: ”;CITY$ PRINT “AGE : “;AGE LOOP CLOSE #1 ‘Closing the file handling operation. END 11. WAP TO APPEND THE PERSONAL DETAIL AND STORE IN A FILE RECORD. DAT OPEN “RECORD.DAT” FOR APPEND AS #1 ‘Using a existing file to ask and store records. START: ‘Is used to rewrite the data. INPUT “ENTER YOUR NAME “;NAME$ INPUT “ENTER YOUR CITY”;CITY$ INPUT “ENTER YOR AGE “;AGE WRITE #1, NAME$, CITY$, AGE ‘#1 is the buffer name of the file and all input records are store in record.dat i.e #1. INPUT “DO YOU WANT TO ADD MORE RECORD (S) Y/N “;ANS$ ‘Asking for more records or not. IF ANS$=”Y” OR ANS$=”y” THEN GOTO START: ‘To check if the user type small ‘y’ or capital ‘Y’ CLOSE #1 ‘Closing the file handling operation. END
Approved by Curriculum Development Centre 275 Oasis Radiant Computer Science, Book 10 12. WAP to search and display only those records according to the entered by the user from the data file “PERSON.DAT”, (Note: The file contains Name, Address and phone no as field names) CLS INPUT “NAME TO DISPLAY ONLY ITS RECORDS “;N$ ‘ ASKING WHOSE RECORDS WANT TO DISPLAY OPEN “PERSON.DAT” FOR INPUT AS #1 WHILE NOT EOF(1) INPUT #1, NA$,A$,PH ‘TO READ THE DATA FROM THE EXISTING FILE AT FIRST IF N$=NA$ THEN ‘TESTING WHETHER THE ENTERED PERSON DETAIL IS STORE OR NOT PRINT “NAME: “;NA$ PRINT “ADDRESS : ”;A$ PRINT “PHONE NO : “;PH GOTO LAST: ‘AFTER PRINTING DATA ENDIGN THE PROGRAM END IF WEND CLOSE #1 PRINT “NO SUCH RECORDS FOUND” LAST: END 13. WAP To delete some records according to the user’s choice from the data file “PERSON.DAT”. The data file contains Name, Address and Phone number as field names: CLS OPEN “PERSON.DAT” FOR INPUT AS #1 ‘Opening given program in INPUT mode OPEN “TEMP.DAT” FOR OUTPUT AS #2 ‘Creating a temporary file START: DO WHILE NOT EOF(1) INPUT #1, N$, A$, PH ‘Reading data from the given file and printing PRINT “NAME : “;NA$ PRINT “ADDRESS : ”;A$ PRINT “PHONE NO : “;PH INPUT “DO YOU WANT TO DELETE THIS RECORD “;Y$ ‘Asking user if he/she want to delete displayed ‘record or not.
Oasis Radiant Computer Science, Book 10 276 Approved by Curriculum Development Centre IF LCASE$(Y$)=”y” THEN GOTO START: ‘If user want to delete the records next record will be appear ELSE ‘If user don’t want to delete the records then particular records will be written in TEMP.DAT file WRITE #2, NA$, A$, PH GOTO START: END IF LOOP CLOSE #1, #2 KILL “PERSON.DAT” ‘Deleting original file because required records are written in TEMP.DAT file NAME “TEMP.DAT” AS “PERSON.DAT” ‘Again renaming file TEMP.DAT as PERSON.DAT END 14. Some file system commands: 1. FILES : To display the list of the files and directories on the disk. Syntax: Files [files specification] Example 1: CLS FILES END Output: This program will display the list of files and directories on the disk drive. Example 2: CLS FILES “*.BAS” END Output: This program will display the list of files having .BAS as an extension. 2. CHDIR: To change from one working directory to another. Syntax: CHDIR [Pathname] Example 1: CLS CHDIR “C:\QBASIC” END Output: It will change the sub directory to QBASIC directory of C: Example 2: CLS CHDIR “A:\ABC10” END Output: It will change the sub directory to ABC10 directory of A:
Approved by Curriculum Development Centre 277 Oasis Radiant Computer Science, Book 10 3. MKDIR: To create a sub directory on the specified disk. Syntax: MKDIR [Pathname] Example CLS MKDIR “D:\CLASS10” END Output: It will make a directory CLASS10 directory in D: 4. RMDIR: To delete a sub directory from the specified disk. Syntax: RMDIR [Pathname] Example CLS RMDIR “D:\CLASS10” END Output: It will remove the directory CLASS10 of D: 5. NAME ….AS……: To change the name of a file on the disk. Syntax: NAME old filename as new filename CLS NAME AS TEMP.DAT AS PERSON.DAT END Output: It will change the name file TEMP.DAT as PERSON.DAT 6. KILL: To delete(s) file on the disk. Syntax: KILL [Filename with path] Example 1: CLS KILL “A:\CLASS10\*.BAS” END Output: It will delete all files having .BAS as an extension of CLASS10 directory of A: Example 2: CLS KILL PERSON.DAT END Output: It will delete the file PERSON.DAT of current disk drive.
Oasis Radiant Computer Science, Book 10 278 Approved by Curriculum Development Centre Exercises • File organisation refers to the way of organisation or arranging the data in a file. • In a Sequential Access Data file data are stored in a sequential order. • OPEN statement prepares for input/output to a file or device. • There are three modes of file: OUTPUT, APPEND and INPUT. • APPEND mode is used to add more records to an existing file. • CLOSE statement closes all the open data files. • PRINT# or WRITE# statements place data into a sequential file. • INPUT# statement reads data items from a sequential file and assigns them to programme variables. • EOF () function tests the end of a file. Points to remember 1. Answer the following questions. a. Define data b. What is make of data file? Write different modes. c. Differentiate between sequential access data file and random access data file. d. Write advantages of sequential access data file. e. Differentiate between INPUT and OUTPUT mode. f. Differentiate between OUTPUT mode and APPEND mode. g. Differentiate between WRITE# and PRINT# statements. 2. Write the syntax and purpose of the following: a. OPEN b. CLOSE c. PRINT# d. WRITE# e. INPUT# f. LINE INPUT# g. EOF () 3. Write QBASIC to solve the following problems. a. Write a programme to create a data file “Store.dat” and store Name, Roll No. and Class. b. Write a programme to create a sequential file “INFO.DAT” to store the information of 10 students. The related information are Name, Address and Phone No. c. Write a programme to open a data file “ABC.REC” in output mode and
Approved by Curriculum Development Centre 279 Oasis Radiant Computer Science, Book 10 store information as employees’ name, post, department and salary. d. Write a programme to store students’ name, class and date of birth in a new sequential data file “STD.REC”. This program allows a user to enter records according to the users choice. e. A data file “Class.dat” has 300 records that contains student’ name, class, data of birth, guardians’ name. Write a programme to input 50 more records in the same file. f. Write a programme to add more records in a sequential data file “Result.dat” having name, roll no, and marks in 5 subject (English, Nepali, Math, Science and Computer Science). The program should run as per users choice. g. Write a programme to append 10 more records (Name, Class, Section) to a sequential file “Class.dat”. h. Write a programme to display all the records of sequential data file “Account.dat” on the screen. The data has the following records: Name, Age, Address and Phone no. i. Write a programme to display all the records from the data file “salary. txt”. j. A data file contains name, age and sex of the patients. Write a programme to count and print the number of patients. k. A sequential data file “Record.dat” contains name, post, department, and salary of some staffs. Write a programme to print first 20 records. l. Write a programme to display only those records whose salary is less than 10000 from a data file “salary.dat” that contains Name, Post and Salary of employees. m. Write a programme to display records from the 5th position to the 12th position from the sequential file “BOOKLIST.DAT”. It contains Book title, Author’s name and price. n. A sequential data file “Exam.dat” contains the name class and marks secured by students in Math, Nepali and Computer Science. Write a programme to calculate the total and display all the information in tabular from. o. A data file staff.dat contains the name, class and roll no. Write a programme to display the records of the persons whose name starts with ‘S’. p. Write a programme to do the following cases: Cases 1: To create data file “school.doc” and store the records (name, address and phone no.) of 10 people. Case 2: To read the records from data file “school.doc”. Case 3: To add the records in “school.doc”.
Oasis Radiant Computer Science, Book 10 280 Approved by Curriculum Development Centre Case 4: Quit the program q. A sequential data file “student” text contains students name and marks secured in English, Maths, Computer, Nepali. Write a programme to display all the records along with total and percentage. r. A sequential data file “ABC.DAT” contains some records. Write a programme to print only last 5 records from the file. 4. Debug the following. a. REM to display records. OPEN “Info.dat” FOR display AS #1 CLS PRINT “Name”, “Post”, “Salary” DO WHILE NOT EOF (1) PRINT #1, n$, p$, s PRINT n$, p$, s WEND CLOSE #2 END b. REM to print record of the students whose score are above 200. OPEN “EMP.DAT” FOR APPEND AS #1 CLS DO WHILE EOF (1) INPUT #1, N$, A%, SC SELECT CASE SC CASES IS>200 THEN PRINT N$, A%, SC END SELECT LOOP CLOSE #4 END c. REM to display records where age is above 15. OPEN STUDENT.DAT FOR INPUT #1. CLS DO WHILE NOT EOF (1) INPUT NAME$, ADD$, TELNO$, AGE IF AGE is greater than 15 THEN PRINT NAME$, ADD$, TELNO$, AGE NEXT CLOSE #1 END 5. Read the program and answer the question that fallows. a) OPEN “detail.dat” FOR INPUT AS #1
Approved by Curriculum Development Centre 281 Oasis Radiant Computer Science, Book 10 OPEN “ temp.dat” FOR OUTPUT AS #2 INPUT “Name of the students”; S$ FOR I=1 TO 10 INPUT #1, N$, C, A IF S$<>N$ THEN WRITE #2, N$, C, A ENDIF NEXT I CLOSE #1, #2 KILL “detail.dat” NAME “temp.dat” AS “detail.dat” END i) What is the main objective of the above programme? ii) If the data file “detail.dat” contains only 8 records, then the program will run? why? b) OPEN “SAL.DAT” FOR OUTPUT AS# 1 CLS DO INPUT “ENTER THE NAME”; N$ INPUT “ENTER THE POST”; P$ INPUT “ENTER THE SALARY”; S# WRITE #1, N$, P$, S# INPUT “DO YOU WANT TO STORE MORE RECORDS? (Y/N); CH$ LOOP WHILE UCASES(CH$) =”Y” CLOSE#1 END a) Write the work of WRITE# and CLOSE# b) List all the string variables present in the program. c) OPEN “EMP.DAT” FOR APPEND AS#1 CLS DO INPUT “ENTER NAME”; N$ INPUT “ENTER POST”; P$ INPUT “ENTER SALARY”; S# WRITE #1, N$, P$, S# INPUT “ADD MORE DATA? (Y/N)”; C$ CH$= UCASE$ (C$) LOOP WHILE UCASE$ (CH$) = “Y” CLOSE#1 END a) What is the purpose of APPEND mode b) What will happen if UCASE$ is not used in programme.
Oasis Radiant Computer Science, Book 10 282 Approved by Curriculum Development Centre Chapter 11 Introduction to C Language ffl Introduction to C Language ffl Charactertics of C Language ffl Basic Elements of C Language ffl Operators in C Language ffl Looping THIS CHAPTER COVERS :
Approved by Curriculum Development Centre 283 Oasis Radiant Computer Science, Book 10 Introduction to C 11 Language Chapter Introduction This chapter covers core materials of C language. The C language is not purely a high level language, but intermediate between low and high level languages. It is very popular amongst programmers due to its capability to handle large files, dynamic memory allocation and different types of data. Its compiler was developed by Ken Thompson and Dennis Ritchie in early 1970s. C is prized for its efficiency, and is the most popular programming language for writing system software. The UNIX kernel is written in C. Why Use C? In today’s world of computer programming, there are many high-level languages to choose from, such as C, Pascal, BASIC, and Java. These are all excellent languages suited for most programming tasks. Even so, there are several reasons why many computer professionals feel that C is at the top of the list: • C is a powerful and flexible language. What you can accomplish with C is limited only by your imagination. The language itself places no constraints on you. C is used for projects as diverse as operating systems, word processors, graphics, spreadsheets, and even compilers for other languages. • C is a popular language preferred by professional programmers. As a result, a wide variety of C compilers and helpful accessories are available. • C is a portable language. Portable means that a C programme written for one computer system (an IBM PC, for example) can be compiled and run on another system (a DEC VAX system, perhaps) with little or no modification. Portability is enhanced by the ANSI standard for C, the set of rules for C compilers. • C is a language of few words, containing only a handful of terms, called keywords, which serve as the base on which the language’s functionality is built. You might think that a language with more keywords (sometimes called reserved words) would be more powerful. This isn’t true. As you
Oasis Radiant Computer Science, Book 10 284 Approved by Curriculum Development Centre programme with C, you will find that it can be programmed to do any task. • C is modular. C code can (and should) be written in routines called functions. These functions can be reused in other applications or programmes. By passing pieces of information to the functions, you can create useful, reusable code. Features of C The C language is an overwhelming choice of software developers. It is equipped with some special features: • General purpose language. • It is an assembly language. It is not high level nor low level, but an intermediate level programming language. • Modular and structural concept is used in C language. So, debugging, testing and maintenance are easy. • Problems are divided into small tasks or modules, called functions • Highly portable language and it is machine independent also. • User function and header file make C as a rich language. We can build our own functions and header files for our large programmes. These types of facilities make it a language of software development • It is a free form language because statement can span several lines without problem of line number and place, but each statement should be terminated by semi-colon (;). • Introduction to incremental/decrement operator. Keywords or Reserve Words The basic building blocks of programme statements are called keywords. Every language has specific keywords with specific meaning and functions. These keywords are part and parcel of the compiler. Any user data are introduced into compiler environment for compilation through keywords. These keywords are not used as variable names. In C programming, certain names or words are reserved by the programming language itself for the special purpose with special meaning. These words are called keywords. The meaning of these words is already defined to the compiler and hence cannot be re-defined to mean anything else. The
Approved by Curriculum Development Centre 285 Oasis Radiant Computer Science, Book 10 ANSI C defines 32 keywords. The following are the keywords in C programming language. auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while My First Programme in C We can write programme in turbo C or C++ editor as below: /* hello.c*/ /*My First Program in C language */ #include<stdio.h> void main( ) { printf(“Hello, World \n”); } Main () Function: A programme in C programming language might have a number of functions declared and defined in the same programme. Among these functions, the function which is executed first is known as main() function, and it is written as follows:- Example: void main () main( ) is a main function and it has only one module or function printf( ) to solve problems. In one main( ) function, many functions are present to solve problems. Comments Programme starts with header file written with directive #include. Example #include<stdio.h> Quotation marks instruct the compiler to begin its search for the header file in the current directory.
Oasis Radiant Computer Science, Book 10 286 Approved by Curriculum Development Centre Example #include “stack.h” Every C programme has one main function written as main ( ) or int main ( ) or void main() on the basis of return. Every statement is terminated by semicolon (;). It is a block-based structure so curly brackets are used to make blocks. Comments Comments are nonexecutable statements used to clarify objective of the programme. Comments are started by /* and terminated by */. This type of style is suitable for multi-lined comments. Example /* hello.c*/ /*My First Program in C language */ /* This book is useful for all categories of students from beginners to advanced users */ The space is not allowed between slash (/) and asterisk (*). Now, double-slash is also used to write comments. Generally, single line comment is started by double-slash (//). Example // hello.c // My First Program in C language This language is case sensitive. It can recognise programme written in uppercase or lower case. As a good programming practice, we use lower case to write programme. Example (i) The printf ( ) and Printf ( ) are different in C language. (ii) The input function scanf () and Scanf ( ), both quite different. Use following commands: • We save programme with file name hello.c. • Compile programme by pressing Alt+F9. • Compile and Run programme by pressing Ctrl + F9. • Open user Window by pressing Alt + F5 • Close your programme window by pressing Alt + F3.
Approved by Curriculum Development Centre 287 Oasis Radiant Computer Science, Book 10 Variable and Constant The variable or literal is like a container to contain valued. The value of contents can be changed during programme execution, but constantd are data which remain constant during the programme life cycle. Sr Variables Comments 1. Integer Variable <1> Integer variable is a value which is always an integer during the programme execution. <2> The integer variable name contains integer constant. <3> Integer variable is declared with word - int. <4> Example: int x ,y , z; int amount, principle; int index, roll, sign; 2. F l o a t Variable <1> Float variable is a value with 6 decimal accuracy and remains float during programme execution. <2> The word float is used before float variable at the time of declaration. <3> Example : float rate; float interest, temperature, pay; float x, y, z; 3. D o u b l e Variable <1> In float, 6 places are there for decimal precision, but in case of double decimal precision is 12 places. <2> It is declared with word - double. <3> Example: double second; double x, y ,z; double income, cost, power, time; 4. Character Variable <1> These variables contain letters, numbers, special characters etc. <2> They are declared as: char name; char symbol, sex, answer, response; char address[30 ];
Oasis Radiant Computer Science, Book 10 288 Approved by Curriculum Development Centre Declaration of Variable The compiler is a manmade system software used to accept user data and process it. It is used to develop software for processing of data. The C compiler cannot understand data without its type declaration. The types of variable help the compiler to allocate space in memory to hold data. The assigning types of variable are termed as declaration. Syntax DataType variable; Example int digit; float basic; char name[20]; Program #include<stdio.h> void main( ) { int x ,y ; x = 5 ; y = 10 ; printf(“x = %d \n “, x); printf(“y = %d \n” ,y) ; getch( ) ; } Constants A constant is a quantity that doesn’t change. This quantity can be stored at a location in the memory of the computer. In C, there are basically four types of constants, namely integer constants, floating-point constants, character constants and string constants according to usage. But actually in a broad sense C constants can be divided into two major categories • Primary Constants, for example, Integer constant, Real constant, Character constant • Secondary Constants, for example, Array, Pointer, Structure, Union, Enum, etc. Syntax:
Approved by Curriculum Development Centre 289 Oasis Radiant Computer Science, Book 10 const <data type> <variable name> = <value to be assigned> Like a variable, a constant is a data storage location used by your programme. For example, Integer constant [For e.g. 426, +782, -8000, -7605] Floating-point constant [For e.g. 426.0, 32.76,-48.5792] Character constant [For e.g. ‘A’, ‘I’, ‘5’,’=’] String constant [For e.g. “Kathmandu”, “Ram”] There are mainly three types of constants. They are discussed below: 1. Literal constants: A literal constant is a value that is typed directly into the source code wherever it is needed thereby literal constants are also referred as constants. 2. Symbolic constants: A symbolic constant is a name that substitutes for a sequence of characters. The characters may represent a numeric constant, a character constant or a string constant. Thus, a symbolic constant allows a name to appear in place of a numeric constant, a character constant or a string. When a programme is compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence. Symbolic constants are usually defined at the beginning of a programme. The symbolic constants may then appear later in the programme in place of the numeric constants, character constants, etc. that the symbolic constants represent. 3. Defining symbolic constants: A symbolic constant is defined by writing #define name text where name represents a symbolic name, typically written in uppercase letters, and text represents the sequence of characters that is associated with the symbolic name. Note that text does not end with a semicolon, since a symbolic constant definition is not a true C statement. Moreover, if text were to end with a semicolon, this semicolon would be treated as though it were a part of the numeric constant, character constant or string constant that is substituted for the symbolic name. A C programme contains the following symbolic constant definitions. #define TAXRATE 0.23
Oasis Radiant Computer Science, Book 10 290 Approved by Curriculum Development Centre Example #define PI 3.141593 #define TRUE 1 #define FALSE 0 #define FRIEND “Susan” #define MAX 60 #define PI 3.14 Program #include<stdio.h> #define PI 3.14 void main() { float radius; printf(“Enter radius:”); scanf(“%f”,&radius); printf(“\nThe primeter of circle is %.2f\n”,2*PI*radius); getch(); } White Space or Escape Characters These are not seen on the monitors. Generally, most frequently used white space characters are \t(providing tab space) and \n(new line feed) Characters Name \b Blank Space \n New Line \f Formfeed \r Carriage Return \t Horizontal Tab \v Vertical Tab Program #include<stdio.h> void main() { printf(“Computer Science”);
Approved by Curriculum Development Centre 291 Oasis Radiant Computer Science, Book 10 printf(“KTM”); getch(); } Output: Computer Science KTM The new line character(‘\n’) is not used in this programme, so cursor is not returned to second line to display KTM. Both the strings are displayed in one line. Program #include<stdio.h> void main() { printf(“Computer Science \n”); printf(“KTM”); getch(); } Output: Computer Science KTM The new line character (‘\n’) is used in this programme, so cursor is returned to second line to display KTM. Both the strings are displayed in separate line. Input/Output Function Some input and output functions are described. The concept of getchar(), putchar(), gets(), puts(), scanf(), printf() are essential for programming. The decision of use of these functions are problem oriented. Character Input/Output We use getchar( ) and putchar( ) for character inputting and outputting purpose. We use putc( ) also to display characters on screen .
Oasis Radiant Computer Science, Book 10 292 Approved by Curriculum Development Centre getchar( ) and putchar( ): Sr. getchar( ) putchar( ) (a) It is used to enter character through keyboard at the time of program execution. It is used to display character on screen. Escape sequences are used with it. (b) Format: variable = getchar( ) ; Format : putchar(variable or character); (c) Example: Example: void main() void main() { { char letter; char letter = ‘A’; printf(“Enter character:”); putchar(letter); letter = getchar(); putchar(‘B’); putchar(letter); } } String Input/Output The string handling process is done through gets( ), fgets( ), puts( ) and fputs( ). (A) The differences between gets( ) and puts( ) are given below: Sr. gets( ) puts( ) a. It stands for get - string. It stands for put-string. b. Conversion specifiers are not used with it. The conversion specifiers are not used with puts( ). c. It reads a string from keyboard(Standard Input Device) It uses one argument, which can be either a data - item, or a variable. It displays data (string) on screen (Standard Output Device). d. Format: gets(variable) ; Format: puts(data - item or variable);
Approved by Curriculum Development Centre 293 Oasis Radiant Computer Science, Book 10 e. Example : main( ) { char name[20]; printf(“Enter name:”); gets(name); puts(name); } Example: main( ) { char name[20]; printf(“What is your name:”); gets(name) ; puts(name); puts(“Thank You “); } Formatted Input/Output In C programming, most frequently used input/output functions are scanf( ) and printf( ).These functions are defined in header file - stdio.h.These functions are dedicated for formatted inputting and outputting of data. We use conversion specifiers with formatted inputting and outputting. The specifiers are: %u, %d , %ld, %f ,%c ,%s etc. Sr. scanf( ) printf( ) (i) It stands for scan format. So, it is a formatted input function. It stands for print format. So, it is used for formatted output. (ii) Format: scanf(control sequence,var-1,var-2 ..) ; We use %d, %f,%s etc are control sequences. We use ampersand (&) with numeric variables. Format: printf(control sequence ,var-1,var-2 ...); or printf(strings) ; (iii) Example: Example: void main( ) void main( ) { { int x , y ; float x , y ; printf(“Enter two integers :”) ; printf(“Enter two floats :”) ; scanf(“%d%d” , &x , &y) ; scanf(“ %f %f “ , &x , &y) ; printf(“x = %d , y = %d\n” , x ,y) ; printf(“ x = %.2f , y = %.2f \n” ,x,y) ; getch( ); getch( ); } }
Oasis Radiant Computer Science, Book 10 294 Approved by Curriculum Development Centre Generally, we use some numbers just before conversion specifies to reserve space on the screen or output devices. The format is: % w d % w.d f where w is the width of integer numbers and its value is also in integer. In w.d , the d indicates spaces after decimal point Example % 4d % 6. 2f Formatted input and output are responsibility of function scanf () and printf ( ).We use some conversion specifiers or format commands with these functions. In case of scanf( ), the type of variables are denoted by these specifiers. Some special codes are also used with output function printf ( ) to control output. These special codes are called- backslash codes or Escape Sequences. • Format Conversion or Format specifiers (% code) • Escape Sequences or backslash code (\code) Format Conversion or Format specifiers used with input and output functions. Conversion specifiers Meanings %c character %s string variable or constant % i decimal integer %d decimal Integer. We use integer before d to determine width of integer numbers. For example, %4d means the four spaces are reserved for integer digits. %f float. We use width of float numbers .For example, %5.2f indicates that the number will contain 2 numbers after the decimal points and five preceding it. %u unsigned decimal number %0 Octal
Approved by Curriculum Development Centre 295 Oasis Radiant Computer Science, Book 10 %x or %X Hexadecimal %e or %E Scientific %% Display percentage sign( % ) Operators Operators are special types of symbols or character(s) used to manipulate all type of data used in computer systems. Example: In a + b, + is operator, a and b are operand and the whole addition process is called the operation. Arithmetic Operator Arithmetic or mathematical operators are used for mathematical manipulation. For mathematical manipulation, numerical data are used. Some mathematical operators are: Operator Meaning Example + Addition or Unary plus x + y - Subtraction or Unary minus x - y * Multiplication x * y / Division x/y % Modulo Division (remainder after division) x % y Exponentiation In C language, there is no operator for exponentiation. We use ready made function pow(x,y) of math.h header file which returns xy xy Logical Operator It is used to combine two or more relational operators. It makes decision building block with relational operators. Operator Meaning && logical AND || logical OR ! logical NOT Logical AND. It is used to combine all the relations or conditions. It returns TRUE, if all the conditions are true.
Oasis Radiant Computer Science, Book 10 296 Approved by Curriculum Development Centre Example if(sale>=5000 && sale< 10000) commission = sale*0.5; • Logical OR. If more than one conditions are employed with OR(||) , return can depend on any one satisfied condition. It is some time called, UNION operation . Example if(age >=18 || education = ”SLC”) printf(“ Selected.\n”); • Logical NOT. If there is not any condition satisfied, the NOT(!) returns TRUE. To control this type of logic, NOT gate (inverter) is used. NOT gate generates output signal which is the reverse of the input signals. Its truth table is very simple: Example int x = 1; do { printf(“W E L C O M E \n”) ; x = x +1; } while(x!=5) ; The process of printing can continue until value of x is not equal to 5. The looping is terminated when value of x becomes 5 (TRUE). Relational Operator The relational operators are used to compare two or more quantities.The comparison is also one important operation for data. In our daily life, the comparisons is done every walk of life from home to hospital, school to university, and even toe to top. Operators Meaning = = is equal to ! = is not equal to < less than
Approved by Curriculum Development Centre 297 Oasis Radiant Computer Science, Book 10 < = less than and equal to > greater than > = greater than and equal to Increment and Decrement Operator (Unary) These are special types of operators used in C /C++ /C# /JAVA to increase or decrease value of variables by 1. It has two types: (a) Prefix, and (b) Postfix. • Prefix is divided as prefix increment operator (++variable) and prefix decrement operator (- - variable). In case of prefix, 1 is added /subtracted to operand and then result is assigned to left side variable. Example + + x ; (+ + is a prefix increment .) - - y; ( - - is a prefix decrement .) • Postfix is also in two forms as post increment (variable ++) and post decrement operator (variables - -). In this type of operator, at first value is assigned to leftside variable then operand is increased or decreased by 1. Example x + +; (++ is a postfix increment.) y - - ; ( - - is a postfix decrement .) Program #include<stdio.h> void main() { int a=9, b=3,x=9,y=3; int sum1, sum2; sum1=a+(++b); sum2=x+(y++); printf(“The sum=%d\n”,sum1); printf(“The sum=%d\n”,sum2); } Output
Oasis Radiant Computer Science, Book 10 298 Approved by Curriculum Development Centre getch(); The sum=13 The sum=12 Note • sum =a+(++b) indicates that b is incremented first then added to a • sum =x+(y++) indicates addition takes place before incrementing the b. Conditional (ternary) Operator It has three parts: a) conditional expression b) ? c) expressions separated by colon(:) Format conditional expression? exp-1: exp-2 ; If the conditional expression being evaluated true, expression (exp-1) before colon (:) is evaluated otherwise expression (exp-2) after colon is evaluated. It is a unique if--else statement used in C /C++ program. Example x = (y>z ) ? y : z ; We can present it using if----else also. if(y>z) x = y ; else x = z ; Data Type It is an instruction that is used to declare the type of variables being used in the program. Any variable used in the program must be declared before using it in any statement. Data types determine the way a computer organises data in memory. It determines how much space it occupies in storage and how the bit pattern stored is interpreted. Types can be either predefined or derived The predefined types in C are the basic types and the type void. The C language supports four basic data types, each of which are represented differently within the computer memory.
Approved by Curriculum Development Centre 299 Oasis Radiant Computer Science, Book 10 Data Type Description Typical Memory Requirements char A single character 1 byte int An integer value, typically reflecting the natural size of integers on the host machine 2 bytes or 4 bytes float Single precision floating-point number 4 bytes double Double-precision floating-point number 8 bytes The type declaration statement is usually written at the beginning of the C program. Different types of data type are as follows. Data Type Typical Size in Bytes Minimal Range char 1 –128 to 127 unsigned char 1 0 to 255 signed char 1 –128 to 127 int 2 –32768 to 32767 unsigned int 2 0 to 65535 signed int 2 Same as int short int 2 –32768 to 32767 unsigned short int 2 0 to 65535 signed short int 2 Same as short int long int 4 –2147483648 to 2147483647 signed long int 4 Same as long int unsigned long int 4 0 to 4294967295 float 4 3.4×10-38 to 3.4×1038 with six digits of precision double 4 1.7×10-308 to 1.7×10308 with ten digits of precision long double 10 3.4×10-4932 to 1.1×104932 with ten digits of precision
Oasis Radiant Computer Science, Book 10 300 Approved by Curriculum Development Centre typede f. It stands for type definition and used to build user defined type of data. Format typedef type identifier; Example typedef short int length; typedef long int unit; typedef long double width; typedef long float real; typedef signed char boss; length x, y; unit basic, salary; real north, south, east, west; • Enumeration. It is also a user defined data type. It is used to assign numerical value to the list of strings. The named constant is known as enumerator. Syntax: enum identifier{var1,var2,….}; or enum identifier{list of named constants or enumerators}; Example (i) enum day{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; enum day d; d is a enum type of data. (ii) enum reptile{ lizard, crocodile, snake, tortose, }; The named constants or enumerators lizard, crocodile, snake and tortoise represent integer value started from 0 to 3.The lizard represents 0, crocodile 1, snake 2 and the value represented by tortoise is 3. When the value of named constant is given with =, the value is started from there and next named constant value is increased by 1. Example enum reptile{ lizard=5, crocodile, snake, tortoise,