15. Write a function procedure palind$ (s$) to input a string and check whether a supplied string
is palindrome or not.
Solution:
DECLARE FUNCTION palind$ (s$)
INPUT “Enter a string”; s$
IF s$ = palind$(s$) THEN
PRINT “palindromic string”
ELSE
PRINT “not palindromic string”
END IF
END
FUNCTION palind$ (s$)
FOR i = LEN(s$) TO 1 STEP -1
a$ = a$ + MID$(s$, i, 1)
NEXT
palind$ = a$
END FUNCTION
16. Write a function procedure vowel! (s$) to input a string and count the number of vowels
present in it.
Solution:
DECLARE FUNCTION vowel! (s$)
INPUT “Enter a string”; s$
PRINT “Total vowels::”; vowel(s$)
END
FUNCTION vowel (s$)
FOR i = 1 TO LEN(s$)
a$ = UCASE$(MID$(s$, i, 1))
IF a$ = “A” OR a$ = “E” OR a$ = “I” OR a$ = “O” OR a$ = “U” THEN c = c +
1
NEXT
vowel = c
END FUNCTION:
JBD
Computer Studies-10 151
C Dompu- ictionary
Modular Program : A software design technique that increases the extent
to which software is composed of separate parts, called
Module : modules.
SUB procedure : A set of program statements which, when acting
together, complete a specific task, and is identified by
Local variable : a name.
Global variable : SUB procedure is essentially a program within a
program designed to perform a specific task.
A variable declared as local is one that is visible only
within the block of code in which it appears.
A variable which can be accessed (used or changed)
throughout a computer program and is not confined
to a single block.
Recap
• Modular programming is a software design technique that increases the
extent to which software is composed of separate parts, called modules.
• SUB procedure is essentially a program designed to perform a specific task.
• The DECLARE statement is used to declare a SUB procedure. QBASIC
automatically generates a DECLARE statement when you save the program
having no declaration statement for the first time.
• The SUB...END SUB statement is a procedure statement that marks the
beginning and ending of a subprogram.
• The CALL statement is used to transfer control to another procedure, a BASIC
SUB program.
• FUNCTION procedure is used by the programmer to define a new function.
• The FUNCTION...END FUNCTION statement declares the name, the
parameters, and the code that form the body of a FUNCTION procedure.
• A process of passing value of variables is known as call by value.
• A process of passing addresses to a function is known as call by reference.
• A variable declared as local is one that is visible only within the block of code
in which it appears.
• Global variable is a variable which can be accessed (used or changed)
throughout a computer program and is not confined to a single block.
JBD
152 Computer Studies-10
Review Yourself
1. Answer the following questions.
a. What do you understand by modular programming? State any three
benefits of modular programming.
b. List any two main differences between SUB procedure and FUNCTION
procedure.
c. What is the purpose and syntax of SUB...END SUB?
d. What is the purpose and syntax of CALL statement?
e. What are the two ways of passing parameters to a procedure? Explain in brief.
f. What is the function and syntax of FUNCTION...END FUNCION
statement?
g. What is the difference between global and local variables in terms of their scope.
h. What is the function and syntax of COMMON statement?
i. What is the function and syntax of DIM SHARED statement?
2. Write down the output of following programs.
a. DECLARE FUNCTION TEST(N)
FOR I= 1 TO 4
READ N
S=S+TEST(N)
NEXT I
PRINT “Result is:”; S
DATA 2, 3, 4 ,5
END
FUNCTION TEST( N)
TEST=N^3
END FUNCTION
b. DECLARE FUNCTION outp$ (s$)
s$ = “KATHMANDU”
PRINT outp$(s$)
END
FUNCTION outp$ (s$)
FOR i = 1 TO LEN(s$)
t = i MOD 2
IF t = 1 THEN
JBD
Computer Studies-10 153
w$ = w$ + UCASE$(MID$(s$, i, 1))
ELSE
w$ = w$ + LCASE$(MID$(s$, i, 1))
END IF
NEXT
outp$ = w$
END FUNCTION
c. DECLARE FUNCTION CON (b)
CLS
z = 1111
ans = CON (z)
PRINT “The result is”; ans
END
FUNCTION CON (b)
p=0
DO WHILE b <> 0
d=b MOD 10
e=d * 2 ^ p + e
b=INT(b / 10)
p= p + 1
LOOP
CON = e
END FUNCTION
3. Debug the following program.
a. DECLARE FUNCTION REV$(ST$)
CLS
INPUT “Enter a string:”;S$
LET R$=REV$(ST$)
PRINT “The string in reverse is “:R$
END
FUNCTION REV$(ST$)
FOR I=LEN(ST$) TO 1
RV$=RV$+MID$(ST$,1,I)
NEXT
RV$=REV$
END FUNCTION
JBD
154 Computer Studies-10
b. DECLARE FUNCTION remodd (n)
CLS
INPUT “any number “; a
PRINT “Even digits only “; remodd(n)
END
FUNCTION remodd (n)
p=0
WHILE n <> 0
r = n MOD 10
IF r MOD 2 = 1 THEN
s=s+r^p
p = p * 10
END IF
n = n \ 10
WEND
s = remodd
END FUNCTION
c. DECLARE FUNCTION MAX (N( )) END
CLS
FOR I = 1 TO 10
INPUT A(I)
NEXT I
A=MAX(A ( ))
PRINT “The greatest number is ”;X
FUNCTION MAX( N ( ) )
FOR I = 1 TO 10
IF A(I) <H THEN H=A(I)
NEXT I
H= MAX
END FUNCTION
4. Study the following program and answer the questions that follow.
a. DECLARE FUNCTION SUMDIGT(N)
CLS
INPUT “Enter any number:”; NUM
S=DIGITSUM(NUM)
PRINT “Sum of individual digit is=”; S
JBD
Computer Studies-10 155
END
FUNCTION DIGITSUM(N)
S1=0
DO WHILE N>0
R= N MOD 10
S1=S1+R
N=INT(N/10)
LOOP
DIGITSUM=S1
END FUNCTION
i. List out the different variables used in the above program.
ii. What will be the output if the value of NUM is 543.
b. DECLARE SUB SERIES(A, R, N)
CLS
INPUT “Enter first term:”;X
INPUT “Common ratio:”;Y
INPUT “Number of terms to be generated:”;Z
CALL SERIES (X, Y, Z)
END
SUB SERIES (A,R,N)
FOR I=1 TO N
PRINT A
A=A*R
NEXT
END SUB
i. What will be the output if user input 3, 2 and 4 for variables X,Y and Z
respectively?
ii. What type of parameters X, Y and Z are?
c. DECLARE FUNCTION xyz (n)
FOR I= 1 TO 5
READ n
Z = xyz (n)
S = s+z
NEXT
PRINT S
JBD
156 Computer Studies-10
DATA 10,13,15,4,6
END
FUNCTION xyz (n)
IF N MOD 2 =0 THEN xyz=n
END FUNCTION
i. What is the name of function used in the above program?
ii. How many times the function will be called in the above program?
5. Solve the following problems.
a. Write a sub-procedure cube(l) to input the length of a cube and print its
area. (Hint: A = 6*l^2)
b. Write a program to create a procedure using SUB...END SUB to input
the value of length, breadth and height of a box. The program should
calculate the area and volume of the box.
c. Write a sub procedure triangle (a,b,c) to input three sides of a triangle and
determine whether a triangle can be formed or not. (Hint: IF (a+b)>c AND
(b+c)>a AND (c+a)>b THEN PRINT “The triangle exists”)
d. Write a sub procedure to generate the following pattern:
5
55
555
5555
55555
e. Write a sub procedure pattern ( ) to generate the following pattern:
55555
4444
333
22
1
f. Write a sub program factors (n!) to input a number and find the factors of
the supplied numbers.
g. Write a sub procedure palind (n!, s!) to input a number and check whether
it is palindrome or not.
h. Write a sub program occur (n!) to input a positive number and count the
occurrence of even digits. Find out the sum of even digits.
JBD
Computer Studies-10 157
i. Write a sub procedure ARM (n, s) to input a number and check whether
it is armstrong or not.
j. Write a sub procedure sum (n!) to input a number and find the sum of its
individual digits.
k. Write a program to declare a user defined function using FUNCTION...
END FUNCTION to calculate the volume of a cube. The program accepts
the length, width and height. (Use expression method).
l. Write a program to declare a user defined function using FUNCTION...
END FUNCTION to calculate area and circumference of a circle.
m. Write a function procedure to read the length, breadth and height of a
box. Calculate the volume and surface area of a box.
(Hint: vol = lbh and sa = 2(lb+bh+hl))
n. Write a program using FUNCTION...END FUNCTION GREAT(A,B,C) to
find the greatest number among the three numbers.
o. Write a program using FUNCTION...END FUNCTION sum (n) to print
the sum of the first n natural numbers.
p. Write a program to declare a user defined function arm! (n!) to input a
number and check whether it is an armstrong number.
q. Write a program to declare a user defined function palind! (n!) using
FUNCTION...END FUNCTION to input a number and check whether it
is a palindrome or not.
r. Write a user defined function hcf (a,b) to input two positive numbers and
find the highest common factor.
s. Write a function procedure palind$ (s$) to input a string and check
whether a supplied string is palindrome or not.
t. Write a function procedure vowel! (s$) to input a string and count the
number of vowels present in it.
JBD
158 Computer Studies-10
Chapter 10
FILE HANDLING
IN
QBASIC
Objectives
After completing this chapter, you will be able to:
y Define the file organization and explain the two types of file organization.
y Explain the process of creating a sequential file.
y Explain the sequential file updation process.
C Ooncept verview
We have so far discussed programs
where the data is supplied in either or the
following two ways:
• At the time of writing the programs
using READ…. DATA statements.
• At the time of execution of the programs
through INPUT statements.
These approaches have two limitations:
• It is difficult to handle large volume of
data.
• The data stored in one program cannot
be shared by other programs.
These limitations can be overcome by
placing the data into a separate area called
a data file.
JBD
Computer Studies-10 159
Data File Defined
A data file is a collection of data organized in a Fields
specific format and for a specific purpose which is
kept somewhere in external memory. A file consists Emp # FName Phone
4242386
of a number of records, each of which contains a 1001 Ramesh 4437565
set of related data. For example, a “student file” Prem 4225586
will have one record for each student containing 1002 Kajol 4426552
all the particulars such as registration number, 1003 Suresh 4442425
name, class, age and sex. Each particular is a data 1004
item and is referred to as a field. This file can be 1005 Tenzing
used as input by a number of BASIC programs. Records
File Organization
File organization refers to the way of organizing or arranging the data in a file,
so that it is retrieved conveniently. QBASIC supports two types of file organi-
zations. They are: random access files and sequential access files. The criteria
needed for choosing a file organization type are:
• Fast access to a single record or collection of related records
• Easy record addition/update/ removal
• Storage efficiency
• Redundancy as a warranty against data corruption
Random Access Files
Random access files can be accessed in any order. This makes it unnecessary to
read through all of the data records to get to a specific data record. Although
creating a random access file involves more program steps than creating a se-
quential file, the speed, flexibility and efficient use of storage space are distinct
advantages. The fundamental storage unit is called a record. Records are usually
numbered to permit random access. Random access storage and retrieval take
place through a buffer.
JBD
160 Computer Studies-10
Sequential Access Files
A sequential access file is a file that must be accessed in a sequential order, starting
at the beginning of the data block and preceding in order until an end-of-data
marker is encountered of the required number of items has been read.
The advantages of sequential access files are as follows:
• File design is simple.
• Location of records requires only the key record.
• Low cost file medium such as tapes can be used.
• Saves a lot of storage space.
• When the activity rate is high, simplicity of the accessing method makes
processing efficient.
The main drawbacks of sequential data file are follows:
• Updating requires that all transaction records be sorted in the key record
sequence.
• A new master file, physically separate and exclusive is always created as a
result of sequential updating.
• Information on the file is not always current. Addition and deletion of records
are not simple tasks.
Creating a Sequential File
The following steps are required to create a a sequential file and access data from
it.
• Open the file in output (o) mode.
OPEN“O”, #1, “filename”
• Write data in the file using PRINT # or WRITE # statement.
PRINT # 1, variable/expression, ...
WRITE # 1, variable/expression, ...
• Close the file.
CLOSE # 1
• Reopen the file input (I) mode to access the data.
Open “I”, # 1, filename”
• Read data from the file using INPUT # or LINE INPUT # statement.
INPUT # 1, variable list
LINE INPUT # 1, variable
JBD
Computer Studies-10 161
Opening a File
The OPEN statement prepares for input/output to a file or device. The file or
device must be opened before any input or output is attempted to it. Opening a
file creates a buffer in the memory which helps in I/O operation and determines
the mode of access. The buffer is a block of memory that is reserved for I/O
operation on the file. The syntax of the OPEN statement is as follows:
OPEN mode, [#], file number, filename
or
OPEN filename [FOR mode] A$ [#]_ filenumber
Where,
filename specifies the particular file to be used. This should conform to the
specifications of the file when it was created. Filenames must be enclosed in
quotations.
file number is an integer number and can be any number between 1 and 255.
mode is a string constant and takes one of the following three forms:
Mode Meaning
O or Output
Specifies sequential output mode and positions the file
I or Input pointer to the beginning of the file.
A or Append
Specifies sequential input mode.
Specifies sequential output mode and positions the file
pointer to the end of the file.
Examples:
File Creation
OPEN “EXAM.DAT” FOR OUTPUT AS # 1
OPEN “O”, #1, “EXAM.DAT”
OPEN “INFO.TXT” FOR OUTPUT AS # 2
OPEN “O”, #2, “INFO.TXT”
File Reading
OPEN “EXAM.DAT” FOR INPUT AS # 1
OPEN “I”, #1, “EXAM.DAT”
OPEN “INFO.TXT” FOR INPUT AS # 2
OPEN “I”, #2, “INFO.TXT”
JBD
162 Computer Studies-10
Writing Data to a File
The PRINT # statement or WRITE # statement is used to place data into a sequential
file. The general syntax is as follows:
PRINT # filenum, expression list
WRITE # filenum, expression list
Where,
filenum is the number used when the file was opened for output.
expression list consists of the numeric and/or string expressions to be written to
the file.
The difference between WRITE # and PRINT # is that WRITE #
• inserts commas between items as they are written to the disk.
• does not put a blank space in front of a positive number.
• delimits strings with quotation marks.
A return/line feed sequence is inserted after the last item in the list is written to
disk.
Closing a File
The CLOSE statement is used to terminate input/output to a disk file or device.
A CLOSE with no file numbers specified closes all open files. This statement
performs the following housekeeping task:
• Physically writes the last partially filled buffer on the disk (Sequential file
only). The WRITE statement places data in the buffer and the data are written
to the disk when the buffer is filled. Generally, the buffer will contain data
when the project terminates. These data must be written to the disk.
• Releases the buffer
• Releases the file number
The syntax is:
CLOSE [[#] filenumber [,[#] filenumber]...]
Where,
filenumber is the number under which the file was opened.
Examples:
CLOSE
Closes all the open files.
CLOSE #1, 2, 3
Closes the files that were opened using file numbers 1,2 and 3.
JBD
Computer Studies-10 163
Write a program to open a data file (STD.TXT) in output mode andSolved Example
store information of students. Data file should store information such
as student’s name, class, address and phone number. The program
should allow user to input records as needed.
Solution:
OPEN “std.txt” FOR OUTPUT AS #1
top:
CLS
INPUT “Enter student’s name”; n$
INPUT “Enter class”; p$
INPUT “Enter address”; d$
INPUT “Enter phone number”; s$
WRITE #1, n$, p$, d$, s$
INPUT “Do you want to add records”; y$
IF UCASE$(y$) = “Y” THEN GOTO top
CLOSE #1
END
Reading Data from a File
The INPUT # statement is used to read data items from a sequential file and
assign them to program variables. The syntax is as follows:
INPUT # filenum, variable list
Where,
filenum is the number under which the file was opened for input.
variable list contains the variable names to be assigned to the items in the file.
The variable type must match the type specified by the variable name.
The INPUT # statement does not print a question mark during execution.
If end-of-file is reached when a numeric or string item is being read, the item is
cancelled.
Example:
INPUT #1, N$, AGE, WEIGHT
JBD
164 Computer Studies-10
Solved ExampleDetecting the End of a File
The EOF function is used to indicate the end of a sequential file. The EOF function
returns a -1 if end-of-file has been reached. The function returns a 0 if end-of-
file has not been reached. If input is attempted beyond end-of-file, the message
“INPUT past end” appears.The syntax is as follows:
EOF(filenum)
Where,
filenum is the number that was used to open the file.
Write a program to display the fields student’s name, class, address and
phone number from the data file STD.TXT.
Solution:
OPEN “std.txt” FOR INPUT AS #1
CLS
PRINT “Name”, “Class”, “address”, “Phone”
PRINT STRING$(50, “-”)
WHILE NOT EOF(1)
INPUT #1, n$, p$, d$, s$
PRINT n$, p$, d$, s$
WEND
CLOSE #1
END
Renaming a Disk File
The NAME...AS.. statement is used to rename files on the disk.The syntax is as
follows:
NAME old filename AS new filename
Where,
old filename is a string expression containing the device and current filename.
new filename is the new name of the file.
Example:
NAME “MARK” AS “EXAM”
Locates the file MARK and then renames it EXAM.
JBD
Computer Studies-10 165
Deleting a File
The KILL statement deletes a specified file from the disk. The syntax is as follows:
KILL filespec
Where,
filespec contains the device name and the filename. The file specification must
be enclosed in quotes. The filename in the file specification can be used with the
DOS wild card characters to delete more than one file at the same time. If you
issue a KILL for a file that is open, a File already open error occurs.
Example:
KILL “EXAM.BAS”
Deletes the file EXAM.BAS from the current directory of the disk in the default
drive.
Display Names of the Files
The FILES statement is used to display the names of the files on a disk. The syntax
is as follows:
FILES [filespec]
Where,
filespec is a string expression containing the device name and filename. The file
specification must be enclosed in quotes. The standard DOS wildcard characters
may be used in the file specification. When the file specification is omitted the
FILES statement lists all the filenames on the current drive and directory.
Example:
FILES
List all files in the current directory on the disk in the default drive.
FILES “*.BAS”
List all files with .BAS extension in the current directory on the disk in the default
drive.
Creating a New Directory
The MKDIR statement creates a new directory on the specified disk. The syntax
is as follows:
MKDIR Pathname
Where,
Pathname is a string expression that identifies the new directory.
JBD
166 Computer Studies-10
Solved ExampleChanging the Default Directory
The CHDIR statement changes the default directory on the specified drive. The
syntax is as follows:
CHDIR Pathname
Where,
Pathname is a string expression which identifies the new directory that will
become the current directory.
Removing a Directory
The RMDIR statement removes a directory from the specified disk. The syntax is
as follows:
RMDIR Pathname
Where,
Pathname is a string expression, can have maximum of 128 characters, identifying
the subdirectory to be removed from its parent.
The directory to be deleted must be empty.
Reading a String of n Characters
The INPUT$ function is used to read a string of n characters from the file. The
syntax is as follows:
INPUT$ ( n,[, [#] filenum] )
Where,
n is the number of characters to be read.
filenum is the number under which the file was opened.
CLS
OPEN “TEST” FOR OUTPUT AS #1
PRINT #1, “BASIC”
CLOSE
OPEN “TEST” FOR INPUT AS #1
PRINT INPUT$(3, #1)
CLOSE
JBD
Computer Studies-10 167
Solved ExampleUpdating a Sequential File
Updating process can be of deleting of some data from the data file, adding of
some new data to the data file or editing or making some changes to the existing
data in the file or it could be joining two data files to create a new file.
Modification of Existing Records
Modification means changing the contents of an existing record in the original
file. The steps to modify a sequential access data file are:
a. Open the main data file in input mode (“I”) to read data.
b. Open a new temporary data file in output (“O”) mode to write data.
c. Read data from the main data file and display to the user.
d. If necessary, correct the data.
e. Write new modified data to the temporary file.
f. Repeat steps from c to e until all the data is written into the temporary file.
g. Close both the files.
h. Delete temporary file from the storage device.
i. Finally, rename temporary data file as main data file.
REM “Modify the salary of an employee”
OPEN “std.txt” FOR INPUT AS #1
OPEN “temp.txt” FOR OUTPUT AS #2
WHILE NOT EOF(1)
INPUT #1, n$, p$, d$, s$
PRINT “Enter name of student:::”; n$
PRINT “Class:::”; p$
PRINT “Address:::”; d$
PRINT “Phone number:::”; s$
INPUT “Edit the phone number”; y$
IF UCASE$(y$) = “Y” THEN
INPUT “Enter the new phone no.”; ns$
WRITE #2, n$, p$, d$, ns$
ELSE
JBD
168 Computer Studies-10
Solved ExampleWRITE #2, n$, p$, d$, s$
END IF
WEND
CLOSE #1, #2
KILL “std.txt”
NAME “temp.txt” AS “std.
txt”
END
Deletion of Records
If you need to delete some data from a sequential access data file then most of the
process will remain same as in the modification process.
The only difference is that instead of modifying and writing the data to the
temporary data file, copy all the data to the temporary data file, except the data
that you want to delete. When the temporary data file is renamed as the main
data file it will not contain the data you want to delete.
The steps to delete a sequential access data file are:
a. Open the main data file in the input mode (“I”) to read data.
b. Open a new temporary data file in output (“O”) mode to write data.
c. Read data from the main data file and display to the user.
d. If you want to delete any data then
do not write to the temporary data file else write it in the temporary data file.
e. Repeat steps c and d until all the data is written into the temporary file.
f. Close both the files.
g. Delete main data file from the backing storage.
h. Finally, rename temporary data file as main data file.
REM “To delete data from the file”
OPEN “std.txt” FOR INPUT AS #1
OPEN “temp.txt” FOR OUTPUT AS #2
top:
WHILE NOT EOF(1)
INPUT #1, n$, p$, d$, s$
PRINT “Student’s Name:::”; n$
PRINT “Class:::”; p$
JBD
Computer Studies-10 169
PRINT “Address:::”; d$Solved Example
PRINT “Phone no:::”; s$
INPUT “Delete record”; y$
IF UCASE$(y$) = “Y” THEN
GOTO top
ELSE
WRITE #2, n$, p$, d$, s$
END IF
WEND
CLOSE #1, #2
KILL “std.txt”
NAME “temp.txt” AS “std.txt”
END
Insertion of New Records
Opening a data file in the append mode (”A”) adds any new data entered to the
end of the data file. Sometime you need to add some data in between the already
existing data in a data file.
When you need to add some data in between the existing data, again you need to
use a temporary data file, and copy all the data from the main data file with the
additions required to this temporary data file.
The steps to insert new records between the existing data are:
a. Open the main data file in the input mode (“I”) to read data.
b. Open a new temporary data file in the output (“O”) mode to write
data.
c. Read data from the main data file and write to the temporary data file until
the place where new data is to be added is reached.
d. Get new data and write to the temporary data file.
e. Read rest of the main data file and write to the temporary data file.
f. Close both the files.
g. Delete main data file from the storage device.
h. Rename temporary data file as main data file.
JBD
170 Computer Studies-10
Solved ExampleREM “Toinsert new record”
OPEN “std.txt” FOR INPUT AS #1
OPEN “temp.txt” FOR OUTPUT AS #2
WHILE NOT EOF(1)
INPUT #1, n$, p$, d$, s$
PRINT n$, p$, d$, s$
INPUT “Add record before this(y/n)”; y$
IF UCASE$(y$) = “Y” THEN
INPUT “Enter the new name”; nn$
INPUT “Enter class”; np$
INPUT “Enter address”; nd$
INPUT “Enter phone no”; ns$
WRITE #2, nn $, np$, nd$, ns$
END IF
WRITE #2, n$, p$, d$, s$
WEND
CLOSE #1, #2
KILL “std.txt”
NAME “temp.txt” AS “std.txt”
Insertion of New Records
Opening a data file in the append mode (”A”) adds any new data entered to the
end of the data file. Sometime you need to add some data in between the already
existing data in a data file.
When you need to add some data in between the existing data, again you need to
use a temporary data file, and copy all the data from the main data file with the
additions required to this temporary data file.
The steps to insert new records between the existing data are:
a. Open the main data file in the input mode (“I”) to read data.
b. Open a new temporary data file in the output (“O”) mode to write
data.
c. Read data from the main data file and write to the temporary data file until
the place where new data is to be added is reached.
d. Get new data and write to the temporary data file.
e. Read rest of the main data file and write to the temporary data file.
f. Close both the files.
g. Delete main data file from the storage device.
h. Rename temporary data file as main data file.
JBD
Computer Studies-10 171
Solved ExampleREM “Toinsert new record”
OPEN “std.txt” FOR INPUT AS #1
OPEN “temp.txt” FOR OUTPUT AS #2
WHILE NOT EOF(1)
INPUT #1, n$, p$, d$, s$
PRINT n$, p$, d$, s$
INPUT “Add record before this(y/n)”; y$
IF UCASE$(y$) = “Y” THEN
INPUT “Enter the new name”; nn$
INPUT “Enter class”; np$
INPUT “Enter address”; nd$
INPUT “Enter phone no”; ns$
WRITE #2, nn$, np$, nd$, ns$
END IF
WRITE #2, n$, p$, d$, s$
WEND
CLOSE #1, #2
KILL “std.txt”
NAME “temp.txt” AS “std.txt”
Searching a Record
Data from sequential file is searched sequentially, item after item starting at the
beginning. The steps to search records are listed below:
a. Open the main data file in the input mode (“I”) to read data.
b. Initialize the variable Flag by 0.
c. Ask the user to input name to be searched.
d. Read the data from the data file.
e. Compare the input name with the name in the data file.
f. Is the name matching?
{ Yes: Display the record
No: Goto step g }
g. Is EOF (End of File) reached?
{ Yes: Goto step h
No: Read the next record }
h. If Flag = 0 the display “Record does not exist”
i. Close the file
JBD
172 Computer Studies-10
Hands on
Problem
1. Write a program to create a sequential file result.dat to store the information of 10 students.
The related information title are: name, class and marks secured in three subjects.
Solution:
CLS
OPEN “result.dat” FOR OUTPUT AS #1
FOR i = 1 TO 10
INPUT “Enter a name:::”; n$
INPUT “Enter a class:::”; c$
INPUT “Enter marks in english:::”; e
INPUT “Enter marks in maths:::”; m
INPUT “Enter marks in computer:::”; c
WRITE #1, n$, c$, e, m, c
NEXT
CLOSE #1
2. A sequential data file RESULT.DAT contains the name and marks secured by the students in
three subjects. Assuming that mark for each subject is 32, write a BASIC program to count
the number of students passed.
Solution:
OPEN “result.dat” FOR INPUT AS #1
WHILE NOT EOF(1)
INPUT #1, n$, c$, e, m, c
IF e >= 32 AND m >= 32 AND c >= 32_ THEN t = t + 1
PRINT n$, c$, e, m, c
WEND
PRINT “Total passed students:::”; t
CLOSE #1
3. Write a program to open a data file EMP.DAT in append mode and store information such as
name, address and salary. The program should allow user to input records as needed. After
the record entry, the program should display all the records from the file EMP.DAT.
Solution:
REM “To create the file EMP.DAT”
OPEN “EMP.DAT” FOR APPEND AS #1
top:
JBD
Computer Studies-10 173
INPUT “Enter employee’s name”; n$
INPUT “Enter his address”; ad$
INPUT “Enter his salary”; s
WRITE #1, n$, ad$, s
INPUT “Do you want to add records”; y$
IF UCASE$(y$) = “Y” THEN GOTO top
CLOSE #1
REM “To read the file EMP.DAT”
PRINT “Name”, “Address”, “Salary”
OPEN “EMP.DAT” FOR INPUT AS #1
WHILE NOT EOF(1)
INPUT #1, n$, ad$, s
PRINT n$, ad$, s
WEND
CLOSE #1
END
4. Write program to read the data file marks.dat and find the highest mark of a class.
Solution:
max = 0
OPEN “marks.dat” FOR INPUT AS #1
PRINT “roll no”, “name”, “marks”
WHILE NOT EOF(1)
INPUT #1, r, n$, m
PRINT r, n$, m
IF max < m THEN
max = m
END IF
WEND
PRINT “The highest mark is :”; max
CLOSE #1
END
JBD
174 Computer Studies-10
C Dompu- ictionary
Data file : A data file is a collection of data organized in a specific
format and for a specific purpose which is kept
somewhere in external memory.
File Organization : File organization refers to the way of organizing
or arranging the data in a file, so that it is retrieved
conveniently.
Random access files : Random access files can be accessed in any order. This
makes it unnecessary to read through all of the data
records to get to a specific data record.
Sequential access file: A sequential access file is a file that must be accessed
in a sequential order, starting at the beginning of the
data block and preceding in order until an end-of-
data marker is encountered of the required number of
items has been read.
Recap
• A data file is a collection of data organized in a specific format and for a
specific purpose which is kept somewhere in external memory.
• File organization refers to the way of organizing or arranging the data in a
file, so that it is retrieved conveniently.
• A sequential access file is a file that must be accessed in a sequential order,
starting at the beginning of the data block and preceding in order until an
end-of-data marker is encountered of the required number of items has been
read.
• The OPEN statement prepares for input/output to a file or device. The file or
device must be opened before any input or output is attempted to it.
• The CLOSE statement is used to terminate input/output to a disk file or
device.
• The INPUT # statement is used to read data items from a sequential file and
assign them to program variables.
• The EOF function is used to indicate the end of a sequential file.
• The LINE INPUT # statement is used to read an entire line without delimiters
from a sequential file into a string variable.
• The NAME...AS.. statement is used to rename files on the disk.
• The KILL statement deletes a specified file from the disk.
JBD
Computer Studies-10 175
Review Yourself
1. Answer the following questions.
a. What is a data file, a record and a field?
b. What do you understand by file organization? Name the two types of
file organization supported by QBASIC.
c. What are the criteria needed for choosing a file organization?
d. Explain the difference between a sequential file and a random file.
e. What is the major difference between “O” mode and “A” mode of
sequential file creation?
f. Write the purpose and syntax of the following QBASIC keywords.
i. OPEN statement
ii. PRINT # statement
iii. CLOSE statement
iv. INPUT # statement
v. EOF function
2. Study the following program and answer the given questions.
OPEN “Detail.Dat” FOR INPUT AS # 1
OPEN “Temp.Dat” FOR OUTPUT AS # 2
INPUT “Name of the students”; NM$
FOR I = 1 TO 10
INPUT # 1, N$ , C, A
IF NM$<> N$ THEN
WRITE #2, N$, C, A
END IF
NEXT I
CLOSE #1, #2
KILL “Detail.Dat”
NAME “Temp.Dat” AS “Detail.Dat”
END
a. What is the main objective of the above program?
b. If the data file “detail.dat” contains only 8 records, then the program will
run? If not then what will be error message?
JBD
176 Computer Studies-10
3. Solve the following problems.
a. Write a program to create a file EMP.DAT which contains the employee
code, name, age and basic pay of 5 workers. It also contains the DA as
35% of basic pay, HRA as 10% of basic pay and total pay as the sum of
basic pay, HRA and DA.
b. Write a program to display all records from a data file EMP.DAT that
contains employee code, name, age and basic pay, HRA and DA of 5
workers.
c. A sequential data file “EMP.DAT” contains employee code, name, age
and basic pay, HRA and DA of 5 workers. Write a program to update the
basic pay of every employee by 10%.
d. Write a program in BASIC to create a sequential data file “ADD.TXT”
which asks the name, address and salary of ten employees.
e. Write a program to display all the records from “ADD.TXT” for the
employees whose salary is more than 20000 and update their salary by 20%.
f. Write a program to ask name, symbol number and division of a student
and save them in a data file “EXAM.DAT”.
g. Write a program to append name, identification number of a staff in an
existing data file “INFO.DAT”the program should be able to store any
number of records as per the user’s desire.
h. Write a program to create a data file EMP.DAT containing emp_num,
emp_name and basic_salary of ten employees.
i. Write a program to read all the records from the EMP.DAT and find the
total basic salary the company has to pay to its employee.
j. Write a program to create a sequential file data file “REPORT.DAT” which
ask the students’ name, class and marks secured in three subjects for ten
students.
k. Write a BASIC program to count the number of passed students from the
sequential file “REPORT.DAT”. Assuming that mark for each subject is 50.
l. Write a program to create a data file EMP.REC containing emp_num,
emp_name and basic_salary of five employees.
m. Write a program to read all the records from the EMP.REC and find the
total basic salary the company has to pay to its employee.
n. Create a sequential data file “MARKS.DAT” to store student’s name and
marks in Eng, Math and Computer of number of students.
o. Write a program to display the records of files whose marks in English is
greater than 60.
JBD
Computer Studies-10 177
Chapter 11
INTRODUCTION
TO
C-LANGUAGE
Objectives
After completing this chapter, you will be able to:
y Explain the characteristics of C language.
y Explain the different elements of C language.
y Explain the two important categories of control statements in C language.
y Differentiate between single dimensional array and double dimensional array.
y Explain the advantages of using function in C language.
y Describe the two important methods of passing an arguments.
C Ooncept verview
C is a general-purpose programming language. It
is very versatile and functional language. It was
designed by Dennis Ritchie in early 70’s at the Bell
Telephone Laboratories for use with the Unix operating
system. C gained more popularity in programming
environment because it is reliable, simple and easy to
use. C stands between high level language and low
level language. That is why it is called a middle level
language. It provides low-level access to memory,
provides language constructs that map efficiently to
machine instructions and require minimal run-time
support.
Despite its low-level capabilities, the language
was designed to encourage machine-independent
programming. The C program can be compiled for a
very wide variety of computer platforms and operating
systems with minimal change to its source code.
JBD
178 Computer Studies-10
C-Language Defined
C is a general-purpose programming language. It is very versatile and functional
language. It was designed by Dennis Ritchie in early 70’s at the Bell Telephone
Laboratories for use with the Unix operating system. C gained more popularity
in programming environment because it is reliable, simple and easy to use. C
stands between high level language and low level language. That is why it is
called a middle level language. It provides low-level access to memory, provides
language constructs that map efficiently to machine instructions and require
minimal run-time support.
Despite its low-level capabilities, the language was designed to encourage
machine-independent programming. The C program can be compiled for a very
wide variety of computer platforms and operating systems with minimal change
to its source code. The language has become available on a very wide range of
platforms, from embedded micro controllers to supercomputers.
Characteristics of C-Language
C-Language is a programming language widely used for systems programming.
It exhibits the following specific characteristics:
• It is a structured programming language.
• It is a general purpose programming language.
• It has rich and powerful set of operators.
• It supports a rich set of data declaration and data type.
• It has 32 reserved words.
• It provides low-level access to computer memory by converting machine
addresses to typed pointers.
Elements of C-Language
The important elements of C-Language are:
• Character set
• Keywords
• Variables
• Constants
• Operators
JBD
Computer Studies-10 179
Character set
Character set is a set of valid characters that a language can recognize. A character
represents any letter, digit, or any other sign. The C-langauge has the following
character set:
Letters: A-Z, a-z
Digits: 0-9
Special Symbols: Space + -* / ^ \ () [] {} = != < > . ‘ “ $ , ; : % ! & ? _(underscore) #
<= >= @
White spaces: Blank space, Horizontal tab, Carriage return, Newline, Form feed.
keywords
Words, which have special meaning for the compiler, are known as keywords.
Keywords can only be used for some special purposes. These are also known as
reserved word, which means these words cannot be used as identifiers.
Variables
Variable refers to a storage area whose contents can vary during processing. For
instance, to store name of a student and marks of a student during a program run,
we require storage locations that too named so that these can be distinguished
easily. Variables, called as symbolic variables, serve the purpose.
Rules for naming variables in C-Language:
The C-Language defines certain rules for naming variables. You must name
variables according to these rules; otherwise, your program will not compile.
• Variable name must begin with a letter or an underscore (’_’), which may be
followed by a sequence of letters, digits (0-9), or “_”.
• Variable names must be unique.
• ‘C’ keywords should not be used as variable names.
• Both upper case and lower case letters are permitted.
• The name of a variable needs to be without any embedded space.
Examples of variable names
• student_name
• int r = 35;
Constants
Constant is a data item which does not change its value during the execution of
a program. It is often referred to as literals. Constant is commonly used to store
known variable.
The C language provides several different kinds of constants:
JBD
180 Computer Studies-10
Integer constant
Integer constant is a whole number without any fractional part. It may contain
+ or -sign. A number with no sign is assumed to be positive. Commas cannot
appear in an integer constant.
For example,
• int radius=35;
Real constant
Real constant is a number having fractional parts. It may also have either + or - sign
preceding it. A real constant with no sign is assumed to be positive.
For example,
• float area=252.50;
Character constant
Character constant consists of one or more characters enclosed in single quotes.
For example,
• char add=’d’;
String literal
String literal is a sequence of zero or more characters surrounded by double
quotes. When a string literal is assigned to an identifier declared as a constant,
then it is known as a string constant.
For example,
• char const name[]=”Divya”
Data Types
Data type is defined as the set of possible values a variable can hold. The power
of a programming language is often measured by the variety and abundance of
data types that it supports. There are four basic data types in C. They are char,
int, float and double.
Data Type Byte Range
char 1 0 to 255
int 2 -32768 to 32767
float 4 6 digits of precision
double 8 12 digits of precision
JBD
Computer Studies-10 181
Data Type Modifiers
A modifier is used to change the meaning of the basic data type according to the
requirement of the program. The data modifiers are short, unsigned and long.
Following table shows data type modifiers with memory consumption.
Modifier Byte
short int 2
long int 4
unsigned short 2
unsigned long int 4
Operators
C-Language is enhanced with various built-in operators. Operators are the
symbols or letters which makes the compiler perform a specific operations on
operands (variables) in a program. The operators provided by C-Language are
classified under different categories. They are:
• Arithmetic operators
• Arithmetic assignment operators
• Increment and Decrement operators
• Relational operators
• Logical operators
• Ternary operator
Arithmetic operators
Arithmetic operators are used for various mathematical calculations. The result
of an arithmetic expression is a numeric value. There are five different arithmetic
operators in C-Language. They are addition, subtraction, multiplication, division
and remainder, which are +, -, *, / and % respectively. These operators work on
all the data types. Each operator requires at least two values called operands. The
following table lists the arithmetic operators:
Operator Meaning Example
+ Addition t=a+b
- Subtraction t=a-b
* Multiplication t=a*b
/ Division t=a/b
% Modulo
division t=a%b
JBD
182 Computer Studies-10
Assignment operators
Assignment operator is represented by the symbol ‘=’. The assignment operator
takes the value on the right side and stores it in the variable on the left side. An
expression is composed of one or more operations. An expression itself has a
value, which is the same that is assigned to the left-hand operand. The syntax is
as follows: x <operator>=y
Operator Meaning Example
= Assignment x=y
+= Add to x+=y
-= Subtract from x-= y
*= Multiply by x*=y
/= Divided by x/=y
%= Modulo by x%=y
Increment and Decrement operators
These operators are unique to C. C provides ++ and -- operators. These operators
are called increment and decrement operators. They are also arithmetic operators.
They can be used with one or more than one operands.
Operator Meaning Example
++ Increases the value of the operand x++
-- Increases the value of the operand x--
Relational operators
Relational operator is used to compare two values and the result of this
comparison is always logical i.e. either true or false. They are used to determine
the relationship between different operands. Mathematical expressions can
be connected by a relational operator. C provides six relational operators for
comparing numbers and characters.
Operator Meaning Example
== Equal to a == b
< Less than a<b
> Greater than a>b
<= Less than or
equal to a <= b
>= Greater than
or equal to a >= b
!= Not equal to a !=b
JBD
Computer Studies-10 183
Logical operators
Logical operator is used to connect two relational or logical expressions. The
result of such an operation is always logical i.e. either true or false. The commonly
used logical operators in C-Language are &&, ||and !.
Rules of logical operators
• The output of the logical AND
operation is true if both its operands are true. For all other combinations, the
result is false.
• The output of the logical OR operation is false if both operands are false. For
all other combinations, the result is true.
• The logical NOT is a unary operator. It negates the value of the operand.
Operator Meaning Example
&& Logical AND a && b
|| Logical OR a || b
! Logical NOT !a
Ternary operator
Ternary operator is powerful and unique. It provides a “shorthand” method of
expressing a simple if/else statement. The operator consists of the question-mark
(?) and the colon (:). The general format is:
expression ? expression : expression;
A first look at C program
Let us start with simple example of a C language that prints a string on the screen.
Solved Example /* This is first C program */
#include<stdio.h>
void main()
{
printf(“Fun with C programming”);
getch();
}
JBD
184 Computer Studies-10
The above program produces following output.
Fun with C programming
The above program is one of the simplest programs that can be written in C. Let’s
examine the program line by line.
/* This is first C program */
This is a comment.All lines beginning with /*__________*/ are comments. Compiler
does not execute comments. Comments are included for the programmer for
short explanations or observations.
#include<stdio.h>
The statements that begins with # sign are called directives for the preprocessor.
Preprocessor directives are statements that are processed before the program is
compiled. The software that handles these directives is called the preprocessor.
The preprocessor directive shown above attaches the code of the header file stdio
to your program. Header files contain all the information that is required to make
use of the C libraries that are attached to your code during the linking process.
void main()
This line indicates the beginning of main function. The main() function is the
point from where all C programs begin their execution. Infact, the content of
main() is always the first to be executed when a program starts. Every function
contains a function body, delimited by curly braces (’{’ and ‘}’).
printf(“Fun with C programming”);
This line displays the message on the screen. Every executable statements must
be terminated by a semicolon (;).
getch();
This line reads a single character directly from the keyboard, without echoing to
the screen.
Formatted Input-Output
C provides the standard functions, scanf() and printf(), for performing formatted
input and output respectively. They are included in the header file, stdio. These
functions accept, as parameters, a format specification string and a list of variables.
The format specification string is a character string that specifies the data type of
each variable for input or output and the size or width of the input or output.
JBD
Computer Studies-10 185
The printf() function
The printf() is a function used to send formatted output to the standard output
device based on a format specification. The format specification string and the
data to be output, are the parameters to the printf() function. The general format
is:
printf(format, data1, data2,...);
where,
format is the format specification string. For each variable to be displayed this
string contains a specification beginning with the symbol %, followed by a
character called the conversion character.
Example:
printf(”%c”, add);
The format specifiers and their meanings are:
Format specifier Meaning
%d
%c The data is formatted to integer.
%s
The data is formatted as a character.
%f
The data is a string and characters from the string are
printed until a NUL character is reached.
The data is output as float or double with a default
precision of 6.
Other symbols permitted in the format specification string are:
Symbol Meaning
\n Used for a new line.
\t Used for tab
The scanf() function
The scanf() is a function used for formatted input from the standard input device
(the keyboard) and provides many of the conversion facilities of the printf()
function. The general format is:
scanf(format, data1, data2,...);
The scanf() function reads characters from the standard input device, formats
them according to the format specification string, and stores the input in memory
locations represented by the other arguments (data1, data2,...).
Examples:
scanf(”%d”, &a);
scanf(”%d %d”, &a, &b);
JBD
186 Computer Studies-10
Solved ExampleSolved Example
#include<stdio.h>
void main()
{
int l,b,area;
printf(“Enter the length of a rectangle”);
scanf(“%d”, &l);
printf(“Enter the breadth of a rectangle”);
scanf(“%d”,&b);
area=l*b;
printf(“\n The area is=%d”,area);
getch();
}
Flow of Control
A program is a set of different types of statements viz. statements to receive input
from user, statements to process data or to perform calculation and statements
to display the output. The statements in a program can be executed in a similar
manner as they appear in the program or we can direct the control to a particular
statement based on specific conditions.
Generally a program executes its statements from beginning to end. But not
many programs execute all their statements in strict order from beginning to
end. Most of the programming languages decide what to do in response to
changing circumstances. The flow of control jumps from one part of the program
to another, depending on the calculations performed in the program. Program
statements that cause jumps are called control statements.
The control statements of C language can be put into the following
categories:
• Selection statements
• Looping statements
Selection Statements
Selection statements allow your program to choose different path of execution
based upon the outcome of an expression or the state of a variable. C supports
two major types of selection statements: if statement and switch statement.
JBD
Computer Studies-10 187
Solved ExampleThe if statement
The if statement is a selection statement. If the condition is true then the statement
after the condition will be executed otherwise execution will skip to the next
statement. The general format is:
if (condition)
statement;
or
if (condition)
{
statement1;
statement2;
// Place as many statements
// here as necessary.
}
#include<stdio.h>
void main()
{
int n,r;
printf(“Enter any number”);
scanf(“%d”,&n);
r=n%2;
if (r==0)
printf(“It is an even number.”);
getch();
}
The if...else statement
The most common selection statement in C program is the if...else statement. The
execution of the if...else statement starts with the evaluation of conditions. The
statement tests one condition; if the first condition is false, the other is tested. The
general format is:
if(condition)
statement1;
else
statement2;
JBD
188 Computer Studies-10
Solved Example #include<stdio.h>
void main()
{
int n,r;
printf(“Enter any number”);
scanf(“%d”,&n);
r=n%2;
if (r==0)
printf(“It is an even number.”);
else
printf(“It is an odd number.”);
getch();
}
The if...else if statement
The if...elseif statement is a chain of if statements. It is used to perform a series of
tests, one after the other, until one of them is found to true. This construction is
like a chain of if/else statements connected together. The else part of one statement
is linked to the if part of another. When put together this way, the chain of if/else’s
becomes one long statement. The general format is:
if(condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
...
else
statement;
JBD
Computer Studies-10 189
# include <stdio.h>Solved Example
void main()
{
int a,b,c;
printf(“Enter a first number”);
scanf(“%d”,&a);
printf(“Enter a second number”); scanf(“%d”,&b);
printf(“Enter third number”);
scanf(“%d”,&c);
if (a>b && a>c)
{
printf(“A is greatest”);
}
else if (b>a && b>c)
{
printf(“B is greatest”);
}
else if (c>a && c>b)
{
printf(“C is greatest”);
}
else
{
printf(“Wrong entry”);
}
}
The switch statement
C language provides a multi-branch selection statement known as switch. It
is used when there are multiple values for a variable. When switch statement
is executed, its condition-variable is evaluated and compared with each case
construct. If one of the case constants is equal to the value of the condition-
variable, control is passed to the statement following the matched case label.
JBD
190 Computer Studies-10
If no case constant matches the condition-variable, the control passes to the
statement labelled default. A break statement is used to exit the switch statement.
The general format is:
switch (expression)
{
case value1:
statement block;
break;
case value2:
statement block;
break;
default:
statement block
}
Solved Example #include<stdio.h>
void main()
{
int choice, months;
float charges;
printf(“Club Membership Menu\n”);
printf(“1.Child Membership\n”);
printf(“2.Senior Membership\n”);
printf(“3.Quit the Program\n”);
printf(“Enter you choice:”);
scanf(“%d”, &choice);
printf(“Enter months:”);
scanf(“%d”,&months);
switch (choice)
{
case 1:
charges=months*40;
printf(“Total charge is= %f”,charges);
break;
case 2:
charges=months*20;
JBD
Computer Studies-10 191
printf(“Total charge is= %f”,charges);
break;
case 3:
printf(“Thanks”);
break;
default:
printf(“Wrong choice”);
}
getch();
}
Looping Statements
A looping statement allows a set of instructions to be performed repeatedly until
a certain condition is fulfilled. C language provides three kinds of loops: for loop,
while loop and do-while loop.
All three loop constructs of C language repeat a set of statements as long as a
specified condition remains true. This specified condition is generally referred to
as a loop control. For all three loop statements, a true condition is any nonzero
value. A zero value indicates a false condition.
The for loop
The for loop is the easiest to understand of the C language loop. It is an entry-
controlled loop. It provides a compact way to iterate over a range of values by
defining the initial, increment and final values of the counter variable. The number
of increments required to reach the final value of counter variable determines the
number of times the body of the loop will be executed. The general format is:
for (initialization;test;update)
statement;
or
for (initialization;test;update)
{
statement;
...
...
}
JBD
192 Computer Studies-10
Solved Example#include<stdio.h>
#include<conio.h>
Solved Examplevoid main()
{
int var;
clrscr();
for (var =1; var<=10;var++)
{
printf(“%d\n”,var*var);
}
getch();
}
The while loop
The while loop is an entry-controlled loop. It is used to continually execute a block
of statements while the test expression or the control statement remains true. As
soon as the condition becomes false, the program control leaves the loop and
goes to the next immediate statement after the while loop. The general format is:
while (condition)
statement;
or
while (condition)
{
statement;
statement;
...
#include<stdio.h>
#include<conio.h>
void main()
{
int n, rem, rev=0;
clrscr();
JBD
Computer Studies-10 193
Solved Example printf(“Enter a number”);
scanf(“%d”, &n);
while(n!=0)
{
rem=n%10;
n=n/10;
rev=rev*10+rem;
}
printf(“The reversed number=%d”,rev);
getch();
}
The do...while statement
The do...while loop is an exit-controlled loop i.e., it evaluates its test-expression
after executing its loop body statements. It executes the body of the loop before
its execution is tested and ensures that the body always executes at least one
time. The do...while places its conditional expression at the bottom of the loop.
The general format is:
do
{
statement block;
}
while(condition);
#include<stdio.h>
#include<conio.h>
void main()
{
int n, num, digit, reverse=0;
clrscr();
printf(“Enter the number”);
scanf(“%d”,&num);
JBD
194 Computer Studies-10
Solved Example n=num;
do
{
digit=num%10;
reverse=reverse*10+digit;
num=num/10;
}while (num!=0);
if(n==reverse)
printf(“Number is palindrome”);
else
printf(“Number is not palindrome”);
getch();
}
Nested Loop
A loop may contain another loop in its body. This form of a loop is called nested
loop. The inner and outer loops may not be of the same construct.
The rules for the formation of nested loops are:
• An outer loop and inner loop cannot have same control variable.
• The inner loop must be completely nested inside the body of the outer loop.
• The inner loop must terminate before the outer loop.
• Outer loop opens first but closes last.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(”\n Enter any number:”);
scanf(”%d”, &a);
for (int i=1; i<=a; i++)
JBD
Computer Studies-10 195
{
for (int j=1; j<=i; j++)
printf(”%d\n”, i);
}
getch();
}
Arrays in C-Language
An array is a group of like-typed variables that are referred to by a common
name. Each array element has a distinct position in the array. All the elements of
an array have the same data type. Each element of an array can be referred by an
array name and its subscript. The subscript number specifies the position of an
element within the array (also called the index of the element). The first element
of an array has an index of 0 and the last element has an index one less than the
dimension size of the array.
An array may be a single-dimensional array or multi-dimensional array.
Single Dimensional Array
An array whose elements are specified by a single subscript is known as a one
dimensional (or single dimensional) array. It is used to process data items of the
same type.
Array Declaration
Like simple variables of C language, an array needs to be declared before it can be
used to store information. An array declaration defines a variable type, variable
name and size. The general format is:
data type variable-name[size]
where,
Data type is the base type of the array.
variable-name is the name with which array will be referenced.
size is the number of elements an array can hold.
JBD
196 Computer Studies-10
#include<stdio.h>Solved Example
#include<conio.h>
void main()
{
int l;
int n[5]={4,6,99,3,2};
int g=0;
for (l=0;l<=4;l++)
{
if(n[l]>g)
g=n[l];
clrscr();
printf(“Greatest number=%d”, g);
}
getch();
}
Multidimensional Array
An array that has more than one subscript is known as multidimensional array.
It can be visualized as array of arrays.
Array Declaration
A two dimensional array is the simplest form of a multidimensional array. In a
two dimensional array, two subscripts are enclosed in square brackets. The first
subscript designates the row and the second subscript designates the column. It
is used for table processing or matrix processing.
The general format of a two dimensional array declaration in C language is as
follows:
data type variable-name[rows][columns]
where,
Data type is the base type of the array.
variable-name is the name with which array will be referenced.
rows denotes the number of rows.
columns denotes the number of columns.
JBD
Computer Studies-10 197
# include <stdio.h>Solved Example
# include <conio.h>
void main()
{
int j,k;
int num[3][4]={1,2,3,4,5,7,3,4,5,6,3,2};
clrscr();
for(j=0;j<3;j++)
{
int sum=0;
for(k=0;k<4;k++)
{
printf(“%d \t”,num[j][k]);
sum=sum+num[j][k];
}
printf(“=%d”,sum);
printf(“\n”);
}
}
Functions in C-Language
Functions are the building blocks of C language and the place where all program
activities occurs. It is a collection of statements that performs a specific task. It
can be invoked from the other parts of the program and should return a value. It
groups a number of program statements into a single unit.
Every function has its own name, and when that name is encountered, the
execution of the program branches to the body of that function. When the function
returns, execution resumes on the next line of the calling function.
Functions come in two varieties: library functions and user defined functions.
Library functions are a set of pre-defined functions whereas user defined
functions are the functions created by the user at the time of writing a program.
JBD
198 Computer Studies-10
Solved ExampleThe advantages of a function are:
• A function breaks up a program into a small and manageable unit.
• A user-defined function helps to divide a program into a number of parts,
which makes it easier to understand a program.
• If the same task has to be performed in several places in a program, a function
can be written and executed whenever it is needed. So, it reduces the size of
a program.
• The use of functions saves a programmer the problem of debugging a program
that does not function properly.
Category of Functions
The function is mainly categorized into three types:
Function with no argument and no return value
In this method, called function does not receive any value or data from the calling
function and it does not return any data back to the calling function.
#include<stdio.h>
#include<conio.h>
void main()
{
sum();
}
sum()
{
int a, b, tot;
printf(“Enter any two numbers”);
scanf(“%d %d”, &a, &b);
tot=a+b;
printf(“sum=%d”,tot);
getch();
}
Function with arguments but no return value
In this method, the called function receives the data from the calling function.
The arguments and parameters should match in numbers, data type and order.
But the called function does not return any value back to the calling function
instead it prints or uses the data in its scope.
JBD
Computer Studies-10 199
Solved Example#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
printf(“Enter any two numbers”);
scanf(“%d %d”, &a, &b);
sum();
}
sum(int a, int b)
{
int tot;
tot=a+b;
printf(“sum=%d”,tot);
getch();
}
Function with no arguments but return value
In this method, the called function does not receive any value from the calling
function. It uses the data and performs the specified task within its scope.
However after performing the specified task the called function returns the
computed value to the calling function.
Function Prototype
A function prototype is a declaration of the function that tells the program about
the type of value returned by the function and the number and type of arguments.
It enables a compiler to carefully compare each use of the function with the
prototype, to determine the function is invoked properly. The number and types
of arguments are compared and any wrong number or type of argument is
reported as an error. The general format is:
return-type function-name (parameter list);
Where,
return-type returns the type of data after the execution of function.
function-name is used at the time of calling function.
parameter list contains the types of data and name accepted by the function.
Following are some examples of function prototype:
float vol(int l, float b, float h);
JBD
200 Computer Studies-10