0% found this document useful (0 votes)
165 views177 pages

CS 1 Compressed

The document provides an overview of operating systems, explaining their role as an interface between users and computer hardware, and detailing their services including information, process, and memory management. It discusses various operating systems such as Windows and Linux, highlighting their features, architecture, and functionalities. Additionally, it covers file systems, disk management, and the operations associated with files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views177 pages

CS 1 Compressed

The document provides an overview of operating systems, explaining their role as an interface between users and computer hardware, and detailing their services including information, process, and memory management. It discusses various operating systems such as Windows and Linux, highlighting their features, architecture, and functionalities. Additionally, it covers file systems, disk management, and the operations associated with files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 177

1

OPERATINGSYSTEMS
INTRODUCTION
As all know, programs are written for execution. But if we do not know, how
to operate computer system then written programs are of no use. We must have the
environment within which user as well as other programs can do useful work. How
this environment is provided by operating system is discussed in this chapter.

1.1 IDEA OF AN OPERATING SYSTEM


user of
Anoperating system is a program, which acts as an interface between
acomputer and computer hardware. It provides an environment to run other programs
also. It makes system convenient to use. It also performs basic tasks like input and
output management i.e. it helps in using hardware in efficient manner.
Any computer system has following layer structure.
Users

Application program
Operating system
Hardware

Fig. (1.1)
Computer hardware is at innermost level. Operating system is at outer level to
that of computer hárdware. Application programs are at outer level of the operating
system. While users interact with the computer hardware through application program
and operating system.

Services in O/S
programs and to the
Operating system (0/s) provides certain services to th
users. There are following three major types of services:
1) Information Management
2) Process Management
3) Memory Management

Information Management
It refers to a set of services used for storing, retrieving, modifying or removing the
information on various devices. It manages the organization of information in terms
2 Operating Systems

of directories and files, allocating, deallocating the sectors to various files ensuring
Inght people have access to information and driving various devices.
Some of the system calls in this category are as follows:
1) Create a file 2) Create a directory
3) Open a file (for, read, write or both). 4) Close a file
5) Read data from file to buffer 6) Move the file pointer
7) Read and return file's status 8) Create a link
9) Change working directory 10) Write data from buffer to file

Process Management
If operating -system supports multiple users then services under this are very
important. In this regard operating system has to keep track of all the completing
processes (running programs), schedule them, dispatch them one after another. But
user should feel that he has the full control of the CPU.
Some of the systems calls in this category are as follows;
1) Create a child process identical to the parent
2) Terminate a process
3) Wait for a child process to terminate
4) Change the priority of process
5) Block the prOcess
6) Ready the process
7) Dispatch a process
8) Suspend a process
9) Resume a process
10) Delay a process
11) Fork a process

Memory Management
The services provided under memory management are
memory directed to keeping track
of and allocating, deallocating it to various processes.
keeps a list of free memory locations. Before a program The operating system
is loaded in memory from the
disk. this module consults this free
list, allocates the memory to the process,
depending upon program size and updates the list
of free memory.
Some of the systems calls in this category are as
1) Allocate a chunk follows,
of mnemory to process
2) Free a chunk of memory
from a process
Overview of O/S
Operating system first developed by
Microsoftwas DOS. But was a
operating system. After DOS a complete new it single user
(GUI) was developed. It was system with graphical user interfaco
windows 3.1. Later on Windows
of windows was launched. After 95 an upgraded vers1OM
that Windows 98 a new version
of
windows we
Operating Systems 3

launched. It is multitasking and again GUI based operating system. Some of the main
features of windows 98 are listed below:

1) Faster operating system


It includes tools that help your computer run faster than Windows 95 without
adding new hardware. It optimizes your computer's efficiency by a group of some
special programs that are used together some of the programs are like
1) Maintenance wizard, 2) Drive converter, 3) Disk defragmenter.

2) Easy to use
It makes your computer easier to use with new and advanced features like web
integration, multiple display support, power management, and universal serial bus.
Web integration
Windows 98 explorer and Internet explorer integrate local and web based
resources in a single view. Auto complete automatically completes previously visual
addresses as you type them. It supports for all major Internet standards Activex, Java.
Multiple display support
It makes possible to use several 'monitors simultaneously to increase size of your
desktop.
Power management
On-Now makes your computer more responsive by improving startup time. Using
power management techniques On-Now can start your computer in just a few seconds
and restore all your programs where you left them.
Universal serial bus
It makes your computer easier to use with advanced plug and play capabilities.
Using a new universally standard connector you can add devices to your computer
easily without having to restart.

3) More Entertaining and Fun


It makes your computer more entertaining by introducing new features such as
enhanced television, video playback and support for new hardware.

4) Help
It is very easier to use and find answers to questions quickly. You can also get up
todate technical support from World Wide Web (WWw).

1.2 WINDOWS NT
Windows NT is multi-user, multitasking and multithreading. operating system.
Multitasking is preemptive i.e. each task is given time slice when that time slice is
over the next one is started.
Windows NT features include vitual memory management, symmetric
multiprocessing. Symmetric multiprocessing allows Windows NT to schedule various
4 Operating Systems

tasks on any CPU. Generally tasks are scheduled on any available processor. When
tasks are broken into independent threads, a large amount of parallelism is achieved
Windows NT can interact with all existing networking systems like Novell's
Netware, Sun micro system's NFS, etc. It is also portable operating system and will
be available on other hardware platforms like Intel's X-86 family.

Virtual Dos Machine


(VDMs)
W in 32. W in 32 Posix Posix
Client Client Client Client
16- bit
Windows
Environment/

W in 32 OS 12
Subsystem Subsystem
MS- DOS W in 32
Client Subsystem

System Services
Object Manager Process Local ProceduresVirtualMemory Security
(OM)
1/0 Manager
Manager Call facilitities Manager Reference File System
(PM) (LPC) (VMM) Monitor Catche Manager
(SRM) Device Drivers
Network Driver
Kernel

(HAL) Hardware Abstraction Layer

Keyboard Monitor Monitor Modem Mouse Other

Fig. (1.2) Architecture of Windows NT

Windows NT has a new high performance file system called New Technology File
System (NTFS)implements fault tolerance, security and has support for large files.
Windows NT has a modular architecture divided into different subsystems and
layers. At lowest layer is hardware abstraction layer. It provides all hardware specific
functions. On top of that is the Windows NT kernel. It provides basic operating
system services. On top of kernel there are six modules, which are listed below with
their functions.
1) Object manager- it creates manages and deletes objects, which are processes.
2) Process manager- it creates, terminates, suspends and resumes processes, tasks,
and threads.
3) Virtual memoIy manager- it manages the memory for prOcesses. It also allocates
and frees memory.
4) Security reference monitor- It enforces security policy and keeps
track of file
access rights based on ownership and
permission for the user.
Operating Systems
5
5)Local procedures call facility- it is
used to pass messages between client systems
and subsystems on one system.
6) JO subsystem- it handles device and passes to
data and receives data from the
devices of all subsystems.

1.3 LINUX
Linux is an operating system that was initially created as a
young student, Linus Torvalds, at the hobby by a
University of Helsinki in Finland. Linus had an
interest in Minix, a small UNIX systemn, and decided to
develop a system that
exceeded the Minix standards. He began his work in 1991 when he
released version
0.02 and worked steadily until 1994 when version 1.0 of the
Linux Kernel was
released. The current full-featured version is 2.4 (released January
2001) and
development continues.

Linux is developed under the GNU (General Public License) and its source
code is freely available to everyone. This however, doesn't mean that Linux and its
assorted distributions are free and developers may charge money for it as long as
source code remains available. Linux may the
a
be used for wide variety of purposes
including networking, software development, and as an end-user platform. Linux is
often considered an excellent, low-cost alternative to other more
expensive operating
systems.
Due to the very nature of Linux's functionality and availability,
it has become quite
popular worldwide and a vast number of software programmers have taken Linux's
source code and adapted it to meet their individual
needs. At this time, there are
dozens of ongoing projects for porting Linux to various hardware configurations and
purposes.
Linux has an official mascot, the Linux Penguin, which was selected by
Linus Torvalds to represent the image he associates with the operating system
he
created. Linux is a reliable, secure operating system. In addition to being cost
effective, it is constantly being updated and refined with the latest technologies. As
Linux gains greater acceptance throughout the computing industry, more and more
companies are supporting Linux via both application and hardware compatibility.

Features of Linux
1)Linux is Network-friendly
Since a team of programmers developed Linux over the Internet, its
networking features were given high priority. Linux is capable of acting as client
and/or server to any of the popular operating systems in use today, and is quite
capable of being used to run Internet Service Providers.
Linux supports most of the major protocols, and quite a few of the minor
ones. Support for Internet, Novell, Windows, and
Appletalk networking have been
part of the Linux kernel for some time now. With, support for Simple
Network
6 Operating Systems

Management Protocol and other services (such as Domain Name Service), Linux is
also well suited to serving large networks.

2) Linux is a Multi-user
Linux is an implementation of the UNIX design philosophy, which means
that it is a multi-user system from the word "go." This has numerous advantages, even
for a system where only one or two people will be using it. Security, which is
necessary for protection of sensitive information, is built into Linux at selectable
levels. More importantly, the system is designed to multi-task. Whether one user is
running several programs or severalusers are running one program, Linux is capable
of managing the traffic.

3) Linux is Open
Linux is open. That means that for the entire base system, which includes
the kernel, the GNU tools, and all the basic utilities, we as programmers and users
have access to the source code as well as the right to modify it.

4) Linux is "Eree"
Linux consumer is free to modify the system and do anything he or she
wishes with it.

Information Management consists of two main modules,


1) File system 2) Device driver

1.4 FILE SYSTEM


The file system allows the user to define files and directories and allocate and
deallocate the disk space to each file. It uses various data structures to achieve this.
For information storage, O/S uses files. That information is stored on files, Files
are mapped by the operating system on to physical devices.
A file is a collection of related information. It can contain programs and data. Data
may be numeric, alphabetic or alphanumeric. File is a sequence of bits, bytes, lines or
records. Each file is having name and extension. (It is dependent on file type)

Block
It is a unit of data, which the operating system defines for the sake of convenience.
Normally operating system also keeps all its data structures in terms of blocks.
Operating system would view the disk as comprising of no. of blocks. From hardware
point of view a disk consists of no. of sectors, but from the point of view of the
operating system, it consists of no. of blocks where cach block is having one or more
sectors. Due to this operating system has to translate a block number into physical
sector numbers.
Operating Systems 7
Disk
It is main secondary device. Various types of secondary devices are there like
floppy disk and hard disk. Hard disk can be considered as being made up multiple
floppy disks put one above the other.

Floppy Disk
Floppy disk is made up of round piece of plastic material coated with a magnetized
recording material. The surface of a floppy disk is made of concentric circles called
tracks. Disk can be considered to be consisting of several surfaces, each of which
consisting of tracks. The tracks are normally numbered from as the outermost track
with the number increase inwards. Each track is divided into a no. of sectors of equal
size. Sector capacities may vary; but typically a sector can store up to 512 bytes.
Read Write
Head
Storage
Media

Hard Disk Mechanism Fig. (1.3) Floppy Disks

Double-sided floppy have two sides on which data can be recorded, so given sector is
specified by acomponents of address, surface no, track no, and sector no.

Hard Disk
Hard disk surface is also made of concentric circles called tracks. Each track is
divided into sectors of equal size. The disk drive for hard disk and its read/write
mechanism is shown in fig. (1.3). Read/ write head for each surface connected to arm.
Arm can move in or out to position itself on any track while disk rotates at a constant
speed e.g.
1) Read ablock
2) It is translated into a sector address surface=1, track=10, sector=5. This is called
target address.
3) Read/write heads current position's address is current address, i.e. Surface =0,
track =7,sector =7.
4) Move the arnm in or out position on correct track. In this e.g. move arm inwards
from track 7 to track10. The time taken to move to correct track is called seek
time.
8 Operating Systems

Track 179
Sector 5 Sector 4
Track 0

Sector 6
Sector 3

AEC2
Sector 7 Sector 2 REC

Case 1

Sector 0 Sector 1
Sector:
1 1 Logical Record:
Many logical records Many sectors

Fig. (1.4a) Tracks and Sectors Fig. (1.4b) Logical records and sectors
5) Wait until desired sector comes under rw head as disk rotates. Time to- reach to.
particular sector on track is called rotational delay or latency.
6) Activate R/W head for appropriate surface and read data. The time taken for this
operation is called transmission time.

Transmisslom
ITime Seek Tme

RW
Head

Rotatlonal Delay

Fig. (1.5) Stages Of /O Operations


File
A collection of related information is termed as file.
For each file created by
the operating system maintains a directory entry also called volume
table of contents
(VTOC) as shown.

File Name

No 0f ProeKSes Hatig hs, le. 0peni


le tUsageLoun
Fie Recordlengthi
FileOwne

VTOC Structure
FILE OPERATIONS
General file operations include create,
read, write, rewind & delete a file.
Operating Systems 9

1)Create a file
For creating a file, first whether sufficient space is available for that file is checked. If
it is available, entry for new file must be made in directory.

2) Write to a file
For writing to file, there is command in which name of the file is given. Then
operating system search for that file in directory entry and write to it.

3) Reading a file
For reading also there is system call in which file name is specified. Then operating
system searches for required file in directory entry and read it.

4) Rewind a file
The directory is secarched for appropriate entry and file is reset to the beginning of
file.

5)Delete a file
To delete a file, again directory entry is searched & if that file is found it releases the
memory space and that directory entry now become invalid.

1.5 ALLOCATION METHODS


For the allocation of disk space to various files, two major philosophies are
there, 1)Contiguous 2) noncontiguous.
In this scheme user estimate maximum file size that the file wil grow to,
considering the future expansion and then requests the operating system to allocate
those blocks at the time of creation of file.
Operating system normally uses block allocation list to manage the disk space.
The list gives the account of all blocks on the disk. It also gives you whether the
block is free or allocated. It is more useful to maintain two different tables:
1) allocated blocks 2) free blocks.
Whenever a new file is created depending upon the size of file operating
system can allocate continuous area. If there are multiple free blocks then which
should be chosen? For that following methods are used?
1) First fit: If suppose file requires 7 blocks; then OS goes through block list and
allocate the entry which blocks equal or more than 7.
2) Best fit: For this method free blocks list is to be sorted by no of free blocks. It
would choose that entry which is the smallest amongst all the entries, which are
equal to or bigger than required one.
3) Worst Fit: It allocates free block that is equal to or larger than our requirement.
The main disadvantage of this method is space wastage & inflexibility. Until file
grows to maximum size, many blocks allocated to the file remain unutilized. So
10 Operating Systens

lot of space is wasted. Again file grows more than predicted maximum it creates a
real problem and next blocks have been allocated to another fiie.
Noncontiguous Allocation:
Considering the problems in contiguous allocation, this method is evolved. In thie
maximum size of file does not have to be predicted at the beginning. The file can
grows with time as per the needs. This reduces wastage space
of and operating system
automatically allocates additional blocks as per requirement without aborting
program. There are two methods for implementing this allocation.

(1) Chained allocation (e.g.MS-DOS)


(2) Indexed allocation (e.g. Unix)

Chained allocation (e.g. MS-DOS)


This isnoncontiguous allocation. So next block is traversed using pointer field, which
gives address of next block in same file.
In DOS, these pointers are kept externally in file allocation table.
In MS-DOS file allocation table is used as shown in fig. (1.6). In this scheme the
block can have 512 or 1024 bytes as shown in fig. there are three files in our system.
File A has been allocated blocks 5,7,3,6,10. File B has been allocated blocks 4,8,11.
File C has been allocated blocks 9,2 and 12. The file directory entries for these three
files have been shown in fig.

Directory
Graphical picture of FAT
FAT Entry
FILE
10
A
Disk
Size FILE
.......5
B..... 4
6
12 FILE
6
8
C....
5 7
6 10
3
11
2
10 EOF
11 EOF
12 EOF
13 Free
14 Free
15 Free
16|Bad Marked as bad blocks by formatting
17 Bad

Fig.(1.6) MS-DOS Chained Allocation


Indexed Allocation
Index of blocks is maintained. It is externalized
list of pointers. Then the file directory
entry should point to the index.
Operating Systems 11

Index is maintained in various ways. For example for a file, list of pointers is as
shown below

Directory Entry
2 File Index Block

4 5 7O
Index Block
8 11
12
4

2
s
1
17 19
20 21 22 23

As shown in figure
1) Index block is 12. It is specified in directory entry.
2) In Index block, all block entries for file are given.

File Organization
The main objective is to see how data is organized for storage and retrieval
purposes. File system manager manages the storing and retrieving scheme. It has full
authority of accessibility and taking decisions.
The main important function of file system manager is to organize or
systemize all the data in order to enhance total system's performance and efficiency.
The type of storing and retrieval scheme is decided by configuration of computer
system. In normal operation, files can be systemized or organized by two ways:
(a) Sequential file organization
(b) Direct file organization
(a) Sequential File Organization
The name suggests, the basic operation of file organization. Sequential means
one after another. The records of files are stored in physical order one after other as
you created. The order is same for writing and reading i.e. you have no choice to
change reading order of records. This scheme is suitable for electromagnetic storing
devices like tapes and so on.

Advantages:
(1) The next record physically resides after the previous one. So separate pointer
is not required to keep the track of records while reading them.
(2) Unidirectional access is provided
12 Operating Systems

(3) This is device independent, so any of devices can be used to organize


sequential files. Automatically, portability enhances.

Disadvantages:
f you want any record, then you must always start from first record. When
desired record is found you can read record. You cannot directly access a particular
record so it is time-consuming scheme. This leads to non-optimal utilization of device
and low access efficiency.

(b) Direct file organization


In order to overcome the main disadvantage of large access time and inefficiency in
sequential file organization the concept of direct file organization is developed. Direct
file organization accesses the records through record's physical addresses, on a direct
access storage device.

Advantages:
(1) Any record in the file can be accessed randomly.
(2) Access time is minimized,

Disadvantages:
(1) As the physical address is to be generated, automatically
processing time
increases.
(2) The mechanical movement of I/O device is more.
(3)Possibility of poorer utilization.
(4) Can not be stored on sequential access devices like (magnetic tapes) i.e. it is not
device independent.

Device Driver
Device drivers are software programs required for each device. Each device
will require different driver for different device as per functionality.
A device driver
knows how the buffers, fags, register control and status bits
should be used for a
particular device. For simply reading a character from a
sequences of device specific operations.
device involves complex
Some device drivers are useful for data conversion.
Devices deal with 8 bit or
16 bit data but computer requires 32-bit/
64-bit data bus. Then device driver enables
this conversion from one form to another.

Terminal I/O
Terminal hardware can be divided into two parts,
for input medium and video screen, the keyboard which is used
which is useful as an output medium.
Combination of these two is termed as
VDU.
Operating Systems 13

Terminals are of two types,


1) Dumb terminal
2) Intelligent terminal.

1) Dumb terminal
It can have a microprocessor inside it and limited memory. It is responsible for
basic input and output of characters. It is called dumb because it does no processing
on the input characters.

2) Intelligent terminal
more powerful hardware
The terminal can do processing on the up. So it requires
and software for it.

Process
Process is a program under execution, which competes for the CPUtime and
a paper. It is compiled but it
other resources. Generally, program exists on a disk or
a program, it
does not compete for CPUtime. But whenever a user wants to execute
willbe loaded in memory. At that time it becomes a process.

1.6 MULTIPROGRAMMING
In earlier days the computer systems were very costly and CPU's idle time
was more. For increasing CPU utilization and for reducing idleness of CPU
run simultaneously.
multiprogramming is used. It means several processes appear to

Degree Of Multiprogramming
called
The no. of processes running simultaneously competing for CPUis
degree of multiprogramming.

Context Switching
In multiprogramming at a time multiple
processes are running simultaneously.
Suppose there are two processes, process and process 2.
1

Then there would be time lost in turning attention from process to process 2.
1

That is called context switching.

Run Run Run Run Run Run


Idle
-1 2 1 2 1 2

Context Switch

Time

Fig. (1.7)
Operating Systems
14

Context means storing the pointers of the memory contents Of process and
ait
procee
CPU registers like PC, IR, Acc., SP and other general purpose registers. Each
one for each process.
has a register save area, which the operating system maintains,
In that area context of a process is saved,.

Register Save Area


ProcessA
PC...R.. ()
SP
ProcessB CPU Registers
PC...R..
|SP

Process A

(ii)
ProcessB

Fig.( 1.8)) Context switching (From Process A to B)

1) Refer fig. (1.8) Process A is running


2) Suppose A requires I/O operations then process B should start. For that context
switching is required. At that time operating system stores the CPU registers for
process A (i in fig) and restores the already saved contents of process B in CPU
registers (ii in fig.).
3) When process A is scheduled again process B registers are stored and registers
for process A are restored in CPUand it continues (iii in fig.) where it had left
from.

Process States
Operating system defines three basic process states as given below.
1) Running:
A process, which is executing is termed as running process. In multiprocessing
there will be many running processes and operating system will have to keep
track of all of them.
2) Ready:
A process, which is not waiting for any external event such as an
said to be in a ready state. I/O operation,
Operating Systems 15
3)Blocked:
Process, which is waiting for an external event such as an I/O operation, it is said
to be in a blocked state.
The major difference between a blocked and a ready process is that a blocked
process can't be directly scheduled even if CPU is free whereas ready process can be
scheduled if CPUis free.

1.7 SCHEDULING
While scheduling various processes there are many objectives for operating system
to choose from. Some of the objectives are listed below.
1) Fairness
2) Good throughput
3) Good CPUutilization
4) Low turn around time
5) Low waiting time
6) Good response time

(1) Fairness:
It refers to being fair to every user in terms of CPUtme it gets.
(2) Throughput:
It refers to the total productive work done by the users put together.
(3) CPU Utilization:
It is the fraction of time the CPUis busy on an average with the user processes or
the operating system. If the time slice is very small, then the context switches will be
more frequent hence CPU will be busy executing O/S instructions rather than those of
user processes. Therefore throughput will be low but CPUutilization will be very
high.
(4) Turnaround Time:
It is the elapsed time between the time a program or job is submitted and the time
when it is completed.
(5) Waiting Time:
It is time job spends waiting in a queue of the newly admitted processes in the
O/S to allocate resources to it before commencing its execution.

1.8 PRIORITY
resources like CPU
When no. of processes are competing for the same available
can be external
and memory, then the concept of priority becomes useful. The priority
or internal.

External Priority
process. If user does not
The user specifies it externally at the time of initiating the
assumes a certain priority called
specify any external priority operating system
18 Operating Systems

allocateda very short period of CPU time one by one. The short period of time durino
which a user gets the attention of CPU is known as a time slice.
The processing speed of system and use of multiprogramming in conjunction
with timesharing allows the CPUto switch from one user station to another and do a
part of each job in the allocated time slice until the job is completed.

1
Main Memory
Terminal
Time-sharing
Supervision User 1
User 1
User 2
User 1
Terminal 2
User 2

User 2

Terminal N User N
User N
User N
Fig. (1.9) Idea of Timesharing
Though it appears several users are using the computer system at the same
time, only one program can be in control of CPU. So all the users will fall in one of
the following three status groups,
1) Active: The user's program currently has control of the CPU.
2) Ready: The user'sprogram is ready-to continue but waiting for turn to get the
attention of CPU.
3)Wait: The user waiting for some IO operation.
Timesharing system reduces CPUidle time. It increases CPU utilization also.

1.12 MEMORY MANAGEMENT


Under this service generally memory allocation, deallocation is done by
operating system. Again free memory is also checked.
For above things to be done variety of memory management systems are
as shown in figure. there

Contiguous, Real Memory Management System


-Single Contiguous, Real Mernory Management System
Fixed Partitioned Memory Management System
Variable Partitioned Memory Management System
• Non - Contiguous, Real Memory Management System
-Paged Memory Management System
Segmented Memory Management Systern
-Combined Memory Management System
• Non- Contiguous, Virtual Memory Management System
-Virtual Memory Management System
Fig. (1.10)
Operating Systems 19

In contiguous scheme program is loaded in contiguous memory locations. But


noncontiguous doesn't require it. The program should be divided into chunk. Chunks
are of same size in paging and different size in segmentation. Again memory can be
real memory or virtual memnory. In real memory full process image is expected to be
loaded in memory while in irtual memory only apart of process image is loaded in
memory. We are focusing above all those terms in detail in this chapter.

Single Contiguous Memory Management


In this scheme of single contiguous memory management physical memory is
divided into two contiguous areas. One of them is permanently allocated to the
resident portion of the operating system (monitor) as shown in fig. (1.8). The
operating system may be loaded at the lower addresses to top as shown in fig. or it
can be loaded at the higher addresses. This choice is normally based on where
vectored interrupt service routines are located as these addresses are determined at the
time of hardware design in computers.

0
O/S
(Monitor)
P
User Process
Area
max.
Fig. (1.11) Single contiguous memory management

At anytime only one user process is in memory. Whenever this process is


completed then the next process is brought into memory.
a) All ready processes are held on disk in an exe form. OS holds their PCBS in
memory according to their priority.
b) Only one process runs in memory.
c) When that process is blocked, it is swapped out from memory to disk.
Next priority prOcess swapped in the main memory from disk and it starts
running.
This scheme has very fast access time but use is limited, as it is not having multi
user facility.

Partitions
Generally main memory is divided into various sections called partitions. In
this scheme two types of partitions are available ) Fixed partitions II) Variable
partitions.

Fixed Partitions
In this scheme partitions could be of different sizes. Once decided at the time
of system generation they could not be changed.
20 Operating Systems

System generation is the process of tailoring the operating system. It consists


of nuimber of routines for supporting a variety of hardware items and devices
According to devices used the device routines are selected at the time of system
generation:

PO
OK Partition
100K Partition ID Starting
Size Status
P1 Address
300K 100 ALLC
P2ProOcess A
100 200 FREE
400K
2 300 100 ALLC
P3Process B

3 400 400 ALLC


800K
P4 4 800 100 FREE
900K
Fig. (1.12) Fixed Partitions and its table

If you want to change partition, operations should be stopped and operating


system has to be reloaded with different partition specification. Whenever partitions
are declared operating system creates a partition description table (PDT) for future
use as shown in fig. Irnitially all the entries are marked as free. When a process is
loaded into the partition, that partition is marked as ALLOCATED efer fig.(1.12).
Drawback of this scheme is fragmentation.

Internal Fragmentation
If a partition is of 100K and has to be allocated to a process of 8OK; then 20K
memory is wasted. This is called internal fragmentation.

External fragmentation
•If two free partitions of 30K and 50K are available and a process of 60K has
to be accommodated. Then both the partitions can't be allocated in this process. So
there is wastage of memory space. This is called external fragmentation.
Time complexity is very low because allocation/ de-allocation routines are
simple as the partitions are fixed. Access time is not very high.

Variable Partitions
Due to some drawbacks of static partitions like fragmentation and restriction
on no. of resident processes, (which affects
degree of multiprogramming and so CPU
utilization also.) variable partitions come into existence. In variable
partitions no ol
partitions and their sizes are variable.
At any time any partition
process. But in this scheme
of memnory can be either free or allocated to som
starting address of any partition is varying.
Operating Systems 21

Refer fig. (1.13) the scheme working is as follows;


1)Operating system is loaded in memory; all the rest of memory is free.
2) Program Pl is loaded in the memory and it starts executing.
3) Program P2 is loaded in the memory and it starts executing.
4) Program P3 is loaded in the menory and it starts executing.

O/S O/S O/S O/S O/S O/S O/S O/S


P1 P1 P1 P4 P4 P4

P2 P2 P2 P2 P1

P3 P3 P3 P3 P3
P5
() (i) (ii) (iv) (v) (vi) (vi) (vi)
Fig (1.13): Memory allocation changes with 8 events
5) P1 is blockéd. After a while P4 wants to occupy the memory. The existing free
space is less than the size of P4. Assume that P4 is smaller than, P1 but bigger than
free area available at the bottom. So P1 is swapped out and two chunks of free
space in memory.
6) P4 is loaded and it starts executing. P4 is loaded in the same space available as
P4<P1
7) P2 terminates. Only P4 and P3 continue. The free area at the top and the one
released by P2 can be joine.
8) P1 is swapped out. Also free space in middle is sufficient to hold Pl. Another
process P5 is loaded in the memory.
Thus it starts with two partitions and at stage 8 there are 6 partitions. These
partitions are created by the operating systems at run time and they iffer in sizes.
This scheme wastes less memory than the fixed partitions because there is no
internal fragmentation.
Time complexity is certainly higher than fixed, due to various data structures and
algorithms used in this method.

1.13 NON-CONTIGUOUS ALLOCATION


In various contiguous memory allocation schemes a problem of fragmentation
arises, so non-contiguous allocation provides a better method to solve these problems.
For that following various nethods are used.

1) Paging
In paging the chunks of memory are of same size. The logical or virtual address
space of program is divided into equal size pages and physical main memory is
divided into equal sized page frames. The size of page is the same as that of a page
frame, so that a page can exactly fit into page frame. Therefore it can be assigned to
a

any page frame, which is free.


22 Operating Systems

The addresses which program refers are called virtual or logical addresses, In
reality the program may be loaded at different memory locations are called physical
addresses.
In this scheme generally virtual addresses consist of twO parameters, a logical or
virtual page no., and displacement D within the page. During execution addres
translation has to be done i.e. Virtual page no. should be converted into physical pace
no.
(F.D)---- --P.D)

Physical logical page no.


page frame no.
Page 0

2
Page 1
Fhysical frames
3
4 Memory
2 5 5 Page 2
Page 3
Logical Memory Page 7
pages table
2) Segmentation
Segmentation is similar to paging. Pages are physical in nature and hence are
of fixed
size but segments are logical division of a program so, of variable size.
Each program in its exe form can be considered to be consisting
segments, code, data and stack. Each of these can be divided of major
into further segments.
Generally each program has a main function and few subprograms.
use various functions also. A program can
The fig.(1.14) shows various segments along with their
sizes. Each segment is compiled with respect to 0; as
the starting address for that
segment.
0
SQRT
Main Routine
Program Segment 1
Segment o 699 Segment
0 Number Size
999 1000
Data Area 1
Segment 3 700
2 800
Sub 899 3 900
Program 4 500
|Segment 2 Total 3900
Stack Area
Segment 4
799 Fig. (1.14) Segmentation
499
Operating Systems 23

1.14 VIRTUAL MEMORY


Virtual memory systems can be implemented using paging, segmentation or
combined schemes. The Process can start executing with only part of the process
image in the memory. In real memory systems entire process image has to be in
memory. Actually this scheme is simple, as whole process has to be swapped in or
out. But if the physical memory is limited, then the no. of processes it can hold at any
time becomes limited. So virtual memory systems are implemented. The idea is when
a page not currently in memory is referenced then only that page can be brought in to
the memory.
If there is no page frame free in the physical memory for new page then O/S
has to overwrite an existing page in physical memory. Which page should be
overwritten is decided by page replacement policy. There are some terms related to
virtual memory system are as follows

Locality of reference
This gives some basis to forecast whether a page is likely to be referenced in
the near future based on its passed behavior and hence also whethèr you could throw
that page out to make room for a new one. Clustering of
page references in a certain
time zone is called the principle of locality of reference.

Page Fault
When a process is executing with only a few pages in memory, and when
an
instruction is encountered which refers to any instruction or data in some other page,
which is outside the memory, a page fault occurs.

Working Set
At any time a process has a no. of pages in the physical memory. The set of
pages in the physical memory actively referred to at any moment is called working
set.

Page Replacement Policy


As no. of processes and no. of pages in main memory for each process
increase; at some point of time, all the page frames become occupied. At this timne, if
a new page is to be brought, in, the O/S has to overwrite some existing page in
memory. The page to be replaced is selected by page replacement policy. O/S
designer chooses these type of policy.

Dirty Page
Before overwriting a page in the memory the operating system has to check if
that page has been modified after it was loaded from the disk. If that page is modified,
it becomes a dirty page. The operating system maintains one bit for each physical
page frame for checking whether a page is dirty or not. This bit is called dirty bit.
Operating Systems
24

Demand paging
In demand paging a page is brought in only when
demanded.

1.15 BASICS OF GUI


Poor human computer interface has always been a, problem area in usine
computers. In the past computers were not very powerful. Cryptic commande
provided an interface to the computers operating system.
The users were expected to remember these commands and what they stood
for. All the users would not be computer literates unless they knew the cryptic human
- computer interface. The interface had to become more users friendly. Cryptic
commands were converted into graphical representation. Such an interface is called
graphical user interface or GUI.

Windows operating system is GUI based operating system. The screen can be
split into different partitions. Each partition can be of different size. This partition is
called window and hence called windowing technology.
Some of the characteristics of a window are its title, borders, work area and
Command area.

Components of a Window
Menu bars normally appear at the top of window under window title. When
menu option is selected a pull down menu appears on
the screen. A pull down menu
willhave an action on the left side and keyboard accelerates combination on the right.

Title Bar Aprogram accepls Roll Noand name Microsoft


InterneExplorerTXk -Close Button
Menu Bar HEile Edi View Favortes Iools Help
Maximize/Restore
Tool Bar Slop Rrt HoySvadAFrveyHioy MPi -Minimize Button
|AddresseclNn
Control Box toiLnks
Upscroll Button

Send Vertical Sllder

Down Scroll Button

Status Bar

Fig. (1.15) Typical Window


Structure
Operating Systems 25
Scroll bars
A scroll bar consists of a horizontal or vertical scroll area with a slider bOx
and an arrow in a box at each end. They are used to look at information, which is not
currently visible in a window.
Title bar
It helps to identify each window separately. It displays generally programs
name in title bar.
Every Window is having minimize, maximize, restore button.
Minimize
This is used to minimize program window; but program is not closed, it goes
to bottom line.
Maximize/restore
It is used for making window full screen. Then this button becomes restore
button. When you click this button, window comes to its previous size.
Close It is used for closing window.
Dragging Window
For changing the position of window on screen dragging is used. For that
select a window by clicking it. Press left mouse button. Keeping in that way move
mouse pointer to new position on screen. Then release mouse button, now window
appears at new position.
Resizing Window
Changing the size of window is called resizing.For resizing move the pointer
on to the border of window. Now mouse pointer shape changes to double arrow, press
left mouse button and move the pointer to left or right (according to border whether
left or right.) and release button. Now the window size is changed.

1.16 ACCESS AND SECURITY ASPECT OF O/S


In general security systems will control through use of specific security
features, access to information that only properly authorized individuals or processes
operating on their behalf will have access to read, write, create or delete.
OSIdefines elements of security in the following terms:
1) Confidentiality: Information is not accessed in an unauthorized manner. (Read)
2) Integrity: Information is not deleted in unauthorized manner. (Write)
3) Availability: Information is available to authorized users at right time.

Security
Ability of O/S to control storage and transportation of data in and between the
objects O/S supports is security. In multi-user environment concepts of security are
very important.
Security Threats
1) Due to networking the user has to access data and programs at different locations.
This has increased the threat to the security of computing.
2) Sharing increases security threats.
OperatingSystems
26

Major Threats
1) Unauthorized use of service (tapping)
2) Unauthorized disclosure of information (disclosure)
3) Unauthorized alteration and deletion of information
(amendment)
4) Unauthorized fabrication of information.
5) Denial of service to authorized users.

A B A B

Tapping/ Disclosure Amendment Fabrication Denial


Fig. (1.16)

Tapping and disclosure are passive threats and remaining are active threats.

Attacks on security
Security can be attacked in following ways.
1) Authorization
It means verification of access to the system resources.
1) Intruder may guess or steal password and use it.
2) Intruder may use vendor-supplied password, which
is expected to use by
system administrator.
3) Intruder may find password by trial and error method.
4) If user logs on and go for a break then intruder may use
5) An intruder can write a dummy login program
terminal.
to fool user and that program
collects information for its use later on.

2) Browsing
Files are very permissive so one can easily
may access database and browse system files. Due to that 1t
confidential information can be read.
3) Trap doors
Sometimes software designers want
For that there are some secret entry tomodify their programs after installation.
points which programmers keep and
require any permission. These are it does no
called trap doors. Intruders can use
doors. these trap

4) Invalid Parameters
Due to invalid parameters some
security violation can take
place.
Operating Systems 27

5) Line Tapping
Tappings in communication line can access/modify confidential data.

6) Electronic Data Capture


Using wire taps or mechanism to pick up screen radiation and recognize what is
displayed on screen is termed as electronic data capture.

7) Lost Line
In networking, line may get lost. In such case some O/S log out and allow access
only after correct identify of user. Some O/S cannot do this. So process wilI be
floating and allow intruder to access data.
8) Improper Access Controls
Someadministrator may not plan about all rights. So some users may have more
access and some users have very less access.
9) Waste Recovery
If block is deleted its information will be as it is, until it is allocated to another
file. Intruder may use some mechanism to scan these blocks.

10) Rogue Software


Programs are written to create mischief. Some of the programs under this are as
follows:
a) Trojan Horse: These programs seem to be harmless but actually harmful.
b) Chameleon: It is similar to Trojan horse. It is a mimic logon program to
collect allvalid usernames and passwords ona system.
c) Ordinary Software Bomb:It explodes as soon as it is executed.
d) Timed S/W Bomb: It becomes active only at a specific time.
e) Logical S/W Bomb: It is activated only if logical condition is satisfied.
f) Worms: Programs attacking on node and spreading on other nodes.
g) Virus: It gets attacked to other programs to cause damage.
h) Rabbits: They are like worms. They replicate as soon as they execute.

1.17 COMPUTER WORM


A computer worm is a full program by itself. It is written in such a way that it
spreads to other computers over a network and it also consumes all resources of
network. It was invented by research scientists at XEROX PARC research center.
Internet Worm was introduced on November 2, 1998 into Internet by Robert Morris.

Safeguards against worms


a) Prevent its creation: This is achieved by strong security and protection
policies.
b) Prevent it's spreading: Before transferring any file on a network, user should
be forced to sanction transfer.
28 Operating Systems

1.18 COMPUTER VIRUS


It iswritten with a clear intention of infecting other programs. It is a part of 2
program, which normally piggybacks on a valid program. But it is not a complete
program by itself.

Types of viruses
There are several types of computer virus as follows:
a) Boot sector virus
b) Memory resident virus
c) File virus
d) Command processor virus
e) General purpose virus
Generally classification is done based on what is affected or where the virus
resides.

Infection methods
a) Append: In this method viral code appends itself to the unaffected
program.
b) Replace: In this method viral code replaces original executable program
completely or partially.
c) Insert: In this method the viral code is inserted in the body of an
executable code to carry out some funny actions.
d) Delete: In this case viral code deletes some codes from executable
program.
e) Redirect: In this case the normal control flow of a program is changed to
execute some other code.

Modes of operation
Virus works in number of ways. Generally developer of virus produces any
interesting or useful program such as a game or utility. But his program has viral code
embedded in it. Generally this program is developed under DOs. Then it is
distributed to people.

Virus detection
Normally virus detection program checks integrity of binary files. It maintains
a checksum on each file. At regular frequency
detection program calculates checksum
and matches with original one. If there is mismatch then that program may be
infected.

Virus removal
There are some viruses whose bit pattern in the code can be predicted. The
virus removal program Scans the disk for the patterns of known viruses and O1
detection it removes them.
Operating Systems 29

Virus prevention
For prevention of virus always buy legal copies. of software. Again take
frequent backups of data and run monitor programs frequently to detect virus.

Difference between Computer Virus and Computer Worm


Computer Virus Computer Worm
1) It is not a complete program by 1) It is a complete program.
itself.
2) Viruses cause direct 1harm to the 2) Worm generally consumes system
system by corrupting codes as well. resources.
as data.
3) It cannot operate indepeidently 3) It operates independently.

QUESTIONS
1. Select the correct alternative
terminal does no processing on input characters.
(a) Intelligent (b)Dumb (c) RS232. (d) None of these

(ii) The time required for read write head to move to correct track is (Mar.09).
(a) Latency time (b) Rotational delay (c) Seek time (d) None of these
(iii) Terminate a process' is the system call available in management.
(a) process (b) memory (c) information (d) file
(iv) Linux is type of software. (March 2020)
(a) Public (b) Free (c) Shareware (d) Licence

(v) Operating system is a (March 2003)

a) Hardware, b) Software, c) Input device, d) Output device

(vi) is not an operating system. (March 2004)


a) UNIX b) LINUX )MS-DOS d) C++
(vii) are thé operating system programs. (March 2005)
a) Application programs b)Users programs

c) Process management programs d) Antivirus programs

(viii) is an operating system. (March 2007,2016)


a)c+ b) C c) VB d) LINUX

(ix) Terminate a Process is the system call available in (March 2008)


a) Process b) Memory c) Information d) File
30 Operating Systems

(x)Data is instantly updated in case of - -operating system. (Mar.2010)


a) Batch Processing b)Multi Processing c) Multi user d) Real time
(xi) Context Switching is a term related to management. (March 2016)
a) Process b) Memory c) Information d) device
(xii) the time lost in turning the attention of processor from one process to another
is called as (March 2017)
a) circuit switching b) bandwidth c)context switching d) bracket switching

2. What is Operating system? Explain major services of OS. (March 2009,2020)


3. What are the features of Windows NT operating system? (March 2016,17)
4. Explain in brief the following programs of MS-Window. (March 2003,07,09)
a) Program manager, b) File manager, c) Control panel
5. What are the components of LINUX operating system? Explain any three features
of it. (March2004,2019)
6. With reference to process management explain the terms: (March 2003)
a) External priority, b) Purchase priority, c) Internal priority, d) Time slice
7. Explain the three main functions performed by a memory management module of
an operating system. State any four-memory management systems.(Mar.03,17)

8. Which are three major areas in which the operating system divides its services.
Give examples. (March 2002,08)
9. What is virtual memory? Explain following terms with respect to virtual memory.
a) Page fault b)Dirty bit
10. Explain context switching at process level in multiprogramming system with
example. (March 2002)
11. What objectives are considered while scheduling
processes?Explain.
12. State the various steps involved in allocation of a partition in case
of fixed
partition memory management. (March 2002)
13. What is GUI? Explain components of GUL. (March 2004,05)
14. Explain the following with respect to
GUI: (March 2007)
i) Scroll bar i) Title bar iii) Minimize
15. Explain in short the function
of menu bar and scroll bar components of GUL.
(March 2002, 08)
Operating Systems 31
16. What is GUI? Write any two features of GUI. (Mar.2005)
17.What is VDU? Explain the following terms.
a) Dumb terminal b) Intelligent terminal (March 2002)
18.What is virus? State the various types of virus and the basis in which they are
classified. (March 2002)
19. What is Computer Virus? State any four methods by which a virus can infect
other programs. (March2005,06,17,20)
20.What is computer worm? Explain its mode of operation. (March 2003)
21.. Differentiate between the following. (March2004)
a)Computer worm and computer virus (March2009)
b) Fixed partition and variable partition.
22. Explain the following terms a) Multiprocessing b) Degree of multiprogramming
23. Explain the difference between contiguous and non-contiguous allocation.
24.Explain the single contiguous and fixed partitioned memory management systems
with a suitable memory mapping diagram. (March2005.10)
25.State the various steps involved in allocation of a partition in case of fixed
partition memory management. (March2006)
26. Explain the concept of virtual Memory. Explain any three terms used in virtual
memory. (March 2004)
27. Explain the file system related to Information Management with file operations
only. (March 2007)
28. What are the different functions performed by Memory Management in operating
system? Draw a memory map of a single user computer. Explain types of
partitioning in brief. (March 2004)
29. What is meant by a System Call? How it is used? How does an Application
program (AP) use these calls during execution? (March 2006)
30. Explain the following terms in case of magnetic disk: (March 2006,10)
i) Tracks and Sectors ii) Seek Time
iii) Transmission Time iv) Latency /Rotational Delay
31. Explain virus detection,removal and prevention (March 2016)
Answers Q. (1)
i) Dumb ii) Seek ii) Process
iv)Free v)software vi)C++ vii) Process management programs
vii) LINUX ix) Process. x)Real time xi)process xi) context switching
2
DATA STRUCTURES
INTRODUCTION
Everyone knows, what is program? One of the tools for writing the programs
is High Level Language. Almost all high level languages provide the facility of built.
in data structures. Often, we use these tools without concern about their actual
implementation, such as a welder can use a welding machine without knowing much
about electricity. However, built-in data structures provide limited applications. So in
order to get number of interesting and useful ways of structuring data, programmer
must build various data structures in his program. In this chapter, we will study some
useful data structures.
In order to store and retrieve individual data items, the accessing function are
defined. Due to these functions, the collected data is organized.ves i
For implementation of any data structure we should know:
(a) How much memory space is required
(b) How to access data by coded functions
Data is simply a set of values. Generally collection of data is organized ino
hierarchy of fields, records, and files.
e-g. If you consider student's information as follows:

.
Name RollNo. Physics Chemistry Maths
Sachin 1 91 90 92
In above e.g. name, roll no., physics, chemistry and maths are fields. The
collection of actual values of fields forms a record. The collection of such type of
records forms a file.

Primary Key
A certain field may yniquely determine the record in a file. Such a field is
called primary key. In the above example Roll.No. is a primary key.
The above organization of data into fields, records, files may not be complex
enough to maintain and efficiently process certain collections of data. For this reason
data is organized into more complex type of structures.

2.1 DATA STRUCTURE


The logical or mathematical model of a particular organization of data is
called data structure.
The choice of data model depends on two considerations,
1) It must be rich enough in structure to mirror the
actual relationships of the
data in real world.
Data Structures 33

2) Structure should be simple enough that can effectively process the data
whenever necessary.
Few examples of data structures are array, list, binary tree etc.

DataStructure Operations
The data in data structures are processed by certain operations like:
1)Traversing: For processing certain item in record, each record is accessed
exactly once. (Visiting a record)
2)Searching: Finding lovation of a record with given key value or finding the
locations of all records, which satisfy one or more conditions.
3)Inserting: Adding a new record to the structure.
4)Deleting: Removing a record from a structure.
5)Sorting: Arranging the records in some order.
a
6)Merging: Combining the records in two different sorted files into single
Sorted file.

2.2 ALGORITHMIC NOTATIONS


An algorithm is a finite step-by-step list of well-defined instructions for
an algorithm
solving a particular problenm. The form for formal representation of
consists of two parts, occur in
1) It tells the purpose of algorithm, identification variables, which
algorithmn and lists, input data.
2) It contains list of steps that is to be executed.
There are certain conventions, which has to be followed in algorithms.

i) Step, control, exit


The steps of algorithm are executed one after another beginning with stepl.
Sometimes control may be transferred to step 'n' of algorithm by statement
goto step n'or using control structures.
The algorithm is completed with the statement 'Exit'.

Comments
ii)
It is given in brackets either at beginning
or end of step. It indicates the main
purpose of step.

ii) Variables as
Variable names are generally given in capital letters. Also variables used
counters or subscripts are in capitals.
Assignment Statement
It uses:=
notation
e.g. MAX: =5
Where MAX is a variable
Data Structur
34

iv) Input / Output


For input read statement is used
Read: Variable name
For output write/ print statement is used.
Write: Messages/Variable names

Procedure used
It is used for independent algorithm modules. The term procedure will be
to describe a certain type of sub algorithm.

Example of algorithm
An algorithm to find largest element in array
A nonempty array DATA with numerical values is given. This
algorithm finds
variable
the location LOCand the value MAX of the largest element of DATA. The
K is used as a counter.
Step 1[Initialize] Set K: =1, LOC:=1and
MAX: = DATA [1]
Step 2 [[ncrement Counter] Set K: = K+1
Step 3 [Test Counter] If K>N then:

Write LOC, MAX and Exit


Step 4 [Compare and Update]
If MAX DATA [K], then:
Set LOC: =K and MAX: = DATA [K]
Step 5 [Repeat loop] Goto Step 2

Control Structures
Generally three types of logic are used in algorithms that are as follows,
1) Sequence Logic 2) Selection Logic 3) Iteration Logic

1) Sequence Logic
Generally modules are executed insome sequence. The sequence is represented
by means of numbered steps. Generally flow pattern is as follows,

Flowchart
Algorithm Module A

Module A Module B

Module B
Module C Module C

Fig. (2.1) Sequence Logic8


Data Structures 35
2) Selection Logic
This logic employs a number of conditions. Accordingly which condition is
satisfied that module is executed. Generally the following statement gives end of
such a structure.
[End of IF Structure]
These structures are of three types
Single Alternative
This structure has the form
IF condition, then:
[Module A]
[End of F Structüre]

No
Condition

Yes
Module A

Fig. (2.2) Single Alternative

If condition hoids true then Module A is executed, otherwise Module A is


skipped and control transfers to the next step of algorithm.

Double Alternative
This structure has following form
IF condition, then:
[Module A]
Else:
[Module B]
[End of IF Structure]

No
Condition

Yes

Module A Module B

Fig. (2.3) Double Alternative


36 Data Structu

I£ condition is true Module A is executed and if condition is false Module R i


executed.

Multiple Alternatives
If condition [1] then:
[Module A1]
Else if condition [2] then:
[Module A2]

Else if condition [M] then:


Module AM)
Else:
[Module B]
[End of if structure]

Example of Selection Logic;


Algorithm
This algorithm inputs the coefficients A, B, C of a quadratic equation and
outputs real solutions if any,
Step 1: Read: A, B, C
Step 2 : Set D: = B'-4 AC
:
Step 3 If D>0, then:
a) Set X1: = [-B +D]/2A
and X2: = [-B-VD]/2A
Else if D=0, then:
a) Set X: = -B /2A
b) Write: "UNIQUE SOLUTION'
Else:
Write 'NO REAL SOLUTIONS'
[End of IF Structurel
Step 4: Exit

3) Iteration Logic
Generally these types of structures are called loops. In that two types
of loops are
there, 1) Repeat for, 2) Repeat while
...
1) Repeat for
Form
Repeat for K=R to S by T
[Module]
[End of loop]
Data Structures 37

Where K= Index variable


R= Initial value of K
S= Final value ofK

T= Step (increment/decrement)
*The loop is executed for all values of K starting from R to S with step of T.

R
|K
No
Condition
Is Yes
K>S Yes
No
Module
Module

K=K+T

Fig.(2.4) Repeat
... For Logic Fig.(2.5) Repeat. While Logic
...
2) Repeat while
It uses a condition to control the loop.

Form
Repeat while condition:
[Module]
[End of loop]

The loop continues till a condition is true. There must be initialization


statement and there must be a statement that will change index variable in loop.
Algorithm using Repeat while loop (To find largest element in array.)
Given a nonempty array DATA with N numerical values. This algorithm finds
the location LOC and the value MAX of the largest element of DATA.
1 [Initialize] Set K: =1, LOC: =1
and MAX: = DATA [1]
2 Repeat steps 3 and 4 while K<= N
3 If MAX<DATA[K] then:
Set LOC: = K and MAX: = DATA [K]
[End of If Structure]
4 =
Set K: K+1
[End of step 2_loop]
5 Write: LOC, MAX
6 Exit
40 Data Structu

Algorithm for inserting element into a linear array


INSERT [LA, N, K, ITEM]
LA = Linear array
N=Total no. of elements in the array
K= Any positive integer, K<=N
This algorithm inserts an element ITEM into the K" position in LA.
1. [Initialize Counter] Set J: = N
2. Repeat steps 3 and 4 while J K
3. [Move Jh element downward] Set LA [J+1]:=LA [J]
4. [Decrease Counter] Set J: = J-1
[End of step 2 loop!
5. [Insert element] Set LA [K]: = ITEM
6. [Reset N] Set N: = N+1
7. Exit
Number 9 is inserted 4 is deleted
3 3 3
4 4
5 5
6 5 6
8 8

Original Addition of Deletion of


Array element in element from
middle array array
Fig. (2.6)
Deleting Element in array
It refers to the operation of removing one of the elements from A. Deleting at
an end of array is simple but deleting an element somewhere in the middle of the
array would require that each subsequent elenment be moved one
location upward in
order to fillup the array.

Algorithm for deleting an element


This algorithm deletes the K" element from a linear array LA and assigns it to
a variable ITEM.
DELETE (LA, N, K, ITEM]
LA = Linear array N=Total no. of elements in array
K= Any positive integer such that K<=N
1. Set ITEM: =LA [K]
2. Repeat for J: =K to N-1
Data Structures 41
3. [Move J+1" element upward.] Set LA [J]: =LA (J+1]
[End of loop]
4. [Reset the number N of elements in LA.]
Set N:
=N-1
5. Exit

2.4 BUBBLE SORTING


Sorting means, rearranging the elements in increasing or decreasing ordér.
Suppose A[1], A(2],.... A[n] are in memory. Then bubble sort algorithm works as
follows:
Compare A [1] and A [2] and arrange them in the desired order, so that A [1],
A[2]. Then compare A [2] and A [3] and arrange them so thatA [2], [3]. Continue
A

this process until we compare so


A [N-1] with A [N] that A [N-1], A [N].

Step 1: It involves n-1 comparisons. During this step, the largest element is coming
like a bubble to the n" position. When step 1 is completed A[N]will contain the
largest element.

Step 2: Repeat step 1


with one less comparison. Step 2 involves n-2 comparisons,
when step 2 is comnpleted we get second largest element A[N-2].

Step 3: Repeat step 1


with two less comparisons. It involves N-3 comparison.

Step N-1: Compare A[1]with A[2] and arrange them so that A[1].[A(2].
After n-l steps the list will be sorted in increasing order.
Pass
The process of sequentially traversing through all or part of a list is called a
pass. Each of above step is actually a pass. The bubble sort algorithm requires N-1
passes where n is number of input items.
The time required for sorting algorithm is measured in terms of comparisons.
Specifically there are n-1 comparisons during first pass n-2 comparisons in second
pass and so on.
Complexity of algorithm
f(n) = (n-1)+ (n-2)+....+2 +1
n(n-1)
2
n'
O(n)
=T+
= o(n')
The time required to execute bubble sort algorithm is proportional to n' where
n is number of input items.
Data Structures 41
3. [Move J+1" element upward.] Set LA J]: = LA [J+1
[End of loop]
4. [Reset the number N of elements in LA.]
Set N: =N-1
5. Exit

2.4BUBBLE SORTING
Sorting means, rearranging the elements in increasing or decreasing order.
Suppose A[1], A[2],.... A[n] are in memory. Then bubble sort algorithm works as
follows:
Compare A [1] and A [2]and arrange them in the desired order, so that A [1],
A[2]. Then compare A [2] and A [3] and arrange them so that A [2], [3]. Continue
A

this process until we compare A [N-1] with A [N] so that A [N-1], A [NJ.

Step 1: It involves n-1 comparisons. During this step, the largest element is coming
like a bubble to the n" position. When step 1 is completed A[N] will contain the
largest element.

Step 2: Repeat step 1 with one less comparison. Step 2 involves n-2 comparisons,
when step 2 is completed we get second largest element A[N-2.

Step 3: Repeat step 1 with two less comparisons. It involves N-3 comparison.

Step N-1: Compare A[1] with A[2] and arrange them so that A[1].[A[2].
After n-1 steps the list will be sorted in increasing order.
Pass
a
The process of sequentially traversing through all or part of a list is called
pass. Each of above step is actually a pass. The bubble sort algorithm requires N-1
passes where n is number of input items.
The time required for sorting algorithm is measured in terms of comparisons.
Specifically there are n-1 comparisons during first pass n-2 comparisons in second
pass and so on.
Complexity of algorithm ....
f(n) = (n-1) + (n-2) + +2 + 1
n(n-1)
2
n
O(n)
=7+
= o(n')
n
to
The time required to execute bubble sort algorithm is proportional where
n is number of input items.
42 Data Structure

Algorithm
[Bubble Sort] BUBBLE DATA, N]
Here DATA s an array with N elements. This algorithm sorts the elements in
DATA.
1. Repeat steps 2 and 3 forK=lto N-1
2. Set PTR: = 1 [? pass pointer PTR.]
3. Repeat while PTR<= N-K. [Executes pass.]
a) IF DATA (PTR] > DATA PTR + 1], then:
Interchange DATA [PTR] and DATA (PTR + 1]
[End of IF structure]
b) Set PTR: = PTR + 1
[End of inner loop.]
[End of step 1 outer loop.]
4. Exit
Searching
Searching refers to the operation of finding the location of given element in
the list. The most commonly used searching algorithms are linear search and binary
search.
In linear search the given element is compared with each element of list one
by one. This method is also called seguential search.

Algorithm Linear Search


LINEAR [DATA,N, ITEM, LOC]
Here DATA is linear array with N elements and ITEM is a given item of
a
information. This algorithm finds the location LOC of ITEM in DATA or sets
LOC: = 0, if search is unsuccessful.
1. [Insert ITEM at the end of DATA] set DATA [N+1]: = ITEM
2. [Initialize counter] set LOC: =1.
3. [Search for ITEM)
Repeat while DATA (LOC]# ITEM
LOC: =LOC+1.
Set
(End of loop]
4. [Successful?] IF LOC = N+1 then set LOC; = 0
5. Exit

2.5 BINARY SEARCH


While using this searching method array should be sorted in increasing
numerical order.
Suppose DATA is an array, which is sorted in increasing numerical
we want to find out the location order, and
a
LOCof given ITEM of information in DATA.
Then binary search algorithm applied works as follows.
During each search
for ITEM is reduced to a segment of elements data:
of
DATA (BEG], DATA (BEG +1], DATA
BEG+2],.. DATA[END]l
Data Structures 43

Here BEG and END variables denoted beginning and end locations of the
seoment under consideration. This algorithm comnpares ITEM with middle element
DATA MID] of the segment where MID is obtained by
MID = NT [(BEG+ END)/2]
If DATA [MID] = ITEM then the search is successful and we set LOC: =
MID otherwise a new segnent of DATA is obtained as follows,
a) If ITEM<DATA [MID] then item can appear in left half of the segment.
DATA [BEG], DATA [BEG +1],... DATA [MID-1]
So we reset END: =MID-l and begin searching again
b) If ITEM > DATA MID]then ITEM can appear only in the right half of
the segment.
DATA [MID+1], DATA [MID+2],...DATA END]
So we reset BEG: = MID+l and begin searching again.
c) If ITEM is not in DATA then eventually we obtain END < BEG

It means that search is unsuccessful. In this case we assign LOC: =NLL


(Generally we begin with BEG=1 and END=N or more generally we can say
BIG=LB and END=UB)

Algorithm for Binary Search


(Binary Search) BINARY [DATA, LB, UB, ITEM, LOC]
Here DATA is sorted array with lower bound LB and upper bound UB and
ITEM is given item of information. The variables BEG, END and MID denote
respectively the beginning, end and middle location of a segment of elements of
DATA, This algorithm finds the location LOC of ITEM in DATA or set
LOC=NULL.
1. [Initialize segment variables.]
Set BEG: = LB, END: = UB and MID=INT [(BEG+END)/2]
2. Repeat steps 3 and 4 while BEG <= END and DATA (MID] ÷ ITEM
3. IF ITEM < DATA [MID], then:
Set END: = MID-1
Else:
Set BEG: = MID+1
[End of IF structure]
Set MID: =INT (BEG+END))2]
[End of step 2 loop]
IF data [MID] = ITEM, then:
Set LOC: =MID
Else:
Set LOC: =NULL
[End of IF structure]
4. Exit
Data Structures 43
Here BEG and END variables denoted beginning and end locations
of the
segment under consideration. This algorithm compares ITEM with middle
element
DATA MID] of the segment where MID is obtained by
MID = INT [(BEG + END)/2]
If DATA MID] = ITEM then the search is successful and we set LOC: =
MID otherwise a new segment of DATA is obtained as follows,
a) If ITEM<DATA [MID]then item can appear in left half of the segment.
DATA BEG], DATA (BEG +1],..... DATA [MID-1]
So we reset END: =MID-1l and begin searching again
b) If ITEM > DATA [MID] then ITEM can appear only in the right hall of
the segment.
DATA MID+1], DATA (MID+2],....DATA [END]
Sowe reset BEG:= MID+1 and begin searching again.
c) If ITEM is not in DATA then eventually we obtain END< BEG

It means that search is unsuccessful. In this case we assign LOC: = NULL


(Generally we begin with BEG=l and END=N or more generally we can say
BIG=LB and END=UB)

Algorithm for Binary Search


(Binary Search) BINARY DATA, LB, UB, ITEM, LOC]
Here DATA is sorted array with lower bound LB and upper bound UB and
ITEM is given item of information. The variables BEG, END and MID denote
respectively the beginning, end and middle location of a segment of elements of
DATA. This algorithm finds the location LOC of ITEM in DATA or set
LOC=NULL.
1. [Initialize segment variables.]
Set BEG:= LB, END: = UB and MID=INT [(BEG+END)/2]
2. Repeat steps 3 and 4 while BEG <= END and DATA [MID] #ITEM
3. IF ITEM < DATA [MID], then:
Set END: = MID-1
Else:
Set BEG: = MID+1
[End of IF structure]
Set MID: =INT (BEG+END)/2]
[End of step 2 loop]
IF data MID] = ITEM, then:
Set LOC: =MID
Else:
Set LOC: =NULL
[End of IF structure]
4. Exit
44 Data Structu

Complexity of Binary Search Algorithm


The complexity is measured by the number of f (n) of comparisons to lo¢ate
ITEM in DATA where DATA contains n elements. Each comparison
reduces sample
size in half. So we require at most to
f (n) comparisons locate ITEM where
=
f (n) [log, n]+1
Applications:
(1) This algorithm is used to search ordered array.
(2) To find out the target element whether it is present or not. If present then
correspondingly it gives position in the array.
Limitations:
(a) The given list must be sorted.
(b) The access of list must be random mneans; the middle element can be accessed.

2.6 POINTER ARRAYS


An array whose each element is a pointer is called pointer array.
e.g. -
int * p[4] pointer array
int a [4]- aray of integers
p[O]= &a[0! p[1]= &a[1]
p[2]= &a[2] p[3]= &a[3]
This pointer array p holds the address of each element in array a so it is called
pointer array.
Detailed Example of Pointer Array
Suppose TEAM is an array, which contains the locations
more specifically locations of different teams or
of first elements in different teams.
Team

Team 1 1 Sachin
2 Ajay Team 1

Team 2 4 3 Ravi
Rakesh
Team 3 5 Ajit
6 Nilesh Team 2
Team 4 12 7 Vijay
8
Kapil
Narendra
10 Ramesh Team 3
11 Niren
12 $$$
Sentinel of group
[End of group]
Fig.(2.7) Example of an Array
Data Structures 45

Team [L] and Team [L+1}-1 contains respectively the first and last elements
in Team L.
e.g. Team 1 1
first element of Team 1
Team [1+1]-1– -4 > last element of Team!
to
Team 4 points the sentinel of lists.

2.7 RECORD
A record is collection of related data items. Each data item is termed as field.
File is collection of similar records. Each data item may be a group item composed of
sub items.

Comparison
Record Linear Array
(1) A record may be a collection of The data items in an array
non homogeneous data; may have same data types.
i.e. the data items in a record may
have different data types.

(2) The data items in a record are There nay be natural


indexed by attributes ordering of its elemenis.
So there may not be a natural
ordering if its elements

Example of Record
Suppose a college keeps a record of each studtt, yhich cortains the
following data items.
ITEM SUBITEM
Name Last, First, MI (Middle Initials)
Address
Stream division
Phone

The structure of above record is described as foilqw$:


1. Student
2. Name
3. Last
3. First
3. MI (Middle Initial)
2. Address
2. Phone
2. Stream
3. Division
46 Data Structura

The number to the left of item name (i.e. identifying) represents a level
number. Sub items follow each group item and the level of sub items is 1 more than
the level of group item.

How to access item in record


Suppose we want to know the last name of student then it is accessed using
dot operator as follows,
Student.name.last
Generally for separating sub items from group items dot is used.

Representation of records in memory


Since records contain nonhomogeneous data it can't be stored in array. Some
higher-level languages are having built in record structure (for e.g. PL/1, PASCAL,
COBOL). Suppose these types of structures are not available in language then record
has to be stored in individual variables. But if we want to keep entire file of records,
then alldata elements belonging to the sanme identifier will be of same type. So a file
may be stored in memory as collection of arrays.
C.g. Student file

Name Address Phone Stream


Kulkarni Smita L. 19, Shaniwar Peth 4456184 Arts
Patil Ajit D. 24, M.G. Road 6361621 Commerce

Here elements in arrays name, address, phone, and stream, with same
subscript belong to the same record.

2.8 LINKED LIST


Linked list or one-way list is a linear collection of data elements called nodes
where the linear order is given by means of pointers. Each
node is divided into two
parts:
1. First part contains the information
of the element.
2. Second part contains the address of next node
in list (it is called linkfield).
START is a pointer variable, which contains the address
of first node.
Left part represents the information part of the node
while right part represents
the next pointer field of node. The pointer of last node
contains a special value called
NULL, which is an invalid address.
The schematic diagram of a linked list with
4 nodes is shown below,
Data Structures 47

START

Information part of node 2


Next pointer field of node 2

Fig. (2.8)A Linked List


The following diagram shows a linked list
1) Name of player and no. of runs from an information part while next
pointer field gives the next node's address in linked list.
1)Start 4
2) 4
3) 1 3
4) 3 > 2
5) 2 last node

Name of Player Runs Next

START 4 Ajay 84 3

Sachin 90 NULL

Ravi 40 2

Ajit 80

Fig. (2.9)
Representation of Linked List in Memory
Let List be a linked list. Then LIST will be maintained in memory as follows,
1) LIST requires 2 arrays; we will call them here INFO and LINK such that
INFO [K] and LINK [K] contain respectively the information part and
next pointer field of a node K of list.
2) LIST also requires a variable name such as START, which contains the
location of beginning of list and next pointer sentinel denoted by NULL,
which indicates end of list.
The following e.g. shows how linked list is stored in memnory. The nodes of
the list need not occupy adjacent elements in the arrays INFO and LINK and more
than one list may be maintained in the same linear arrays INFOand LINK. But each
list must have its pointer variable giving the location of its first node.
48 Data Structu

INFO LINK
1

2
START|9 3 I 4
4 N
5
7
S 12
8 K 11
9 L 3
10
11 L 6
12

Linked List can be picturized in following manner:


1) START=9, INFO [9] = L, LINK (9] =3
2) INFO [3] = 1, LINK (3]=4
3) INFO [4]=N, LINK (4]=8
4) INFO [8] = K, LINK [8] =11
=
5) INFO [11] L, LINK [11]=6
6) INFO 6]=I, LINK (6] =7
7) INFO [7] = S, LINK [7]= 12
8) INFO [12] = T, LINK {12] = 0...last node
i.e. "LINK LIST" string is stored in form of Linked List.

Advantages of Linked List


Generally lists are stored in form of arrays. But in arrays insertion and
deletion is not easy. Also array size can't be easily increased. Using linked list this
problem can be solved.

2.9 TREE DATA STRUCTURE


In case of Link data structure, each node has link information
of next node.
Thus sequentially, we can access all the nodes. It will be time consuming
for
searching long list;because cach node has information about next
node only.
In order to reduce time consumption, binary tree concept was
developed.
Before going to binary search tree, let us learn basics tree structure.
of
Tree is an hierarchical structure of collected data items.It is
nonlinear
structure.
Node : It is as element of list. It may be a character,
string or number.
Data Structures 49

Level 0
1
Level

D Level 2

Leve! 3

M Level 4

Fig. (2.10) A Tree data structure

Node Node's description


ROOT A node which has no parent.
The node containing 'A' is the root of the tree.
CHILD Nodes of root.
(a)LEFT CHILD The left node of root.
(b) RIGHT CHILD The right node of root.
The node containing A has left child containing node B
and right (child containing node C.)
PARENT :Node which has child (or children). A is parent of B
and C
LEAF :The node which has no child (or children) D, G, K, M
are leaves.
SIBLINGS Two nodes have the same parent. The nodes containing
D and E are both children of the node containing B.
These nodesare siblings.
ANCESTOR The node is an ancestor of another node, if it is a parent
of that node. The ancestors of the node containing G
are the nodes containing E, B, A. R00T is always an
ancestor of every node.
DESCENDANT The node is a descendant of another node, if it is a child
of that node. The descendant of the node containing E
are. the nodes containing G, H, K. All nodes in the tree
are descendants of the ROOT.
LEFT SUBTREE The descendants of root's left child which acts a root of
subtree.
RIGHT SUBTREE The descendants of root's right child which acts a root of
.

subtree.
LEVEL The distance from the ROOT. The ROOT is always at
zero (0) level.
50 pata Struct

LEFT TREE RIGHT TREE


Level 0

Level 1

LEAF
2
D F Level

LEAF
Level 3

K M Level 4

LEAF LEAF

Fig. (2.11)
Types of Tree
Trees can be classified according to node structure such as
1) Null tree: a tree without node.
2) Binary tree A tree which has left and right child.
:

3) Ordered tree Children of each node are ordered from Left to Right.
:

4) Nonordered tree :Children of each node are not ordered from Left to Right.

Binary Tree
A binary tree T is defined as a finite set of elements called nodes, such that
1) T is empty (called NULL tree or empty tree) or 2) T contains a
distinguished node R called the root of T and remaining nodes of T form an ordered
pair of disjoint binary trees Ti and T2.
e.g.

B
T
T2
D

K
Fig. (2.12) Binary Tree L
a
*If T contains root R then the two trees
T and T; are called respectively le.
and right sub trees of R. If T is nonempty, then its root
is called left successor of K

Similarlyif T; is nonempty then its root is called


right successor of R.
1) is left successor of A and Cis right successor of
B

2) The left sub tree of root A consists of


nodeA refer fig. (2.12).
node B, D, and E and the right subtree of A
consists of nodes C, G, H, J, K andL.
3) Any node N in a binary tree T has
either 0, 1,2 successors. The nodes A, B, C,
have two successors. The nodes D, E, G,
are called terminal nodes. L and K have no successors that nodes
Data Structures 51

Binary tree 'T and T; are said to be similar if they have same structure. The trees
are said to be copies if they are similar and if they have same contents at
corresponding nodes.

Algebraic Expressions
These can be represented as tree. Each variable or constant in E appears as
internal node of T whose left and right subtrees corresponding to the operands of
operation.
E= (a-b)K(C*d)+e)

Fig. (2.13)
Complete Binary Tree
Consider any binary tree T. Each node at T can have at most two children.
The levelrof T can have at most 2 nodes. The tree T is said to be complete if all its
levels except possibly the last have maximum no. of possible nodes and if all the
nodes at the last level appear as far as left as possible.

2 3

4 5 6

Fig. (2.14) 9 10 11 12 13 14 15
8

are 2 * K and 2 * K+ 1and the parent of


The left and right children of node K
K is the node K/2.
e.g. 4" node
Parent node 4/2 = 2
1)4*2 = 8 2) (4 * 2) + 1=9
Children
The depth of complete binary tree is given by,
Dn = [log2 n + 1]
52 pata Struct

Extended Binary Tree


A binarytree T is said to be 2 tree or extended binary tree, if each node N haa
either in or 2 children. In this case nodes with 2 children are called internal nodes
while nodes with 0 children are called external nodes.
Any binary tree may be converted into a 2 tree by replacing cach empty
subtree by a new node. The nodes in original tree are internal nodes in the extended
tree and the new nodes are external nodes in the extended tree.

Binary Tree (Original)

-
->
internal node
(External Binary Tree)
External node

Fig. (2.15)
Representing binary trees in memory
Let T be a binary tree. There are two way of representing binary trees in
memory. 1) Linked representation 2) Sequential representation
1) Linked representation
In this method 3 parallel arrays are used INFO, LEFT and RIGHT.
1) INFO[K] contains the data at node N.
2) LEFT [K] contains the location of left child of node N.
3) RIGHT [K] contains the location of right child of node N.
4) ROOT will contain the location of root R of T. It is a pointer variable.
5) If any subtree is empty then corresponding pointer will contain a null
value.
R

|xD|x x X H

Fig.(2.16)
Data Structures 53

INFO LEFT RIGHT


1

ROOT 2 0 4
5 3 E 0
4 H
5 A 10 2
6
D 0
8
9
10 B 7 3

Sequential Representation
Suppose T is complete binary tree then only single linear array TREE is used
as follows:
45
2 22
45. 77
4 11
5 30
22 77 6
7 90
15
11 30 90
10 25
15 25 88 11
12
13
Fig. (2.17)
14 88

1) The root R is stored in TREE [O1


1) If node N occupies TREE [K]then left child is stored in TREE [2 * K]and
its right child is stored in TREE [2 *K+1]
2) If TREE [1] = NULL then it is empty.

2.10 STACK AND QUEUE DATA STRUCTURE


A
stack is a list of elements in which an element may be inserted/deleted only
at one end, called the top of stack. Elements are removed from a stack in a reverse
order of that in, which they were inserted into the stack. So it is generally referred as
54 Data Structu

LIFO (Last In First Out structure).


Two basic operations associated with stack are as follows
1) Push -To insert an element into a stack.
2) Pop-To delete an element from a stack.
Best example of stack is stack of dishes.

Example: Suppose A is empty stack. Following 5 elements are pushed onto the stack.
1)
Pentium
2) 8085 microprocessor
3) 8051 microcontroller
4) 80486
5) 8255 peripherals
Stack is represented in folowing diagram

Stack A
TOP 5 8255 peripherals
4 80486
3 8051 microcontroller
2 8085 microprocessor
Pentium

1
2 3 4 -
6-- --N
Pentium 8085 8051 80486 8255
microprOcessor microcontroller Peripherals

Top of Stack
In this case 4" element can't be deleted before 5" element. In the same way
for other elements also. The elements may be popped from the stack only in reverse
order of the in which they were pushed onto the stack.
Queue
A queue is a linear list of elements in which deletions can
one end called the front and insertions can take place only at
take place only at other end called the rear.
Queues are also called FIFO(First In First Out lists) i.e. first
element in a queue
will be first element out of the queue. Queues abound
in every day life. E.g. queue
waiting for a bus.
e.g. fig. shows a schematic
diagram of a queue.
1)
A B D

Front element Rear element


Data Structures 55
2) Suppose A is deleted from queue:
B C D

Front element Rear element

3) E &F éleiments are added:


B C E

Front element Rear element

4) B is deleted:

D E

Front element Rear element

QUESTIONS
1) Select the correct alternative and rewrite the following:
a) Maximum number of nodes of symmetric binary tree with depth of 5 is
i) 5, i) 25, iii) 31, iv) 32 (Mar. 2002)
b) Tofind the location of record with a given key value is called
i) Searching, i) Sorting, ii) Finding, iv) Merging (Mar. 2005)
c) is very useful in situation when data is to be stored and retrieved in
reverse order. (Mar. 2019)
i) Stack, i) Queue, iii) Linked List, iv) Tree
d) The number of comparisons required for bubble sorting of an array of 'n'

elements is (Specimen Paper)


i) n(n-1)/2, ii) n/2, iii) log, n, iv) logo n
e
is the operation of rearranging the eiements of an array either in
increasing or decreasing order.
i) Sorting, ii) Searching, ii) DMS, iv) DBMS (Apr 90)
56 Data Struct

f) Accessing each element of an array only once is called (Mar.2003,11)

i) Traversing, ii) Searching, ii) Locating, iv) Selecting

g) The most efficient search algorithm is. (Mar.2004)


i) Binary Search i) Reverse Search ii) Linear Search, iv) Pointer Search
h) Finding the location of record with a given key value is known
as (Mar.2005)

a) Traversing b) Searching c) Sorting d) Inserting

i) Maximum number of nodes of symmetric binary tree with depth of 7 is


a) 125 b) 127 c) 128 d) 124 (Mar. 08)

i) Stored list is essential in process of an array. (Mar.2010)


i) Linear Search ii) Binary Search i) Traversing, iv) Insertion
k) Record contains data. (Mar.2009)
i)Homogeneous ii) Non-homogeneous ii) same iv) none, of these
data structure does not require contiguous memory allocation.
a) array b) string c) pointer array d) Linked list (Mar.2015)
m) A record is collection of (Mar.2017)
a) files b) arrays c) fields d) maps

2. Define the terms: a) Field b)Record c)File (March 2009)


3. Explain the following data structures with suitable diagram.
a)Linear array, b) Linked list, c) Tree (Mar.2003,11)
4. What is linked list? Explain it with suitable example.
5. What are types of binary tree? Explain it with suitable example.
6. What is Binary Tree? With a suitable example, explain the terminology. Describe
family relationship between the elements of a binary tree. (Mar.05,11)
7.
What is a Binary Tree? With a suitable example, show the relationship between
total number of nodes and depth of a binary tree. (Mar. 06)
8. How binary trees are represented in memory? Explain it.

9. Write the difference between linear search and binary search. (Mar. 2017)
10. Explain any.four data structure operations.

11. Explain data structure array.


Data Structures 57

12. What are "records"? Explain how records are represented in memory using
arrays? (Mar.2004)
13. Explain the algorithm for inserting an element from array. (Mar.2009,2016)
14. What is a record? How it differs from a linear array? (Mar. 02, 05, 07, 08)
15. What is searching? Explain binary search algorithm.
16. Explain linear search algorithmwith a suitable example. (Mar.2003)
17. What do you understand by the term "Searching"? Which are the searching

algorithms? Explain the linear searching algorithm. (Mar.2004,07)

18. How Linked list are represented in memory? (Mar. 2017)

19. What is meant by Linked list? With suitable examples show the representation of
linked list in memory. (Mar.2003,2004,2019)
20. What is linked list? Show a linked list with suitable example having six nodes

with a properly labeled diagram. (Mar. 03, Mar. 07, Mar. 08)
21. With a suitable example and diagram show a link list with information elements
and the link fields from start to null pointer. (March 2005)
22. With a suitable example, show labeled diagram for link between two nodes

having the information part and next pointer field. (March 2006)

23. Explain the advantages of binary search algorithm with a suitable example. State
any two disadvantages or limitationsof binary search. (Mar. 07)
24. Explain the bubble sort algorithm with suitable example.(Mar.02,05,Mar.08,20)

25. What is sorting? Explain bubble sorting algorithm. (Mar.2011)

26. What is binary tree? Draw the tree structure for the following expression:

E= (a-b)/[(e* d) + e] (Mar. 2002)


27. Draw the tree structure for the following expression:

[a ++ (b-c)] * [(d- e)/(f+g-h)] (Specimen Paper)


25. What is binary tree? Draw the tree structure for the following expression:

E= (a+b)Y(c* d) - e] (Mar. 2004)


58 Data Structu

26 .With suitable example and labelled diagram show the representation of binary
tree in memory. (March 2003)
27.Draw the tree-diagram which corresponds to the following algebraic expression:
E= (2X + Y)/(5A- B) (Mar. 06)
28.What is Binary Tree? Draw the binary tree structure for the following expression:
[(a + b) * c]/ [a * (b-c) + a (Mar. 08)
29.What is Binary Tree? Draw tree structure for the following expression:
E=(a -b) / ((c*d) + e) (March 2007)
30. Show the representation of records in memory considering suitable example of

three records and three fields. (Mar.03)


31. Explain with flowcharts the following control structures. (Mar.2009,2017)
a) Sequential b) Selection logicc)Iteration logic
32. With suitable example show representation
of Binary tree in a memory.
(Mar.2009)
33. Explain bubble sort algorithm with suitable example.
(Mar.2017)
34. Explain Binary Search algorithm with a suitable example.
(Mar.2019)
35. What is Binary Tree? Draw the Tree diagram
-
for the expression.
B= (3R/5T) (R + Q')
36. What are the (Mar.2019)
functions of Memory Management? State any two types
of
continuous Real Memory Management System.
(Mar.2019)
37. Explain internai and external
fragmentation in memory management of operating
system.
(Mar.2020)
38. Define linked list. Draw and explain
labelled diagram of linked list
with 5 nodes.
(Mar.2020)
Answers Q.(1)
(a) 31(b)searching (c)stack (d)n (n-1)2 (e)Sorting
()Traversing
(g)Binary search (h) Sorting (i) 127 Binary
() Search (k) Non-homogeneous
1) Linked list (m) fields
3
C++ PROGRAMMING
INTRODUCTION
Last year we have seen C++ without its powerful object oriented concepts. In this
chapter we will now see the concept behind object oriented programming, C++ as
OOP, and some of the striking features of OOP.When programmer is given a
complex problem, he follows different programming styles to tackle it.
Some of them are listed below.

3.1 PROGRAMMING APPROACHES


Unstructured programming.
The main program directly operates on global data. Here "main program" stands for a
sequence of commands or statements, which modify data, which is global throughout
the whole program. These programming techniques generate tremendous problems
once the program gets sufficiently large.
Procedural programming
The main program coordinates calls to procedures and hand over appropriate data as
parameters. A single program, which is divided into smallpieces, called procedures.
Modular programming allows grouping of procedures into modules.
Modular programming
The main program coordinates calls to procedures in separate modules and hand over
appropriate data as parameters. Each module can have its own data. This allows each
module to manage an intcrna! state, which is modified by call to procedures of this
module.
Object-oriented programming
Object-oriented programming solves some of the problems just mentioned. In
contrast to the other techniques, we now have a web (group) of interacting objects,
each house-keeping its own state. Objects of the program interact by sending
messages to each other. It is most advanced approach and offers many advantages
over other approaches just mentioned above.

3.2 IDEA BEHIND OBJECT ORIENTED PROGRAMMING


Object Oriented Programming (0OP) is most modern way of organizing
programs. Here the emphasis is given on the way programs are designed; in particular
OOP programs are organized around objects, which contain both data & functions
that act on that data.
The idea is that when a programmer is given a new problem, the decomposition
process that initially takes place is in terms of the objects found in the problem. These
objects can be classified into different groupings called classes, and these classes can
then be analyzed to determine:
L
60
C++ Programmi

The properties held by objects of the class,


The actions objects of the class are capable of performing,
The relationships between classes.
us has
One strong example of this is Biology, where the complexity of life around
been studied extensively in terms of classifying life forms into various groups and
subgroups. Using the object-oriented terms of class and instance, a species can be
seen as a class and an individual member of the species as an instance (or object) of
the class.
Object-oriented design allows us to think about the actual real-world entities of the
problem we are attempting to provide a solution for. Here instances refer to objects
&class provides a template for number of objects.

Benefits Of OOP
OOP approach has lot many. advantages over other programming approaches. Here
are some of them listed below:
1) 00P treats data as a important element in the program development and
doesn't allow to be accessible by any user. Thus it protects data from accidental
modification from outside world. This is achieved through data hiding.
2) OOP allows us to decompose a complex problem into number of entities
called objects and then build data and functions around these entities. Here different
objects may communicate with each others through functions.
Thus object orientation gives us the solution of many problems associated with
developments. Software complexity can be easily managed.
3) Using encapsulation, it is casier to view the actual data and associated
function allowing us to get more details of a model. Encapsulation is collection of
data and functions together.
4) Inheritance, provides you software reusability, code saving and extending
use of existing classes.
5) Through polymorphism, same thing can be implemented in slightly
different manner. Providing more flexibility in the design.

Features of O0P:
1) Programs are divided into objects, and different objects communicate
with
each other through messages, called methods.
2) Emphasis is given on data rather than procedure.
3)Data is hidden and can't be accessed or altered by external functions.
4) Functions operating on data of an object are
encapsulated (tied together in
single data structure called class.)
5)New data and functions can
be easily added whenever necessary.
6) Follows bottom-up approach
in program design.
C++ Programming 61

C++ as Object Oriented Language


O0 programming techniques are the best ways, to develop large, complex
software applications and systems. C++ can be used both as an O0PL and simply "as
a
better C". C++ programs are fast and efficient, which helped to make C++, an
extremely popular programming language. It uses templates, static polymorphism,
dynamic polymorphism, generic programming, inheritance; data binding and
encapsulation etc.which covers most of the object-oriented concepts.
Also C++ supports a programming technique that allows memory management to be
safe and implicit In combination with the use of templates, constructors, and
destructors enables the C++ programmer to use programming and design techniques
that are more advanced than what is supported in the languages with which C++ is
most often compared.

Applications of Object Oriented Concepts


There are number of areas in which OOPs concepts can be interpreted and applied.
Major application lies in the design of GUI (Graphical User Interface).In case of real
time business applications,O0OP are mostly used since it is capable of handling
complex problems and strong features of it.

It'simportant role lies in design, maintenance, and modeling of complex systems.


Recently it is moved into analysis of the system to be designed. It also provides
strong automation support in CAD, CAM, CIM systems. Maintains Object-oriented
databases. Also used in AI and Expert Systems Used for simulation, monitoring and
modeling of Real time systems.

3.3 OBJECT-ORIENTED TERMS AND CONCEPTS


Objects are the physical and conceptual things we find in the universe around us.
Hardware, software, documents, human beings, and even concepts are all examples of
objects.e.g. Script writer,financier,actor, actress,spot-boy, lyricist,choreographer,dress
designer would all be objects a film director might consider in directing a movie.
Likewise, a software engineer would consider stacks, queues, windows, and check
boxes as objects. They are called as runtime entities in object oriented system. They
are also called as class type entities. (since belong to a particular class). They are even
called as an instance of the class. They are used to access members (data and
functions)of the class.

> Classes
Up till now we have seen built in data types (int. float,etc.) derived data types (arrays
functions) those are already known to compiler. Class is said to be user-defined data
type; which is defined by the user. Users of object-oriented technology usually think
of classes as containing the information necessary to create instances, i.e., the,
structure and capabilities of an instance is determined by its corresponding class.
Classes serve as templates for the creation of objects.
62 C++ Programm

related
From object oriented point of view, class provides entire set of data and
functions to be made user-defined. Thus programmer can build number of classes
according to requirements.
or blueprint for a category of
Thus we can say, a class is a pattern, template,
structurally identical items. The items created using the class are called .instances
as
Whenever class is used to create objects, process is known instantiation.
Instantiation has two common meanings:
as a verb, instantiation is the process of creating an instance ofa class, and
as a noun, an instantiation is an instance of a class.
(Some people restrict the use of the term "object" to instances of classes.))

> Operations /methods (functions)


message
A message is a request to an object to invoke (call) one of its methods. A
therefore contains
the namne of the method and
the arguments of the method.
A method(function) is associated with a class. An object invokes a method as a
reaction to receipt of a message. Also many objects communicate with each other via
methods.

> Data binding and Encapsulation:-


It is one of the strongest features of oops supported by C++. The wrapping up of data
and its associated functions together under a single unit is called as encapsulation.
While providing access to an object only through its messages, while keeping the
details private is called Information hiding. Information hiding is the process of
hiding al! the details of an object that do not contribute to its essential characteristics.
Typically the structure of an object is hidden as well as the implementation of the
methods. The advantage of using this is, the data is hidden from outside world and
hence from accidental modification.

> Inheritance
Inheritance can be defined as the process whereby one object acquires
characteristics from one or more other objects. Some object-oriented systems permi!
only single inheritance, a situation in which a specialization may only acquire
characteristics from a single generalization. Many object-oriented systems, however
allow for multiple inheritance, a situation in which a specialization may acquite
characteristics from two or more corresponding generalizations.
Thus main purpose behind using inheritance is reusability of the existing code.

> Polymnorphism
Literal meaning - many forms (ability to take more than one form)
OOP meaning
Same method (message) but different behavior (function code)
C++ Programming 63

Object determines which method gets executed


Polymorphism means existing in many forms, that is same entity like function,
operator is implemented in different ways. In C++ polymorphism is implemented
using virtual functions, function overloading, and operator overloading.

Now let's see all these concepts in detail.

3.4 CLASSES
Aswe are aware, classes are data structures clubbing together data and associated
functions together. Let's see how,

Class declaration:
class class_name
{

access-specifier:
data and functions
access-specifier:
data and functions

access-specifier:
data and functions

}object-list;

C++ allows the declaration and definition of classes. Instances of classes are
called objects. In above declaration, ciass is a keyword. Access specifier may be
public, private and protected, which decides scope and visibility of data members
and member functions declared in the class definition. Thus class is said to be user
defined data type. So implementation of the same class varies from user to user.
Following example illustrates the class definition including its members:

Examplel1: Class definition including its members:


#include<iostream.h>
class ABC

private: int data;


64 C+t Programm
public: void getdata()

cout<<"Enter number:";
cin>>data;
cout<<"The number entered is:"<<data;

};
void main()
{

ABC obj;
obj-getdata( );

Output:
Enter number: 10
The number entered is: 10

Program Explanation: Here we have written class definition having class name
ABC.In this class we have declared one variable as data which is called as data
member of the class, while function getdata is accessing this data member, it is called
as member function.
Class definition ends by giving semicolon after closing curly brace. Then we write
main function (called nonmember function), in which you instantiate a class by
Creating a object. Thus a class is loaded in memory, in turn giving memory to its
respected members (including data members and member functions). This process is
known as instantiation or object creation. Then you give call to member function via
object.

Scope rules for different members of the class:


A class in C++ has a group of data and associated functions called
data members and
member functions, which are given, one of the access
modifiers, namely public,
private and protected.

1) public access modifier:


All data members and member functions declared
using public access
modifier (i.e. those are defined in the public section
of the class) are accessible by any
function in a program.

2)private access modifier:


If you don't specify, any access modifier to the data members or membe
functions of the class, they are by defauit private.
world and they are normally used
These are hidden from outsi0
to implement data hiding concept of object orjented
programming.
C++ Programming 65

But only member functions and friends of the class can use them, in which are
declared.

access modifier:-
3)protected
These can only be used by member functions and friend of a class as well as derived
class member functions. They are similar to private members since they can't be
accessed directly by non-member functions, but can be used by derived ones.
Therefore this access modifier is more restrictive than public but less restrictive than
private. Following program illustrates the use of access modifiers.

Example 2: A Program using access modifiers to display object details.


#include<iostream.h>
class ABC
{

private:int number;
protected:int data;
public: void getdata()

cout<<""Enter first number:'";


cin>>number;
cout<<"Enter second number:";
cin>>data;

void putdata()

cout<<""The first number entered is'"<<number;


cout<<"The second number entered is'"<<data;

};
void main( )

ABC obj;
llobj.number=10; llcan't access private members.
obj-getdata( );
obj.putdata( );

Output:
Enter first number:10
Enter second number:20
The first number entered is10
The second number entered is 20
66 C++ Programmin
Progranm Explanation: In above program, data is protected mnember,
is a private data member. Both of these
while number
can't be accessed from within non-member
function i.e. main function. But getdata( ) and putdata( ) can access
are member functions them since they
of the class. Thus from main function you can access these
private and protected members, not directly, but through
public member functions,
here getdata( ) and putdata( ).

A class itself may be defined at any one of three possible scopes:


1. At the global scope. This leads to a
global class, whereby it can be referred to
by all other scopes. The great majority of C++ classes (including all the
examples presented so far in this chapter) are defined at the global scope.
2. At the class scope of another class. This leads to a nested
class, where another
class contains a class.
3. At the local scope of a block or function. This leads to a local class, where the
class is completely contained by a block or function.

3.5 OBJECT IN C++

Objects are autonomous entities of the class; they are instances of the class and
belong to a class. Traditionally, code and data have been kept apart but in o-o (object
oriented) programming, code and data are merged into a single indivisible thing ' an
object'. Thus methods are normally invoked using objects.

Example 3: Following program illustrates invoking class members (data and


function) via instance (objects) -
#include <iostream.h>
class ABC

public: int i;
void display( )

cout<<"Invoking member function through object";

void main( )

ABC obj; Ifinstance of a class.


obj.i=5; llaccessing data member via instance
cout<<obj.i;
obj.display( ); liaccessing member function via instance
}

Output is:5 Invoking member function through object


C++ Programming 67
> Pointers to Object Members
We have seen use of pointers, to point to a variable. Pointers can also be used to point
object (members of a class also).

Example 4: Accessing members of a class using pointers (pointers to object


members of a class):
:#include <iostream.h>
class ABC

public:
int data;
void getdata()
{ cout<<"Enter data:";
cin>>data;
cout<<"The number entered is:'"<<data;

void main( )

ABC obj;
int *p;
obj.data=4;
p= &obj.data; Ilpointer to object of a class
cout << *p;
ABC *q;
q= &obj.data ;
q->getdata( );

Output is: 4
Enter the number: 10
The number entered is : 10.

Program Explanaion: In above program, we have 2 pointers, one is integer pointer


and other is class type pointer. Both are used to point to object members.
Thus both data members and member functions can be accessed via pointers also, just
by giving them, reference of class to which they belong to.
For invoking member function through pointer, we use pointer to member function
operator (>)
Thus you can assign the address of a public member of an object to a pointer.
Then access that member by using the pointer.
When accessing members of a class given a pointer to an object, use the arrow (->)
operator.
68 C++ Programmi

Passing References to Objects


Variables can be passed to the function either by value or by reference. Similarly We
can pass a reference to object toa function. When an object is passed as an argument
to a function, a copyof that object is made, i.e. function creates its own copy and
works on its own copy therefore, any changes made in function don't affect the
original object while when you pass an object by reference, no copy of the object is
made, its memory address is passed to a function so that called function directly
works on the original object which is passed to the function during function call.
Therefore any changes made in the function are reflected in the original object.

Example 5: A program illustrating how to pass reference to object as a function


argument.

#include <iostream.h>
class ABC

public: int data;


void getdata( )

cout<<"Enter number:'";
cin>>data;
cout<<"You entered:"<<data;

void putdata(ABC &obj) /passing reference to object


{

obj.data = -obj.data;
cout<<"Now number is changed to:"<<obj.data;
}

void main( )

ABC objl;
objl-getdata( );
obj1.putdata(objl);
}

Output is: Enter number: 10


You entered: 10
Now number is changed to: -10

Program Explanation: Here in the putdata(Ofunction we have passed reference lo


object to modify the data mnember from within the member function via
its ODJ
C++ Programming 69
> An Array of Objects
Last year we have already discussed the concept of array, but we have
restricted this idea only to built in data types. But it can be extended and used with the
user-defined data types.
Thus C++ supports arrays of any data type., including class type. So we can
call array having class type elements as array of objects.
Syntax :classname obj[dimension]:
ABC obj[31;
Here is declared array of 3 objects of class ABC

Example 6: Program using array of objects


#include<iostream.h>
class ABC1
{

private:int number;
public:void getdata()

cout<<"\nEnter number:";
cin>>number;
cout<<number;

void putdata()

cout<<"The number entered is"<Knumber;

};
void main( )

ABC1 obj1[31;
ABC1 obj;
for(int i=0;i<3;i++)
{
obj1[i]-getdata( );
obj1[i],putdata( );

Output is:
Enter number: 10
The number entered is10
Enter number: 20
The number entered is20
Enter number: 30
The number entered is30
70 C++ Programmin
3.6 METHODS/FUNCTIONS
They are used to manipulate the data. There are two ways to define methods:

1.Methods can be defined in class definitions.


e.g. int getdata( ){ return
numberl;}
C++ compilers treat these as inline functions: they tryto expand
functions where they are called. the bodies of the

2.Methods can be defined outside


the class definitions.
It is also possible to merely declarea method in a
class definition,
int get_data( );
and give the full definition later, outside
the class: using scope resolution operator.
int ABC:: getdata(){ return numberl; }
i.e. getdata is a function from class ABC.
Because this is outside the class, we must
qualify the function name with
the class (ABC::).
Example 7:Following program illustrates
#include <iostream.h> the same.
class ABC
{

public:
int data;
void getdata()
{ cout<<'"Enter number:'";
cin>>data;

void putdata( );

void ABC::putdata()

cout<<"Entered number is:'"<<data;

void main()
{
ABC obj;
obj-getdata( );
obj.putdata();
}

Output is: Enter number: 10


Entered number is: 10
C++ Programming 71

Program Explanation: Here putdata() member functionis declared outside the class
definition, so we specity scope resolution operator and classname to which this
function belongs to.

3.7 CLASSES VERSES STRUCTURES


A structure is aclass whose members are by default public. (Remember that all of the
members of a class are by default private.) Structures are defined using the same
syntax as classes, except that the keyword struct is used instead of class. For example,
struct Rectangle

Rectangle(int, int);
void draw(int, int);
int x, y;
is equivalent to: --

class Rectangle

public:
Rectangle( (int, int);
void draw(int, int);
int %, y3

The struct construct originated in C, where it could only contain data


members. It has been retained mainly for backward compatibility reasons. In C, a
structure can have an initialiser with syntax similar to that of an array. C++ allows
such initializers for structures and classes all of whose data members are public:

EXERCISE
a) Define class complex with appropriate data and function members.
b) Write a program in C++ to display a given complex number.
c) Write a program in C++ to accept and display three complex numbers.

3.8 NESTED CLASSES


We have already seen nesting of loops,i.e. defining loop within a loop. Similarly you
can definea class inside other class definition.So this is called nesting of the class.
The name of such a nested class is local to the nesting class.

Example 8: Following example illustrates the use of nested class.


#include <iostream.h>
class A

private:int adata;
public: void getadata()
C++ Program
72
{
cout<<"Enter the number:";
cin>>adata;
cout<<"hiyou are in outer class and you
entered:'"<cadata;

class B

private:int bdata;
public: void getbdata()

cout<<"Enter the number:'";


cin>>bdata;
cout<<"hi you are in inner class and you
entered:"'<<bdata;
llgetadata( );

};
B bobj; Ilvalid.
void display()

bobj.getbdata( );
}};
void main( )
{

A aobj;
I/B bobj; Iinvalid.
aobj-getadata( );
aobj.display( );
}

Output is: Enter the number:10


hiyou are in outer class and you eneterd:10
Enter the number:20
hi you are in inner class and you eneterd:20

Program Explanation: Here class A is outer class defined, in the


which you
public section
define nested class B.From within class B.it is not
possible to invoke
outer class member function. Also inner class is
instantiated in the body of oulo
class. You can very well invoke inner class member function
through its instan°
from within member function of an outer class. Here we getbdata( )
function through its instance from within member function have invoked
display( ) of outer class
C++ Programming 73

3.9 CONSTRUCTORS
A construetor is an operation that has the ability to change the state of an object.
The initialization of object takes place using special function called constructor. It is
called when you instantiate an object. The constructor is a function whose name is the
same as the class, with n0 return type (not even void).
Constructors are methods that are used to initialize an object at its definition time.
Constructors have the same name of the class (thus they are identified to be
constructors). As other methods, they can take arguments. So they can be overloaded.
Constructors are implicitly called when we define objects of their classes. There are
two types of constructors.

Syntax:
1)default constructor: If you do not define any constructor in your class then system
provides it. It has no body but you can define it as well. It is also known as no
argument constructor.

classname( )
{

I/body of default constructor.

2)parameterized constructor: this type of constructor can take arguments so it is called


parameterized constructor.
classname(parameter list)

I/body of parameterized constructor.

Example 9: Program using different types of constructor.


#include <iostream.h>
class ABC

int data;
public: ABC) I/ default constructor

cout<<"This is default constructor.";


}

ABC(int a) / single argument constructor

cout<<"This is parameterised constructor.'";


data=a;
cout<<"value of data is:"<<data;
74 C++ Programmi

void main( )
{

ABC obj; lldefault constructor is invoked.


ABCobj1(5);

Output is: This is default constructor.


This is parameterized constructor.
value of data is : 5
so constructor's name is
Program Explanation: Here we have defined class ABC, one default
constructors, The first is
also same as classname. We have defined 2
is created(i.e. by
Constructor, taking no parameter and is invoked when class object
statement ABC obj; Here we have provided body for the default constructor.i
parameterized
Now in the second line class object is created with parameter 5,so
in the
constructor iscalled in the body of which we initialize the data member defined
class.
Thus with the help of constructors. we have fulfilled one of
our requirements of
implementation of abstract data types: Initialization at definition time.

Overloading Constructors
Like any other function, a constructor can also be overloaded with several functions
that have the same name but different type or number of parameters. Remember that
the compiler will execute the one that matches at the moment at which a function
with that name is called.
In fact, in the cases where we declare a class and we do not specify any constructor
the compiler automatically assumes two overloaded constructors ("default
constructor" and "copy constructor"). For example, for the class:
class ABC

public:
int a,b,c;
void multiply (int n, int m) { a=n; b=m; c=a*b; }

with no constructors, the compiler automatically assumes that it has the following
constructor member functions:
Empty constructor
It is a constructor with no parameters defined as nop (empty block Of
instructions). It does nothing.
ABC::ABC) {};

Copy constructor
It is a constructor with only one parameter of its same type that assigns to every
nonstatic class member variable of the object a copy of the passed object.
C++ Programming 75

ABC::ABC(const ABC& objl)

a=objl.a;
b=obj1.b;
c=objl.c;

Note: It is important to indicate that both default constructors: the empty constructor
and the copy constructor exist only if no other constructor is explicitly declared. In
case that any constructor with any number of parameters is declared none of these
two default constructors will exist

Example 10: Program using copy constructor.


#include <iostream.h>
class ABC

private: int data;


public: ABC(){.
ABC(int value){ data=value; }

ABC(ABC &ob)

data=obj.data;
cout<<"copy constructor invoked:";
}

void main( )

ABC objl1(50);
ABC obj2;
ABC obj3(obj1); Ifinvokes copy constructor.
obj2=obj1; Ilinvokes copy constructor.
When initializing an instance with another instance (as might happen when declaring
an instance and immediately initializing it with the values from another instance) and
when passing an instance as a value parameter to a function, the property values of
one instance are copied to another instance. Such copying requires a copy constructor.
C++ automatically provides one that works as long as the class declaration does not
include pointer, class, struct, or array-based data members. In these situations it may
be necessary for programmers to declare their own copy constructors

Example 11: Following example illustrates how to overload class constructors


#include <iostream.h>
class ABC
76 C++ Programm

int width, height;


public: ABC);
ABC (int,int);
int area ()
{
return (width*height);

ABC:ABC) Ildefault constructor.


{

width = 5;
height = 5;
}

ABC::ABC(int a, int b) l/parameterized constructor.


width a;
height = b;

void main ()

ABC objl (3,4);


ABC obj2;
cout << ""objl's area: " << objl.area() << endl;
cout << "obj2 'sarea: <<obi2.area( ) << endl;

Output is: objl's area: 12


obj2's area: 25

Program Explanation: Here first constructor. is default constructor no


arguments taking
and when the class is instantiated,(here obj2)the call to this is made
„initialing height and width to be equal to 5.While when
obl is created since it is
called with 2 arguments ,a parameterized constructor is called.

Constructor and operator new:


The arguments of a constructor can be given as parameters when
new objects: allocating
Date* dl =new Date( 2000, 2, 23 );
Date* d2 = new Date; // default constructor is called.

Exercise: Write a program in Ct+ to overload constructors. Program should


contain two constructors; one without parameter and second with parameters
(assume complex class).
C++ Programming 77

3.10DESTRUCTORS
mechanism, which automatically "destroys" an object when it gets invalid (for
A

example, because of leaving its scope).. Destructors are used to release any resources
allocated by the object's constructor. The usual "resource" being acquired in a
constructor (and subsequently released in a destructor) is dynamically allocated
memory. You don't call them explicitly (they are called automatically for you), and
there's only one destructor for each object. The name of the destructor is the name of
the class, preceded by a tilde (-).
Destructors take no arguments. It is even invalid to define one, because
destructors are implicitly called at destruction time: You have no chance to specify
actual arguments.So overloading of destructor is not possible.
Destruction of objects takes place when the object leaves its scope of
definition or is explicitly destroyed. Destructors are declared similar to constructors.
Thus, they also use the name prefixed by a tilde (-) of the defining class:

Example 12: Following example illustrates use of constructors and destructor


#include <iostream.h>
class ABC

int *width, *height;


public: ABC(int,int); lWconstructor.
~ABC() l/destructor.
int area ()
return (*width * *height);
}

ABC::ABC (int a, int b)


{

width = new int;


height = new int;
*width=a;
*height = b;

ABC::~ABC ()

delete width;
delete height;

void main ()

ABC obj1 (3,4), obj2 (5,6);


cout << "Area of rectangle is: " << objl.area() << endl;
78 C++ Programmi

cout <<"Area of rectangle is:" << obj2.area) « endl;


Output is: Area of rectangle is: 12
Area of rectangle is: 30

3.11 STATICMEMBERS
Static members of a class are not specific to an instance of this class. It is common
and accessible by all the instances of this class. The class constructor does not
initialize static variables. Thus a static function can be considered as a specific global
function, which can access the static private/protected variables of the class.
Declaring a member variable within a class as 'static' means that it is shared among all
of the class's member functions (and friends), and it has "program" (not auto)
lifetime. Its value is not associated with any object of that class type, but rather it
exists apart from any such objects. Therefore to invoke it, requires no object creation.
Its name has class scope (and thus is subject to access restrictions based on whether it
is declared as 'public', 'protected', or 'private'). It has "external" linkage, meaning that
its name is visible outside the file in which it is defined.
Access rules for static and non-static functions of a class:

Non static Non static Static Static


member member member member
variable function variable function
Non static
Yes Yes Yes Yes
member function

Static nember
No No Yes Yes
function

Static variables are automatically declared to 0,so the explicit initialization in the
definition is unnecessary unless you want it to have a non-zero initial yalue.

Example 13: Program to illustrate properties of static members.


#include <iostream.h>
class ABC
{
private: static int data;
public: staticvoid getdata( )

++data;
C++ Programming 79

cout<<"count is:"<Kdata;
void putdata()

++data;
cout<<"Now count is:"<<data;

int ABC::data=5;
void main( )

ABC obj;
ABC::getdata( );
obj.putdata( );

Output: count is: 6 Now count is: 7 one is


Progran Explanation: In above program we have used 2 static members,nonzero
static data member, note that we can initialize this data member to give it
even need not be
value without requiring constructor(explained after this topic),or
a getdata(
called with the help of object. second static member is member function
to be static. But if we
),which also need not be called via class object since declared
instantiation, since
call putdata() member function in the similar way,i.e. without
message as illegal call of non-static member
being nonstatic compiler will give error
you need to instantiate the
function. Thus for invoking nonstatic members of the class
class. a
of objects declared in
Exercise: Writea program in Ct+ to count number
program using static function (assume complex class).

3.12 INHERITANCE.
inheritance. You might want to review
One of the most useful features of classes is
a
the concept. It is possible to declare class
that inherits the properties of another
class or classes. This means that, with good
class design, you can build applications,
i.e. main purpose behind inheritance is
which are based on proven re-usable code.
code-reusability. class, in C+-+
a a child class (or derived
What you need to do is to create subclass/ existing messages,
class. This new lass inherits all the
terminology) of the original is called the
therefore, all the behavior of the original class. The original class
and
new class. A subclass is said to be specialization
a

parent class, or superclass, of the


a superclass a generalization of its subclasses.
Of itS superclass, and the conversely a default, classes
distinguishes two types of inheritance: public and private: As
C++
from each other. Consequently, we must explicitly tell the
are privately derived
30 C++ Program

compiler to use public inheritance. The type of inheritance influences the acce,:
rights to clements of the various super classes

Summary of Inheritance Access Control


Inheritance Control, (Derived class)
Public private Protected
public Public private protected
Access Control, (Base Class)|l private ||Not accessiblelNot accessible|Not accessible
protected protected private protected

The leftmost column lists possible access rights for elements of classes. It also
inciudes a third type protected. This type is used for elements which should be

directly usable in subclasses but which should not be accessible from the outside.
Thus, one could say elements of this type are between private and public elements in
that they can be used within the class hierarchy rooted by the corresponding class.
·
In general, it is good praçtice to,make data members private. Member functions that
must be called from outsidèthe class should be public, and member functions that are
only called from within the class should probably be private.JThus in addition to
speeding development time, proper class construction and reuse results in far fewer
lines of code, which translates to less bugs and lower maintenance costs.

3.13DIFFERENT FORMS OF INHERITANCE


Ct+ supports single and multiple inheritance. Multiple inheritance in C++ is the
ability to have two or more base (or parent) classes. The benefits for the user would
be to create objects, which would have the characteristics of both its parent or base
classes. Thus,

Single Inheritance
> Derived class has only one direct base ciss
Creates "simple" hierarchy of classes - trees
> One to one inheritance of members
> Specializes a single base class

Multiple Inheritançe

A Derived class has more than one direct base class


A Creates complex" hierarchy of classes - graphs
A Possible multiple inheritance of members
A Combines multiple classes
e.g. class D: public A, public B {...};
A Same Inheritance and Access Rules
C++ Programming 81

Multiple Forms of Inheritance


1.Single inheritance 2. Multiple Inheritance

Base Base1 Base2

Derived
Derived

3.Hierarchical Inheritance: 4.Multilevel Inheritance


Base
Base

Derived1.

Derived 1
Derivedn
Derivedn
5.Hybrid Inheritance

Base 1

Derived1 Derived 2

Derived

Syntax for the declaration of derived class


class derived_class_name access_specifier base_class_name

I/ body of class
e.g:
class A
82 C++ Program
{

Ibody of class A

class B : public A

I/ body of class B

Here class B is derived from base class A


Here public access specifier defines ,how
Class is derived from base class .Now let's see
different ways of accessing base class
members

Example 14: Base Class Access Control, Public(publicly


#include <iostream.h> derived class)
class base

int i, j;
public:
void set(int a, int b) {i=a; j=b;}
void sho*(){cout
<«i«"" <<j«""n";}
class derived : public base
{

int k;
public:
derived (int x) //derived class constructor.
{
k=x; }
void showk() { cout << k<« "n":; }

void main()

derived ob(3);
ob.set(1, 2); access member
/
ob.show(); /access member of base
of base
ob.showk(); I/ uses member of
} derived class
Output is:
1 2
3

When the access specifier


base become public membersfor a base class is public,
all public mnembers the
of the derived class; and of
C++ Programming 83

All protected members of the base become protected members of the derived
class.
The base class'private elements remain private to the base and are not
accessible by members of the derived class.

II This programwon't compile.


Base Class Access Control, private(privately derived)

#include <iostream.h>
class base

int i, j;
public:
void set(int a, int b) { i=a; j=b; }
void show(){ cout <<i«""<«j<«""\n";
};

I/Public elements of base are private in derived.


:
class derived private base
{

int k;
public: derived(int x) { k=x;
void showk() { cout <<k << "n":
void main()
{

derived obj(3);
obj.set(1, 2); I/ error, can't access set()
obj.show(); Il error, can't access show()
}

When the base class is inherited by using the private access-specifier, all
public and protected members of the base class become private members of
the derived class.
This means that they are still accessible by members of the derived class but
cannot be accessed by parts of your program that are not members of either
the base or derived class.

o Inheriting Protected Members, public


#include <iostream.h>
class base
{

protected: int i, j; Il private to base, but accessible by derived


public: void set(int a, int b) { i=a; j=b;
C++ Programm
84
{ cout << i<«""<«j<«"n'";
void show()

class derived :public base

int k;
public: Il derived may access base's i and j
void }
setk(){ k=i*j;
void showk() { cout <<k<« "\n'";

void main( )

derived obj;
obj.set(2, 3); / OK, known to derived
obj.show(0; / OK, know to derived
obj.setk( );
obj.showk();

Output is:
2 3
6
When a class member isdeclared as protected, that member is not accessible
by other, non-member elements of the program just like private members.
If the base class is inherited as public, then the base class' protected members
become protected members of the derived class and are, therefore, accessible
by the derived class,

o Inheriting Protected Members, protected :-


#include <iostream.h>
class base

protected: int i, j; Ilprivate to base, but accessible by derived


public: void setij(int a, int b) { i=a; j=b;
void showij( ) { cout <<i<<"" <<j«"n"; }
}:
I| Inherit base as protected.
class derived : protected base

int k;
public: Il derived may access base's i and jand setij().
void setk()

setij(10, 12);
k=itj;
C++ Programming 85

void showall( )

cout <<k<«"";
showij( );

)
void main(

derived obj:
obj.setij(2, 3); I/ illegal, setij( ) is protected member of derived
obj.setk(); / OK,public member of derived
obj.showall( ); / OK, publicmember of derived
obj.showij( ); /illegal, showij( ) is protected member of derived
When the base class is inherited as protected, allpublic and protected
members of the base class become protected members of the derived class.

3.14 CONSTRUCTORS AND DESTRUCTOR'S IN DERIVED


CLASSES
A derived class may have constructors and a destru tor. Since a derived class may
provide data members on top of those of its base class, the role of the constructor and
destructor is to, respectively, initialize and destroy these additional members.
When an object of a derived class is created, the base class constructor is applied to it
first, followed by the derived class constructor. When the object is destroyed, the
destructor of the derived class is applied first, followed by the base class destructor.
In other words, constructors are applied in order of derivation and destructors
are
applied in the reverse order. For example, consider a class C derived from B, which is
in turn derived from A.
class A {/*...
...
*/}
class B :
public A
{/* */}
class C: public
B {
*..*/}
Derived class object construction and destruction order.
c being constructed c being destroyed

A: :~A
A: :A

B: :B B: :-B

C: :C
C::-C
86 C++ Programm

The constructor of a derived class whose base class constructor requires arguments
should specify these in the definition of its constructor. To do this, the derived class
constructor explicitly invokes the base class constructor in its member initialization
list.
e.g., the XYZ constructor passes its argument to the ABC constructor in this way:
XYZ::XYZ(Const int max) ABC(max)
{/*.. */)
In general, all that a derived class constructor requires is an object from the base
class.
Note: The order in which the base class constructors are invoked is the same as the
order in which they are specified in the derived class header (not the order in which
they appear in the derived class constructor's member initialization list)
and the
destructors are applied in the reverse order.
O
Order of execution of constructors and destructors inheritance
#include <iostream.h> in
class base

public: base() cout << "Constructing baseln'";


~base() cout << "Destructing baseln'';
class derived1 : public base

public: derived1() { cout <<"Constructing derived1\n";


~derived1(){ cout << "Destructing
}; derived1\n"; }
class derived2 : public
derived1
public: derived2() { cout <<"Constructing
};
~derived2() { cout << "Destructing derived2\n";
derived2\n'"; }
void main()
derived2 obj;
ll construct and destruct
ob
Output:
Constructing base
Constructing derived1
Constructing derived2
Destructing derived2
Destructing derivedl
Destructing base
When an object a
constructor, it
of derived class is created,
will be called first, followed if the base class contains a
by the derived class' constructor.
C++ Programming 87

When a derived object is destroyed, its destructor is called first, followed by


the base class' destructor, if it exists.
Put differently, constructor functions are executed in their order of derivation.
Destructor functions are executed in reverse order of derivation.
In case of multiple inheritance, the general rule applies:
Constructors are called in order of derivation,destructors in reverse order.

3.15MULTIPLE INHERITANCE IN C++


You can easily derive from more than one class by specifying the superclasses in a
comma-separated list:
public - visible to the world and therefore usable by any other object

private - visible solely within one object i.e. local to an object


-
protected - visible to an object, its friends and any derived classes
In general, a derived class may have any number of base classes, all of which
must be distinct:
o Inheriting Multiple Base Classes:
#include <iostream.h>
class base1

protected: int x;
public: void showx() { cout <<X<< "n'"; }

};
class base2

protected: int y;
public: void showy(){ cout <<y<«"n"; }

};
I/ Inherit multiple base classes.
class derived : public basel, public base2

void set(int i, int j) { x=i; y=j;


public:
};
void main( )

derived obj;
obj.set(10, 20); ll provided by derived
1
obj.showx(); I/from base
obj.showy); I/ from base 2

Output:
10
20
88 C++ Programmi

To inherit more than one base class, use a common-separated list.


Be sure to use an access specifier for each base inherited.

Ambiguity in multiple inheritance


Ambiguity in multiple inheritance may also arise when 2 base classes have functions
with the same name, while a class derived from both, has no function with this name.
So how objects of the derived class can access the correct base class function? Since
the function name, alone is not sufficient, since compiler can't figure out which of the
2 functions are to be executed...This problem is resolved using scope resolution
operator to specify the class in which function to be invoked lies.

include <iostream.h>
çlass basel

public:. void show(){ cout <<class base1":


class base2

public: void show(){ cout <<class base2?


class derived : public basel, public base2

void main( )

derived obj;
obj.show(0; llambiguous to the compile
obj.base2::show( ); I/function from base2 class.
}

Passing Parameters to Base Class Constructors


Another question arises when
dealing with multiple inheritance:
parameters to the constructor how does one pass
function of a base class, here ---
#include<iostream.h> it is
class Base

protected: int j;
public:
Base(int y)

j=y;
cout << ""Base class constructor
called.n";
C++ Programming 89

-Base( )
{

cout << "Base class destructor called.\n";

:
class Derived public Base

int k;
public:
I/Derived uses x; y is passed along to Base
Derived(int x, int y): Base(y)

k=x;
cout << "Derived class constructor called.n";

-Derived()
{
cout << "Derived class destructor called.n'";
}
};
void main( )

Derived obj1(5,6);

The output from this program is the


same as in the previous example:
Base class constructor called.
Derived class constructor called.
Derived class destructor called.
Base class destructor called.
some were assigned. After
Program Explanation: In this program, however, y values
x 5 and has the value of 6.
both constructors are called, has the value of
You should notice that in the class declaration, the base class,
Base, requires the
you ensure that the base
parameter int y. Since two parameters are used in Derived (),
Class is passed the necessary parameters by using
the declaration (assuming that
parameter2 is the base class argument):
derived_class(type parameter1, type parameter2, .):
base_class(parameter2)

I/ body of derived constructor


C++ Programm
90

Granting Access
access level of inherited members of a derived
There are two ways to change the
class. The first method is a recent development in the world of C++, and it has way
become the new standard. This new standard is the using declaration. The second
to change an access level is to use access declarations..
access declarations
The following base and derived class declarations show how
work:
class Base

public: int a;
};
class Derived : private Base

public: Base :: a;

Even though, by default, a is inherited by Derived as private, the access


declaration
Base :: a; changes a's level of access to public.

3.16 USE OF VIRTUAL IN C++ (Dynamic polymorphism)

Virtual Base Classes


Think about the following situation: a class named Base is declared. Then, two
classes are derived from that original: Derived1 and Derived2. Next, yet another new
class is declared -- a derivative of both Derived1 and Derived2 -- Derived3. Looking
at this situation, if a variable from the original class, Base, is called in association
with Derived3, what willhappen?
There are essentially two copies of Base in Derived3: the one inherited from
Derived1, and the one inherited from Derived2. If Derived3 tries to reference a
variable in Base, an error will occur. To prevent an extra copy of Base from being
created during the declaration of Derived3, we use virtual base classes.
The following class declarations clarify the situation described above. Notice the use
of the keyword virtual in the declaration of the derived classes:

class Base

public:
int a;

class Derived1: virtual public Base

public: int b;
};
C++ Programming 91

class Derived2: virtual public Base

public: int c;
class Derived3: public Derived1, public Derived2

public: int d;

There is only one difference between a virtual class and a "normal" class. If
a virtual base class is inherited more than once by the same class, only one copy of it
will be present. If a "normal" class is inherited more than once by the same class,
multiple copies of it will be present in the derived class. Thus virtual base class
prevents inheriting multiple copies of same base class members

3.17 INHERITANCE CONFLICTS


Member Conflicts
O Name conflicts can occur same member name from more thanone
-

base class
Derivedclass can overshadow base class members name
Use scope resolution operator to resolve conflicts
Multiple Inheritance Conflicts
copy of a member
O
Derived class may combine more than one
copy of a member
Base class may combine more than one
When to use virtual members of a member of
a derived class extends the functionality
Make member'virtual' ifa Make a
member
the base class, and this extended functionality has to be accessible.
an object of the derived
'virtual' ---1.inside other member functions of the base class
class.
to an object of the derived class.
2.When using pointers that can point
ambiguity is resolved at the
Virtual function supports runtime polymorphism since
run time ,so it is also called as RTTI(Run Time Type
Identification)

Polymorphism: user should know types of


Before going for polymorphism, are going in details of that one
polymorphism.The types are as given indiagram. We
by one in later part of chapter.
Polymorphism

Run time Polymorphism


Compile time Polymorphism

Virtual functions
Function overloading Öperator overloading
92 C++ Programm

Virtual functions:

Keyword virtual only appears in the base class, all classes that derive this class
will have the corresponding method automatically declared virtual by the system.
The structure of the virtual function in the base class and each of the derived classes
is identical. The return type and the number and types of the parameters must be
identical for all since a single statement can be used to call any of them.
If the keyword virtual is used, the system will use late binding,which is done at run
time, but if the keyword is not included, early binding will be used. In early binding
which function to be executed is decided at compile time so it will execute the
function in base class only. In late binding that is decided at run time so it will
execute appropriate function from derived class. In late binding it decides function
according to contents of pointer while in early it decides function execution according
to type of pointer.

Example 15: Following example illustrates the use of virtual function.


#include<iostream.h>
class Base
{

public: void display){ cout<<"In Base";


class Derived1: public Base

public: void display){ cout<<"In Derived1";


class Derived2: public Base
{
public: void display0{ cout<<"In Derived2":
};
void main( )

Derived1 objl;
Derived2 obj2;
Base *ptr;
ptr=&objl;
ptr->display0;
ptr=&obj2;
ptr->display0;
};

Output is :-- In Base


In Base
C++ Programming 93

Why so???7?Here, compiler ignores the contents of pointer and chooses the
member function matching with the type of pointer. (and since pointer is of
base type), Base class function is called.
Thus it can't solve the problem of accessing objects of different classes using
same statement.

The solution is to use virtual function.

#include<iostream.h>
class Base
{

public: virtual void display0{ cout<<"In Base";

class Derived1: public Base

public: void display0{ cout<<"In Derived1";

class Derived2: public Base


{

public: void display0{ cout<<"n Derived2";


void main)

Derived1 objl;
Derived2 obj2;
Base *ptr;
ptr=&objl;
ptr->display0;
ptr=&obj2;
ptr->display0;
}

Now output is: --In Derived1


In Derived2
Thus, here member function of the respective derived classes is executed. So here
same function call(ptr->display():)executes different functions, depending upon the
contents of ptr to which it is pointing currently and not on its type(i.e. of base).

as pointing to a base class can be


NOTE: Pointer rule in C++:--A pointer declared a pointer to a
used to point to an object of a derived class of that base class, but
an object of the base class or to any of the
derived class cannot be used to point to
other derived classes of the base class.
94 C++ Programm

Characteristics (Rules) of virtual function:-


1
The virtual functions must be member of some class.
2.They can't be static members.
3.0bject pointers can access them.
4.A virtual function in the base class must be defined, even though may not be
it
used.
5.Prototype declaration for the virtual function in base and derived
same. Since if they are different, class must be
it will not be virtual function but compiler will treat
it as a function overloading.
6.Virtual constructors are not possible, but virtual
destructors are...
7.They can be friend of other class.
8.You cannot use a pointer to a derived class to access
base class object.
9.Base class pointer can be incremented or
type, and it can't point to next decremented only relative to its base
object of the derived class.
10.If virtual function is not defined
in the derived one, function
is called. of the base class
11.Empty Virtual function defined
in the base class is called as pure
function virtual
e.g. virtual void display(void) = 0;
12.A class declared to have pure
virtual function
of that class can't be created. Such a couldn't be instantiated. That
means objects
class class is called as abstract base
13.Virtual functions supports
runtime polymorphism
Identification.) (RTTIi.e. Run Time Type
Pure virtual function and abstract
class Base class

public: virtual void display()=0;


}: Ilpure virtual function.
class Derived1: public
Base
public: void display0{
cout<<"In Derived1";
}
class Derived2:
public Base
public: void display){
cout<<"In Derived2";
void main)
C++ Programming 95
Derived 1 objl;
Derived2 obj2;
Base *ptr[2];
ptr[0]=&objl;
ptr[0]-->display 0;
ptr[1]=&obj2;
ptr[1]-->display);
}

Output is: In Derived1


In Derived2

Here virtual function is derived as virtual void display 0=0; The equal to sign here
has nothing to do with assignment, also value O is not assigned to anything...
But the (= 0) syntax is simply, to tell the compiler that a function is pure(i.e. having
no body).
But if you remove the body of the virtual function in base class, why can't we remove
the function altogether? Since it doesn't work otherwise. So here base class, Base is
considered to be as an abstract class. Abstract class is often defined as one, that will
not be used to create any objects, but exists only as a base class of other classes.i.e. in
above program if youcreate object of the base class to call its function(like Base obj;
and obj.display();)it will lead to compiler error---since abstract class can't be
instantiated.
The class to be called as abstract, a class must contain atleast one pure virtual
function.
EXERCISE
1) Write a program in C++ for the following Inheritance structure:
Shpe
Triangle Pectangle

2) Write a program in C++ to accept and display for the following Inheritance
structure: Roll No.)
Student (Name,

Art (stream,Div) 3cience Commerce


(Bream,type) (Gream,elective)

Medical Enggineeing
(CEISore ,Div) (PCM &ore, stream, name)

S) Using virtual function calculate the


area of triangle and rectangle.
96 C++ Programn
3.18 FRIENDS IN C++
It is sometimes useful to let the functions of one class have access to
the component
of another class without making the components public and without the overhead ot
having to call member functions to get private data, in this case
friends are usefi
Friend functions or classes have full access to
the public, protected, and private
members of any class for which they have been declared as
friends. The definition of
the friend function may or may not be included in the
file containing the definitions
for the class's member functions
Friends can be either functions or other classes.
A class grants access privileges to it;
friends. They provide a degree of freedom in
the interface design options. The major
difference is that a friend function is called like f(x),
while a member function is
called like x.f).
Derived classes of a friend aren't necessarily friends.
DEF is a friend, classes derived from DEF
If class ABCdeclares that class
don't have any automatic special access
rights to ABCobjects. A friend may be a non-member
function, a member function of
another class, or an entire class. The difference between
Friends and derived classes
is that derived classes might not be able to access
all the members of the base class
while Friends can access.
The privileges of friendship aren't transitive. A
friend of a friend isn't necessarily a
friend. If class ABC declares class XYZ as a
friend, and class XYZ declares class
LMN as a friend, class LMN doesn't necessarily have any special access
ABC objects rights to
The privileges of friendship aren't reciprocal.
a friend, XYZ objects have If class ABC declares that class XYZ is
special access to ABC objects but ABC
automatically have special access to XYZ objects do not
objects.
Therefore it is true, even in C++
that “friendship isn't inherited, or
reciprocal" transitive,

Friend class
One can also declare a whole class to a
be friend of another class. This allows
member functions of the friend class to all
have full access to all the members
other class. of the
Syntax: --friend some-class-name;
Where this line is placed inside a class
declaration and 'some-class-name'
of a class known in the file holding the class is the name
one class (in this case declaration The following shows how
DEF) can let another class (in this case ABC) a
class be friend'"

#include<iostream.h>
class A
{

private: int data;


public: A()
C++ Programming 97

data=100;

friend class B;
};
class B

public : void friendclass(A aobj)

cout<<"value of data is:"<<aobj.data;

void main ()

B obj;
A objl;
obj.friendclass (obj1);

Output is: value of data is: 100


we are accessing
Program Explanation: In this case we have used friend class, here
function.
private member of class A through its object from within class B's member

Friend function:
C++ allows us to make common function friendly to the both classes,
thereby
allowing function to have access to the private data. Also
function need not be
uses keyword friend, but functipn
member function of the class. Function declaration
a any number of
definition need not. Also function can be declared to be friend of
are unrelated (not following inheritance
classes. So if two or more classes
relationship,), friend function acts as bridge between them.
a

e.g. class B;

#include<iostream.h>
class B;
class A

private: int data;


public:
A0{ data=100;
friend int friendfunction(A,B);

class B
98 C++ Programm,

private: int data;


public: B) { data=50; }
friend int friendfunction (A aobj,B bobj);
};

int friendfunction (A aobj,B bob)


{

return (aobj.data+bobj.data);

void main()

A objl;
B obj2;
cout<<friendfunction(objl,obj2);
}

Output is: 150.


Thus if we want a function to operate on objects of two different classes, (2 objects,of
different classes, operating on their private data), friend function is used.

Exercise: Writer a program in C++ to swap private data values in two classes
using friend function.(Assume single integer data member )

3.19 OPERATOR OVERLOADING


We are already familiar with one of the ways to implement compile time
polymorphism by means of function overloading. Other way is operator overloading.
Operators are similar to functions in that they take operands (arguments) and return a
value. Most of the built-in C++ operators are already overloaded. For
example, the +
operator can be used to add two integers, two reals, or two addresses. Therefore, it
has multiple definitions. But the built-in definitions of the operators are
restricted to
built-in types. The programmer can provide additional definitions, so that they can
also operate on user-defined types. Each additional definition is implemented by a
function C++ allows the programmer to define additional
meanings for its
predefined operators by overloading them.
C++ places a number of restrictions on operator overloading.
Only the pre
defined set of C++ operators may be overloaded. It is illegal to
define a new operator
and then overload it. The meaning of an operator must
also be preserved. You cannot
turn a unary operator into a binary operator or vice versa.
and they should follow
syntax rules of the original operators. The overloaded
operator must have at least one
of the operands that is of the user-defined type.
C++ Programming 99
Most computer languages do some overloading of operators as part
of the language
itself. It is possible, however, in C++ for programmers themselves to re-define the
meaning of C++ operatOrs as long as at least one of the operands is an instance of a
class
Here area few of the many examples of operator overloading:
String1+ String2 are used to concatenate two standard String objects
Date+t increment a Date object
Number 1* Number2 multiply two Number
objects
arr[i] access an element of an Array object

Defining an Overloaded Operator


Thus to define an additional task to an operator, we must specify what it means in
relation to the class to which the operator is applied., so you can include this task in
operator's function body. The code itself for an overloaded operator depends on what
the programmer wants to happen.

Syntax: returntype classname :: operator oper(parameter list)

function body

The word 'operator' is a keyword, followed by the operator symbol and you specify
operands as parameters. So this is called as function operators or operator
functions.
The number of arguments (operands) found in an overload declaration depends on
whether the operator function is declared as a friend or member function(non static)
of the class. (It must be one of the two in order to have access to the members of the
class.)
A basic difference between them is that a friend function will have only one
a
argument for unary operators and two for binary operators. While member function
has no arguments for unary operators and only one for binary operators. Arguments
can be passed by value or by reference.
Since object used to invoke the member function is passed implicitly and therefore
is
it is declared as
available to member function, so it requires one argument less than if
friend function.

Steps for overloading operator:


you
the class definition in which operator is to be overloaded, for that
1.Write
1equire operator function, where
you write the actual code ,you want to execute with
the overloaded operator.
as a member function or as a friend function
2.Declare that operator function
on number of arguments that operator is going to take. Also include this in
epending
ne public section of the class.
100 C++ Programn

3.Now give definition of the operator function, in which you give additional
meaning/task to the existing operator.
4.Now invoke overloaded operator,
It is invoked by oper obj; Or obj oper
Where obj is user defined data type(may be instance of the class in which operator
function is defined) and oper is actual operator to be overloaded.This is to be done if
it is unary operator. While if it is binary operator, it can be invoked like,
operator oper (obj1,obj2) if it is a friend function
and objl.operator oper(obj2) if it is a memberfunction

Important Note:

Overloadable Operators
Unary: + & ++

new delete
Binary: + 9%
<< >>
-=|=|%= &= <K=|>>=
&& )
When the compiler encounters an operator it is converted
into an appropriate function
call.
But note that following operators cannot
be overloaded: scope operator (::), member
object selection operator (.*), class object selector operator
conditional operator (?:).and sizeof operator.Operators are (), and the arithmetic
also not allowed to have
default arguments.
Also a strictly unary operator (e.g., ~) cannot
a strictly binary operator (e.g., be overloaded as binary, nor can
as
) be overloaded unary.
C++ does not support the definition of new operator
lead to ambiguity. Furthermore, the precedence tokens, because this can
rules for the predefined operators are
fixed and cannot be altered. For example, no
matter how you overload *, it will
always have a higher precedence than +.
Operators ++ and -- can be overloaded as
prefix as well as postfix.

Example 16: Following example illustrates


how to overload unary
operator(unary minus);-

#include<iostream.h>
class ABC

int nol,no2;
public: void getnumbers(int a,int b);
void display(void);
C++ Programming 101
void operator -();
};
void ABC:getnumbers(int a,int b)

nol=a;
no2=b;

void ABC::display(void)

cout<<no1<<endl;
cout<<no2<<endl;
void ABC::operator -()
{

nol= -nol;
no2= -no2;

void main( )

ABC obj;
obj-getnumbers(3,-5);
cout<<"Before overloading:"";
obj.display( );
-obj;
cout<<"After overloading:";
obj.display( );

Output: Before overloading: 3,-5


After overloading: -3,5
In this case we are overloading unary operator, since this is
Program Explanation: as member function, this operator
unary operator to be overloaded, and defined
any argument. When you define statement (- ob ;),it in turn
function doesn't take
negatingthe original number.
invokes operator function, which is

Following example illustrates how to overload binary


Example 17: objects.)
operator(+operator to concatenate 2 string

#include<string.h>
#include<iostream.h>
class String

private:
int size;
102 C++ Programmi

char str[80];
int nol,no2;
public: String)

strcpy(str," "); lldefault constructor


}

String(char s[])

strcpy(str,s);

void display(void)
{

cout<<str<<endl;
}
String operator + (String sl)

if(strlen(str)+strlen(s1.str))<size)

String temp;
strcpy(temp.str,str);
strcat(temp.str,s1.str);
return temp;
else
cout<<"Be cautious!!!!String overflows!!!!";
};
void main( )

String objl="HI";
String ob2="HELLO";
String obj3;
obj1.display( );
obj2.display( );
obj3=obj1+obj2;
obj3.display( );
}

Output is: HI
HELLO
HIHELLO
Program Explanation:- Here we have overloaded
binary + operator to concatenate 2
strings .Here string objects are user-defined
and + operator operates on them, since in
C++ Programming 103
the operator function definition, we have concatenated 2 strings,
after adding them
they are concatenated to each other, i.e second string is appended to the first one
Statement obj3=objl+obj2 invokes this operator function. Since you want the citect
of concatenation in obj3,which is a string object, your operator function must return
the object(i.e. class type),therefore return type of this operator function is classtype i.e
String.
Dealing with fractions with the operator overloading..-
This program overloads binary + and/ operators to give addition and division of 2
fractions.

#include <iostream.h>
class fraction

private: float n, d;
public: fraction)

n=1;
d=1;

fraction operator +(fraction); I/Operator for adding fractions


fraction operator /fraction); I/Operator for dividing same
void getfr(void);
void printfr(void);

fraction fraction::operator +(fraction f2)

fraction r;
r.n n2.d+d*f2.n;
=

r.d = d*f2.d;
return (r);

fraction fraction::operator 1(fraction f2)


{

fractionr;
r.n =n*f2.d;
r.d= d*f2.n;
return (r);
void fraction::getfr(void)

cout <"\nEnter the numerator -->";


cin >> n;
cout << "Enter the denominator->";
104
C++ Program

cin >> d;

void fraction:printfr(void)

long double r;
r=long double(n/d); .

cout <<n<«
"" <«d<<"="<<r<<" ":

void main)

fraction f1, f2, f3, f4;


fl.getfr0;
f2.getfr0;
f3 = f1+f2;
f4= f1/f2;
cout << "nFraction 1\t-->";
fl.printfr);
cout << "nFraction 2\t--";
2.printfr);
cout <<"nSum\t\t-->";
f3.printfr0;
cout <<"nDivision\t-->";
f4.printfr0;
cout << endl;

Output is : Enter the numerator -->2


Enter the denominator-->5
Enter the numerator -->4
Enter the denominator-->5
Fractionl -->2/5 =0.4
Fraction 2 -->4/5 = 0.8
Sum -->30/25 = 1.2
Division -->10/20=0.5

2) Write a program
EXERCISE
in C++ to overload increment
3) Write a program in C++ to operation.
overload t, ,/,and * for addition,
subtraction division and multiplication
program using both type of two complex numbers.(Write a
of funct friend and member function).
3.20 TYPE CONVERSIONS
When constant and variables
of different type are mixed in an expressioD
compiler applies rules of automatic type
conversion.
Assignment operator also causes
automatic Type Conversion.
C++ Programming 105
Type of the data on right hand side of an assignment operator is automatically
converted to the variable on left.
int a ;
float b
=3.3346:
a=b;
It converts float to integer. Here fractional part is truncated. Thus type
conversion is automatic for built in data types.
Now consider,
obj = objl + obj2;
Now if obj, objl & obj2 are of class type objects, compiler- will carry out this
operation without any objection but it will give error, when one of it is basic data
type. Here compiler doesn't support automatic conversion. Thus we have to have
conversion routines for:
a) Conversion from built-in to class type.
b) Conversion from class type to built-in type.
c) Conversion from one class type to another class type.

> From Basic to user defined


The constructor can be used from argument type to constructor's class type
string: : string (char * a)
{
len = strlen (a);
p= new char (len + 1):
strcpy (p, a);

This constructor builds a string type object from a char * type variable a.
This constructor can be used for conversion from char * type to string type.
eg. strl = string (name 1)
So it converts namel from char * type to string type and then assigns it to object.

> From User defined to built in


Syntax : operator type name (O

fun
statements

This fun converts a class type data to type name.


eg. ABC :: operator float ()

float result = 0;
for (int cnt = 0; cnt < size; cnt++)
result = result * cnt;
return result;
C++ Programm
106

This converts a ABC obj to corresponding scalar variable.


Here you can have
float a = obj;
Where obj is of type ABC.
we can have
By overloading casting operator in the fun (conversion fun)
translation from class to basic type but conversion fun must satisfy conditions
as
1) It must be defined as a class member
2) Must not specify a return value
3) Must not have any arguments
Example 18: Conversion between strings ( char array ) and string objects.
# include <iostream.h>
#include <string.h>
const int size = 80;
class string

private:
char str [size];
public:
string ()
{

str[0] = "\0';

string (char s [1) llconverts str to string (basic àclass)

strcpy (str, s);

void display()

cout << str;

operator char*() I/ conversion fun


return str; llconverts string to char* (classàbasic)

};
void main( )
{

string objl;
char newstr[] ="nHI ";
objl = newstr;
obj1.display( );
string obj2 ="WELCOME";
RCout << obj2; I/ uses conversion function to convert string to
I| char array before sending to <<operator
C++ Programming 107

Output is: HI WELCOME

Program Explanation: Here one argument constructor converts a normal string


(char array)to object of class string.
This conversion is applied when a string is created as ;
string obj2 = "WELCOME";
Or it will be applied in assignment statement as
objl = newstr;
While conversion fun is used to convert from a string class type to a normal
string.
operator char *( )
eg.

return str;
This conversion fun is used by compiler in statement, cout << obj2;
Here obj2 is an argument supplied to the overloaded operator << & as << operator
doesn't know anything about user define string type, compiler looks for a way to
.
convert obj2 to type that here << is used to display str(string) & not object
It finds out conversion fun & uses it to generate a normal string. Which is then
sentto calling string:: display () fun.

Conversion between Objects of different classes;


Here you can use a one-argument constructor or you can use a
conversion fun. Choice depends upon whether you want to put the conversion routine
in the class specifier of the source object or of the destination object.
eg. if you say
objA = objB;

member of class A member of class B.

(destination) (source)
We can put conversion routine in either destination
or source class.

Type Routine in Routine in1


Conversion: destination SOurce

Basic to Basic (built in conversion functions)


Basic to Class Constructor NA

Class to Basic NA Conversion


function
Class to Class Constructor Conversion
function
108

From Class to Class: converted to other (object of other class)


can also be
Objects of one class
conversion routine carries out this conversion.
Writing to
convert object of one class
program illustrates how to
Example 19: Following
other.
#include<iostreanm.h>
#include<math.h>
class polar

private:
double radius;
double angle;
public:
polar ( )

radius = 0.0;
angle = 0.0;

polar (double r, double a)

radius =r;
angle = a;

void display ( )

cout <<"'Radius="'<Kradius<<"\t"< "Angle='" <<angle;

double getr ( )

return radius;

double geta ( )

return angle;

class rec
{

private:
double xcord;
double ycord;
public:
C++ Programming 109
rec ( )

xcord = 0.0;
ycord = 0.0;
rec(double x, double y)

xCord = X;
ycord = y;

rec (polar p) llconversion routine 1)

float r p.getr ();


float = p.geta 0;
a

Xcord r* cos (a);


ycord = r*
sin (a);

void display ()

cout <<"X-coordinate=" <«xcord <<"n"<< "Y-coordinate= "


<< ycord;

void main ()

rec reccord;
polar polcoord (10.0, 0.7855398);
reccord = polcoord;
cout <<"nPolar coordinates:\n";
polcoord.display ( );
cout<<"nRectangular Coordinates: \n";
reccord.display ( );

Output: - Polar coordinates


Radius=10 Angle=0.785398
Rectangular coordinates
X=coordinate=7.07107
Y=coordinate=7.07107
constructors
Program Explanation: Here, conversion routine 1) is 1-arg
a member to the rectangular co
This function sets the object of which it is
as an argument.
ordinates that corresponds to polar co-ordinates of the object received
C++ Program
110

3.21 FILES AND STREAMS


name given to the flow of data.
A stream is a general
data flow.
Different streams are used to represent different kinds of
Each stream is associated with a particular class, containing
member function
data.
and definitions for dealing with that particular flow of
e.g. Extraction operator >> is a member of istream class while insertion
are derived from
operator <« is a member ostream class and both of these classes
ios class.
ifstream represents i/p disk files.

Stream class hierarchy:


ios

istream ostream

fstreambase ofstream

ifstream iostream fstream

Classes used for i/p and ofp to the video display and keyboard are declared in

header file, iostream.h while classes used for file I/O are declared in the file fstream.h

Destination Disk file Source


I/O
output insertion(<<) intput extracrtion(>>)
put ( ),write( ). get (),read().
[ofstream] [ifstream]

Program
Header Files
ifstream ofstream and fstream classes are declared in the header file,
fstream.h. These files also include iostream.h, so there is no need to include
explicitly, since fstream.h takes call of all stream I/O.

String /O
I/ o/ps same strings to a file

# include<fstream.h>
void main ()

ofstream f1("'test.doc'");
C++ Programming 111

fl<<"HI'";
fl<<"Hello'";

When the program terminates, fl object of ofstream class, goes out of scope, which in
turn calls the destructor, which closes the file. So here we don't need to close the file
explicitly. So when you run this program, lines/strings specified, are written to the file
and there is no o/p in the screen.

Reading Strings
To read the same file, we must create an object of class ifstream.

#include<fstream.h>
void main( )
{
const int MAX = 80;
char buffer [MAX];
ifstream f1("test.txt");
while (f1)
{
fl.getline (buffer, MAX);
cout<<buffer;

we read the text fromn the


Here the insertion operator doesn't work, but instead
file, one line at a time using getline () function.
places the
This function reads the characters until it encounters n' character and
as an argument and contents of the buffer are
resulting string in the buffer supplied
displayed after each line.

Detecting EOF (End Of file)


a can be tested for various error
An ifstream object (f1 here) hàs valuea that
otherwise non-zero. One of
conditions.If a condition is true, object returns 0 value,
a sent to the program from
these conditions is end of file (EOF).The EOF is signal
Nw, when a read or write operation has
reached to the end of the file.
while loop so that it can stop reading
The program checks for the EOF in the
a stream pointer is actually a pointer, but
after the last string. The value returned by
returned has no significance except to be tested fora O/non-zero value.
the address

Character I/O are members of istream & ostream


Get ( ) & put () functions, which
single character of a time
respectively are used to i/p & olp
C++ Programn
112

Example 20: File output ,with characters.

# include <fstream.h>
#include< string.h>
void main)
{

char arr[ ]= HI& Welcomeln";


ofstream fl(Test. txt");
for (int i=0, i <strlen(arr), i++)
fl.put (arr[il);

File input ,with characters.


#include < fstream.h>
void main ()

char ch;
ifstream f1 (Test.txt);
while (f1)
{

fl.get (ch); Il read char.


}
cout<<ch; Il display
}

is
This program uses get function & continues reading it until end of file,
( )
encountered. And each character read from the file is displayed using cout.

3.22 FILES HANDLING IN C++


In real life probiems, we need to handle large amount of data. For this we

need to use some devices like floppy disk/hard disk to store the data. This data is

stored in this device using the concept of files.


file is a collection of related data stored on the disk.
A

Programs can be designed to perform read &write operation on these files.

Opening & closing the file :


Syntax: File-stream-class stream object;
stream object open (“file name");

ifstream class is used to read a stream of object from a file & ofstream class is ust
to write a stream of objects in a file.
e.g. ifstream fobj;
fobj. open (data.txt");
113
File modes :
With class fstream we need to
specify file mode.
General form of function open
() with a arguments is: --
stream-object.open (“file_name",
mode);
The file mode can take any parameter
of the list: -
Parameter Meaning
1. :
ios app
Append to the end of file
:
2. ios ate
Go to the end of file an opening.
3, ios :: binary
4. ios ::
Binary file
in Open file for
:: reading only.
5. ios nocreate
Open fails if the file doesn't exist.
6. ios :: noreplace
Open fails if the file already exists.
7. ios :: out
Open file for writing only
8. ios :: trunc
Delete contents at the file if it exists.

Mode can combine two or more operators using


e.g, fout.open ("data", bitwise OR operator.
ios ::appl ios nocreate);
::
This opens a file named data in the append mode but fails to open
the file if it
doesn't exists.
For ifstream, default mode is ios::in & for ofstream, the
default mode is
ios::out. For fstream, there is no default mode.

> closing a file -


function close (0 is used to close a file, which is opened for read,
write
operations.
It is callèd automatically, by destructor function. It can be called explicitly.
E.g.infile.close();

Binary Files:
In C++ by default the file stream operations are performed in text mode but
we can store data in binary form. The functions write) and read) are used for this
purpose. The forms of these functions are as follows:

in.read(char*)&V,sizeof (V);
out.write(char*) &V,sizeof (V);
These functions take two arguments:
i) Address of variable V
iü) Length of that variable in bytes

Example 21:
#include<fstream.h>
class A
C++ Program
114

protected : char name[40];


int age;
public :
void getdata ()

cout <<"Enter Name :";


cin >> name ;
cout <<''enter age:";
cin >> age;

void display)

cout<<"'name is:"<<name;
cout<<"\nage is:"<cage;

void main )

A obj;
obj. getdata0;
ofstream fl ("ABC.dat");
f1. write ((char *) & obj,
sizeof (ob)) ;
obj.display0;

Output:
Enter Name :smita
enter age:23
name is:smita
age is:23
Press any key to continue
write function takes two arguments:
1. Address of the object to be written.
2. Length of the objects in bytes.
3. We have used size of operator to find the length of object 0

class.
4. Here the address of the object
5. Must be cast to type pointer to char.
C++ Programming 115

File Pointers:
Begin End

Positíor
file pointer.

Each file object has associated with it, 2 integer values called get pointer &
put pointer. These are also called current get position & current put position pointers.
These values specify the byte number in the file where writing and reading takes
place:
so
There is some situation, when user must take control of the file pointers
that you can read from & write to an arbitrary location in the file.
e.g.seekg( ) and tellg( ) function, allow you to set & examining the get pointers, and
the seekp( ) and tellp( ) function perform these same actions on the put pointer.

Specifying the position


so that reading
Seekg ( ) function set the pointer to the beginning of the file
would start there.
This form of seekg) takes one argument which represents the absolute
position in the file.The start of the file is zero.

Specifying the offset


seekg( ) function can be used in two ways.
1) One, where the single argument represents the position.
an
2) You can also use it with two arguments where the first argument represents
on
offset from a particular location in the file & the 2d specifies the location
which offset is measured. There are 3 possibilities for the 2" argument:
beg -beginning of the file
cur- is the cement, pointer position
end - is the end of the file

eg. seekg (-10, ios:: end)


It will set the put pointer to 10 bytes before
the end of the file.

:
seekg( ) fun with two arguments

Begin End

Offset from end


Offset from begin
116 C+t Prograr
Example 22: Program for file manipulation
# include <fstream.h>
# include <stdlib.h>
void main()

const int SIZE = 80;


char line [SIZE];

ofstream fout;
fout.open("country");
fout <<"United States of Americaln";
fout <<"United Kingdom In'";
fout << "South Korea n";
fout << "India In";
fout << "Pakistan n";
fout.close);

fout.open("capital");
fout << "Washington D.C.n";
fout << "Londonn";
fout << "Seoulln'";
fout <<'"New Delhin'";
fout << "Islamabad\n'"';
fout.close0;

ifstream finl, fin2;


fin1.open("country");
fin2.open("capital");
cout <<"Country\t\t\AtCapitalInn"';
for (inti=1;i<=10; i++)

if(fin1.eof) != 0)

cout <<"Exit from country


\n'";
exit(1);

finl.getline(line, SIZE);
cout << line << "\t";
if(fin2.eof) !=0)

cout <<"Exit from


Capital\n'";
exit(1);
C++ Programming
117
fin2.getline(line, SIZE);
cout << line << "n";

Output is:
Country Capital
United States of America Washington D.C.
United Kingdom London
South Korea Seoul
India New Delhi
Pakistan Islamabad
Exit from country

Command -line arguments:


Used when invoking a program from Dos.
They are typically used to pass the name of a data file to an application.
E.g. void main (int argc, char* arg[0)

cout <<nNumber of arguments are:<< argc;


for(int i-0;i<argc; it+)
cout<<"\nArgument << i<<"K argv [i];

Output when run from the command line is: -.


c:>Progl HI Hello Welcome
Number of arguments are: 4.
argument 0= c:/cpp/ch14/.../Prog1.exe (specifies complete path)
argument -H1

argument 2 = Hello
argument 3 =Welcome

To read the command line arguments, the main () function itself must be given two
arguments.
First is argc. (for argument count) which represents total number of command-line
arguments.
The first command-line argument is always the pathname of the current program.
Remaining command-line arguments, are those typed by the user, are delimited by
space character
an array
System stores the command-line arguments as strings in memory & creates
of pointers to this string.
so the first string
Individual string are accessed through appropriate pointer
so on...
(pathname ) is argvl0], second is argv [1] and
118 C++ Programmi

SOLVED PROGRAMS
(1) Write the power () function in C++ that returns x raised to the power n, where n
can be any integer, double power (double x, int p);
Use algorithm that would compute x"by multiplying 1 by x 20 times. (March 2002)
Solution:
#include<iostream.h>
double pow (double, int) ;

void main ( )

double x;
int n;
cin >> X>> n;
cout <<x<K"'raised to'"<<n <"="«pow (x, n) <K endl;

double pow (double x, int n)

if (x==0)
return 0;
if (n==0)
return l;
double y = 1;
for (int i =0;i<n; it+)
y *= X ;
=
for (i 0;i>n;i--)
y = x;
return y;
Output is:
2

2 raised to 3 =8

(2) Write a C++ program to find the greatest common divisor of two numbers.
Define a method find to accept the values and calculate GCD of twonumbers and
print the GCD value. (March 2002)
Solution:
# include<iostream.h>
class ged

int a, b;
public
void find();
C++ Programming 119

void gcd : find (void)

cin >> >>b;


a

while (a != b)

if (a > b)
a -= b;
if (b> a)
b-=a;
}

Cout << a;

void main ()

gcd obj;
cb. find ();
Output is:
15
25

a text and count the number of words


(3} Write a C++ program that will read line of
(March 2002)
in a text.
Solution: •
# include <iostream h>
# include <string h>
void main ()

int i, len, w = 0;
char line [80];
cin. getline (line, 80);
len = strlen (line);
for (i = 0; i < len; i ++)
if (line [i] ==')
W ++;

cout <K words = <w + 1;

Output: Today is Monday


:3
120 C++ Programn

QUESTIONS
1. Select the correct alternatives
1) Following is not the feature of OOPs
a). Polymorphism b) Inheritance c). Data abstraction d) None of the above.
2) Following operator can't be overloaded:
a) ++ b) :: c) - d) *
3) A mechanism, which automatically destroys" an object when it gets invalid is
a) constructor b) destructor. c). object d) member function
4) Which of the following allows to acceess the private data of other function?
a) Inline function b) Friend function c) main function d) All of the above.
5) Object is defined as:
a) Instance of a class b) "black box" which receives and sends messages.
c) Both of the above. d). None of the above.
6) C++ provides:
a). single inheritance b) multiple inheritance
c) multilevel inheritance d) All of the above
7) A structure is a class all of whose members are by default
a) public b).private c)protected d) none of the above.
8) Which of the following is not a feature of Object Oriented Programming
a)Follows bottom-up approach (Mar.2004)
b)Object may communicate with each other through functions
c) Follows top-down approach in design d) Programs are divided into
what are
known as objects.
9) The ability to take more than one form is called in object
oriented programming.
(Oct.2003)
a) inheritance, b) encapsulation, c) polymorphism, d) data abstraction.
10) is not a derived data type in C++. (Mar.2005)
a) Class b) Array c) Function d) Pointer
11) A derived class with several base classes is inheritance.
a) single b) multiple c) multilevel d) hierarchical (Mar.2006,09)
12) Which of the following allows to access the private data of other class is
a) In-line function b) Friend function (Mar.2007)
c) Main function d) All of the above
13) Following operator cannot be overloaded
(Mar.2008)
a) ++ b) :: c) - d) *
C++ Programming 121
1
For a=23 and b=3 the value of c after execution of c=(a/b)*(a%/b)is
a) 14 b) 49 c) 21 d)69 (Mar.2010)
15) In C++ double type data consumes
bytes in memory (Mar. 2016)
a) 2 b) 4 c) 6 )8
16) If all visibility labels are missing then by default members
of class are
a) public b) private c)protected d) Void (Mar. 2017)
17)What will be the value of x
after execution of following expression in C?
X=++ m +n +; where = 10 and n = 15.
+ m
(Mar. 2019)
a) 25, b) 27, c) 26, d) 28
18) operator cannot be overloaded. (Mar. 2020)
a) ++ b) + c):: d) >>

THEORY QUESTIONS
1. What is C++ ? write advantages of C++. (Mar.2003)
2. Explain the difference between procedural programming and object oriented
programming. (Specimen Paper)
3. Write any six main advantages of O0Ps. (Mar.2003)
4. Explain classes and objects.
5. What is resemblance between arrays and pointers?
6. Why references are used?
7. What is difference between class and structure? (Specimen Paper)
8. What is runtime and compile time polymorphism? How it is achieved?
(Specimen Paper)
9. What is operator function? Describe the syntax of operator function. (Mar. 2017)
10. Explain the difference between operator function as amember function and as a

Friend function. (March 2002,2016)


11. Explain difference in function overloading and function overriding.
12. Explain vitual function. Why it is necessary?
13. State any 8 characteristics of virtual functions. (March 2002)
14. Explain difference between nested classes and derived classes.
15, What is class? Give general form of class declaration. (Mar.2003)
16. State characteristics of friend function (March 2016,2017)
17. Explain constructor and destructor with example. (March 2002)
18. What is a Constructor in C++? With a suitable example explain how a constructor

is declared and defined. (March 2005)


a C++.
19. Explain how memory address of variable is accessed in
(Model Paper, Mar.04)
122
an operator. (Model Paper)
20. Why there is necessity of overloading
a diagram, the file input and file output streams in C++.(Mar.2006)
21. Explain with
22. Enlist the basic data types used in C++
with size of data in terms of bytes for
(March 2006)
each.
a variable can be accessed in C++.
23. Explain how the memory address of
(March 2007)
use of pointer variables for function
24. What are pointers in C++? Explain the
definition using call by value and call by reference.
(March 2007,08,09,19)
25. What is the function of each of the following file
stream classes?
i) ifstream ii) ofstream iii) filebuf ++. (March 2008,2020)
26. What is inheritance in C++? What
are different forms of inheritance? Give
example for each. (Mar.2003)
27. What is the difference betwèen function overloading and function overriding?
28. What is runtime and compile time polymorphism? How it is
achieved?
(Specimen Paper)
process of
29. What is operator overloading? State the three steps involved in the
overloading. (Mar.2003,20)
30. What is a Constructor nd a Destructor? Give one example for each.
(Mar.2006,09,2020)
31.What are Destructors?Write the rules for writing destructor function. (Mar.2009)
32. Explain Runtime and Compile time polymorphism? Give any one example.
(Mar.2009,2017)
33. State any six characteristics of constructor function. (Mar.2003,2016,2019)
34. Explain the use of scope resolution operator and memory management operators
in C++ with examples. (Mar.2004)
35. What are classes in C++ for file stream operation? How do you open and close
files in C++?Explain any four file modes. (Mar.2004)
36. Explain the following concepts with an example of each:
a) Inheritance b)Polymorphism c) Data Abstraction (Mar.2004)
37. What are classes in C++? How are member functions defined inside and outside
the class? Explain with examples. (Mar.2004)
38. Explain basic and user defined types in C++. (March 2002)
39. Explain the tree types of data conversion in C++ with a suitable example.

(March 2005,2019)
40. Explain local data and global data variables in C++ using example. (Mar.2016)
C++ Programming 123

A:.Jsing Examples explain how files are opened and closed in C++? state any four
file modes (Mar.2016)
4233.State three characteristics of static data. (Mar.2016)
43. Explain use of memory management operators in C++. (Mar.2016)
44.Explain the concept of function overloading with example. (Mar. 2017)
use of scope resolution operator and memory management operators
45. Explain the
in C++ with examples. (Mar. 2017)
46. Explain the syntax of C+-+t program structure with example. (Mar. 2019)
47. Explain any six operators used in C++. (Mr. 2019)
48.Explain friend function in C++ with example. (Mar. 2020)
49. Write C++ declaration for the following. (Mar. 2020)
i) Array of 10integers ii) Pointer to character variable iii) Object of the class

PROGRAMMING EXERCISE
1. Write a C++ program that right justifies text. It should read
and echo a
sequence of left justified lines and print then in right justified format. (Mar.2006)
2. Implement a class temperature to convert degree
Fahrenheit Value to degree
C
temperature in degree Celsius
Celsius Value. [Hint : C/5 =F-329, where is
(Mar.2006,09,16)
and F is temperature in Fahrenheit degree]
3. Write a program in C++ to find the
Greatest common Divisor (GCD) of two
(Mar.2006)
natural numbers.
program to display first 20 terms of Fibonacci series.
4. Write a C++
(Mar. 2007,09,16)
a program to find factorial of a natural number inputted during
5. Write C++
(Mar. 2008)
program execution.
program C++ that right justifies text. It should read and echo a
6. Write a in
right justified format.
sequence of left justified lines and print them in
olhel (Mar.2007)
program to replace every space in an inputed string (less than 80
7. Write a C++
(i.e. -) (Mar. 2007)
characters) with a hyphen
a
a Class. Each object of this class will represent circle
8. Implement Circle
a float. Include an area () function which will
accepting its radius value
circle.
(Mar. 2008)
calculate the area of
124 C++ Programmin
9. Writea C++ program to find greatest common divisor of two numbers. Define
a method find to accept the values and calculate GCD
of two numbers and
print the GCD value. (Mar. 2008,2011,17)
10. Write a C++ program that will read a line of text. andcount the number of
Words in a text. (Mar. 2008)
11. Write a C++ program to count occurrence a character
of
'in a string.
12. Write a C++ program by using swap function to interchange two
given
numbers. (Mar. 2010)
13. Write a C++ program to accept a number and test whether it is a
Prime number.
(Mar. 2011)
14. Write an object Oriented program in C++ to read an integer number and find
out the sum of its all digits.( e.g. if n=1256 SUM =
1+2+5+6) (Mar. 2011)
15. Implement class average. Include a constructor
in it which will accept value
of three variables from user. Include two more functions
in it, one calculates
average and other prints it.
(Mar. 2016)
16. Write a C++ program to find factorial
of entered number. (Mar. 2017)
17. Write a C++ program to accept a sentence
(maximum 50 characters) and print
sentence in reverse.
18. Write a function in C+t+ to accept (Mar. 2019)
four integers. Find the smallest integer and
print it.
19. Write a C++ program to (Mar. 2019)
find smallest in an array of 10
floats using pointer.
20. Write a class based program (Mar. 2019)
in C++ to find area of a Triangle.
21. Write a C++ program to accept (Mar. 2019)
10 integers in an array
average. and find its sum and
22. Write a C++ program
to accept a sentence of 80 characters and(Mar. 2020)
count number
of word in a sentence.
(Mar. 2020)
Answers Q.(1)
1)None of the above,
2) ::, 3) Destructor, 4) Friend function
5)Both of the above,
6) All of the above,
8)Follows bottom-up approach 7) Public
9)polymorphism 10) Class
11) multiple 12) Friend function
16) private 17)26
13):: 14)14 15) 8
::18)
4
HTML.
INTRODUCTION
HTML is an evolving language,
and stands for Hyper Text Markup Language
It is a text file containing small
markup tags which are instructions given to
browser about how to display the
page.
An HTML file must have an
htm or html file extension.
An HTML file can be created using a
simple text editor (like Notepad in
windows).
HTML was invented by Tim Berners-Lee
while at CERN, the European Laboratory
for Particle Physics in Geneva.

4.1 WHY HTML


Hypertext is an ordinary text with formatting facilities
process of taking ordinary text and Markup is the
and adding extra features to it.
Thus the HTML documents are text files made up
define a document and guide its display. In
of HTML elements that
practical terms, HTML is a collection of
platforn-independent styles that define the various components
Web document. HTML provides the user of a World Wide
with a consistent interface and a highly
effective medium for presenting information to developers.
HTML is a set of instructions given to Web browser for
formatting and layout
of WebPages, so it may be possible that a look of the same HTML
code imay differ
Since different browsers may interprets
them differently.

Advantages of HTML
1) HTML is an easy to use,
learn, implement and flexible alternative to
traditional presentation and tedios software.
2) Contains powerful formatting facilities.
3) HTML documents are device and platform
independent. (Since it can be
designed to work on not only home PCs but also on graphical workstations,
dumb terminals, network computers, hand-held devices etc.)
4) You can traverse to any HTML document required because
of hyper linking
facility available, thus controlled navigation is possible.
) Required HTML pages can be updated easily, without changing whole
document.
O) lt is a kind of software, which has been called world ware.

) Independent work can be done and you need not rely cn application or
program vendor.
) No expensive license software or hardware required.
HTML
126

9) If compatibility with user habits, expectations and multiple platforms is th


goal, then HTML is the only approach to delivering a web application.

Disadvantages of HTML
1) HTML doesn't offer programming languages features and capabilities.
2) It's easy to write "bad" HTML containing errors.
3) Complex HTML code is hard to read and understand and code complexity
increases to make interactive web page. So building comnplex pages is very
time consuming.
4) I's easy to make mistakes (e.g. leaving out a ">" or "/" character).
5) Special types of software like scripting languages (VB Script, Java Script) are
required for handling different events and validations.
6) Can't detect errors easily since no special debugging tool is provided.

4.2 HTML DOCUMENTATION


HTML documents are plain-text (also known as ASCI) files that can be
created using any text editor (e.g., Emacs or vi on UNIX machines; Simple Text on
a

Macintosh; Notepad on a Windows machine). You can also use word-processing


software if you remember to save your document as "text only with line breaks".

HTML Editors
HTML Editors are programming tools for Hyper Text Markup Language
(HTML) documents.
There are three categories of HTML Editors:
1. Text Editors

2. HTML Code Editors


3. HTML Design Tools

1)Text Editors
These editors only edit ASCII text. They offer no functionality to facilitate
better HTML development. They are tuseful if your knowledge of HTML is excellent.
Some examples Text Editors include Notepad (Windows), Simple Text
of
(Macintosh), and Pico (Unix).
They are typically WYSIWYG. WYSIWYG is an acronym for "what you se
is what you get"; it means that you design your HTML document visually, as if yo
were using a word processor, instead
of writing the markup tags in a plain-text
and imagining what the resulting page will look like.

2) HTML Code Editors


These editors may or may not be WYSIWYG.
HTML 127

3) HTML Design Tools


These tools are intended for HTML development without exposing the code to
the author. They are typically WYSIWYG. Many of these tools do allow the user to
access the HTML code, however this is not usually apparent to the user. Some
examples of HTML Design Tools include NetObjects Fusion (Web Development),
and Microsoft Office 97 (Traditional Office/Design Tools that provide HTML
output).
You can concentrate on the content, rather than the syntax,of your Web site, You
can Create a Web site without learning HTML, You can Design Elegant and
Consistent Web sites with a few key strokes, since they are more user friendly

> HTML ELEMENT


a
An element is a fundamental component of. the structure of text
documnent.
can
Some examples of elements are heads, tables, paragraphs, and lists. Elements
contain plain text, other elements, or both.

HTML elements are defined using HTML tags.


> HTML Tags
HTML tags are used to mark-up HTMLelements.
< >
HTML tags are surrounded by the two characters and
The surrounding characters are called angle brackets. are usually paired
HTML tags normally comne in pairs like <b> and </b>they
to start and end the tag instruction.
tag.
The first tag in a pair is the start tag, the second tag is the end
content.
The text between the start and end tags is the element
means the same as <B>.
HTML tags are not case sensitive; <b>
Syntax is:
name>
<tag name> text (element content) <Jtag
content)
<tag name attribute name="argumnent/value> text (element
/tag name>
or just
<tag name>
For example:
</TITLE
<TITLE> WELCOME TO MY WEBSITE
<JA>
<A HREF-"URL"> CLICK HERE

AnHTML document is composed of a single element:


<HTMLS <HTML>
body elements:
nat is, in turn, composed of head and
<HEAD> <HEAD>
and <BODY>... </BODY>
128 HTML

> Tag Attributes


Tags can have attributes. Attributes can provide additional information about
h
HTML elements on your page, included inside the start tag.
Attributes always come in name/value pairs like this: name="value"
Syntax is
<tag name attribute name='value'>
c.g.<IMG SRC='c:la.jpg">
so here src is an attribute
for image tag. Normally its value is specified in quotes.

Some useful Tips while writing HTML document


HTML is not case sensitive. So <head> is
equivalent to <HEAD> or <Head
Also all tags are not supported by all World
Wide Web browsers. If a browser doe
not support a tag, will simply ignore it.
it
When you write HTML text, you can never
be sure how the text is displayed ir
another browser. The text will be
reformatted every time the user resizes hi
window. Never try to format the text your
in editor by adding empty lines and spaces
to the text.
HTML will truncate the spaces your text.
one. In HTMLanew in Any number of spaces counts as
line counts as one space.
Using empty paragraphs <p> to insert
tag instead. You might blank lines is a bad habit. Use the <br
have noticed that paragraphs can be
closing tag </p>. Don't rely on it. written without the
The next version of HTML might not allow you to
skip any closing tags.
HTML automatically adds an
extra blank line before and
like before and after a paragraph, after some elements,
and before and after a heading.
4.3 THE MINIMAL HTML
DOCUMENT
Every HTML document should
contain certain standard
document consists of head
and body text. The head HTML tags. Each
contains the actual text contains the title, and the body
that is made up of paragraphs,
Browsers expect specific lists, and other elements.
information
HTML and SGML specifications. because they are programmed according to

Simple html document

KHTML>
<HEAD>
<TITLE> HOME PAGE
STITLE>
<SHEAD>
<BODY> THIS
IS MY FIRST WEB
<BODY> PAGE
KHTML>
HTML
129

(When yOu save an HTML file, you can use either the .htm or the .html extension.
Save the file as "firstpage.htm". Open this file through your Internet browser.)

Example Explained
The first tag in your HTML document is <HTML>. This tag tells your browser
that this is the start of an HTML document. The last tag in your document is
sIHTML>. This tag tells your browser that this is the end of the HTML document.
The text between the <HEAD> tag and the <HEAD> tag is header information.
Header information is not displayed in the browser window. The title is displayed in
your browser's caption.
The text between the <BODY> tags is the text that will be displayèd in your
browser.
The text between the <TITLE> tags is the title of your page

4.4 BASICHTML TAGS


The most important tags in HTML are tags that define headings, paragraphs and
line breaks.

1.<HTML>
The HTML tag identifies a document as
an HTML document. All HTML documents
should start with the <HTML> tag and end with the </HTML> tag.
Syntax
<HTML>......HTML>
e.g.
a
The following example begins and ends short document with
the HTML tag.
<HTMLS
<BODY
This is HTML file.
<BODY>
HTML>

Following tags appear in <HTML>tag.i-


HEAD or mneta-information, about the
The HEAD contains general information,
an HTML document header. It is the first thing in
document. The HEAD tag defines
any document, lying above the BODY and just after the
<HTML> tag starting the
are not displayed as part of the document.
document. The contents of the HEAD STYLE.
HEAD tag can contain TITLE, BASE, ISINDEX, META, SCRIPT,
The
and LINK tags.

Syntax
<HEAD>...SHEAD>
HTML
130

C.g. <HTML>
<HEAD>
<TITLE>WELCOME TO FIRST WEBSITE<TITLE>
HEAD>
<HTML>

TITLE element, which should be


The title of a document is specified by the TITLE
can have only one title, which should
placed in the document HEAD. Each document
way.
identify the document content in a general
links or
The Title is not part of the document text and cannot contain hypertext
--
special markup commands it must be simple
text. Often th title is used to label the
a place in a browser's history or
window displaying the text, or is used to label
--
bookmark list. It therefore should be short less than 64 characters
Other tags can be placed are:

STYLE -- Stylesheet instructions, written in a stylesheet language. Styleshet


instructions specify how the document should be formatted for display. Very few
browsers currently support stylesheets.
SCRIPT -- Script program code -- for enclosing, within a document, scripting
program code that should be run with -- and that can interact with -- the
document. Example languages are JavaScript and VBScript.
E.g.<HTML>
<HEAD>
<SCRIPT language="VBSCRIPT"> VBscript </SCRIPT>
</HEAD>
<BODY>
... text
of the document
<BODY>
</HTML>

2.<BODY> Defines the document's body


The BODY element contains all the contents of a document
Various mark-up elements are allowed within the body to
indicate headings,
paragraphs, lists, hypertext links, images, and so on.

> Attributes in body tag


1) The BACKGROUND Attribute
This allows you to specify an image file to use as a
background (a bit like a
watermark) behind the displayed text and graphics.
E.g.<BODY BACKGROUND="c:la.gif"'>
Text....
<WBODY>
HTML 131

So image a.gif will be set as a background to your web page.

2) Background color of the web page


Attribute is:BGCOLOR="#Iggbb"
Sets the background color to the specified RGB color value, where RR GG and BB
are the hexadecimal color codes for the Red, Green and Blue levels, ranging from 0 to
255 -- that is, 00 to FF. The color "000000" is black, while "FFFFFF" is white.

3) Setting the text color(TEXT Attribute)

Syntax: <BODY TEXT="#rrggbb">text in a body</BODY>


Sets the default text color to the specified RGB color value.

4) Setting color for hyperlinks (LINK Attribute)


Syntax: <BODY LINK="#rggbb">text in a body</BODY>
Sets the default text color of hypertext anchors to the specified
RGB color value.

5) Setting color for visited hyperlinks (VLINK Attribute)


a body</BODY>
Syntax: <BODY VLINK="#rrggbb">text in
to the specified RGB color
Sets the default text color of visited hypertext links
value.
as
> Elements in the BODY are categorized
A) Text Block Elements
content of a document. Structurally,
BODY element contains all the displayed
the document content is organized into
blocks of text, such as paragraphs, lists,
quotations, and so on. These are generically called block
headings, paragraphs, block
"block" chunks of text together into logical units. Block elements
elements, since they -- for example, a list item can contain paragraphs or
can often contain other blocks
block quotations, So that these
elements can often nest together.
The block-level elements are:

Hn (Headings) (hl to h6)


P
ADDRESS
BLOCKQUOTE
PRE
HR
FORM
TABLE
HTML
132

B) Text Emphasis Elements


These are elements that mark text for special meanings, for example, that a particula
piece of text is emphasized (EM) or a citation (CITE), or that specifies the desirea
physical formatting, such as boldface (B) or italics (). These elements can usualy
appear anywhere inside a block element, with a few exceptions (you can't haye
images inside a PRE element).

C) Special Elements -- Hypertext Anchors


Analogous to the text-level markup is the anchor (A) element. This is the element that
marks hypertext links. Obviously you want to know a lot about this one.

D) Character-Level Elements
Then are what I call character-level elements, namely line breaks (BR) and images
(IMG). These are treated much like characters, and can appear wherever there is a

character in a document.

E) Character References
Finally there are character or entity references. These are special HTML "escape"
codes that can be used to enter special characters that are hard to type, such as
accented or other non-ASCII characters. You also need to use these to type angle
brackets or ampersand characters -- as these are otherwise interpreted as HTML tags
(<.. >)or as the beginnings of character or entity references (&).
Analogous to the text-level markup is the anchor (A) element. This is the element that
marks hypertext links. Obviously you want to know a lot about this one.

3. <P> Defines a paragraph


Paragraphs are defined with the <P> tag. Can contain align attribute for alignment of
the text within paragraph.
E.g.<P ALIGN="CENTER"> this is a paragraph</P>

HTML automatically adds an extra blank line before


and after a paragraph. You
must indicate paragraphs with <P> elements.
A browser ignores any indentations or
blank lines in the source text. Without <P> elements,
the document becomes one
large paragraph. The P> closing tag may be omitted.
understand that when they encounter a <P> tag, means
This is because browsers
it that the previous paragrapn
has ended. However, since HTML now allows
certain attributes to be assigned to the
<P> tag, it's generally a good idea to include it.

ADDRESS Elemnent
The ADDRESS element is used for address
information, signatures, statementsO
authorship, etc. It is often placed at the
bottom (or top) of a document. The renderin8
of the contents of the ADDRESS is left up to the
browser -- most browsers render
ADDRESS in italics. It may also be right
justified, or indented. th
HTML
133
e.g.
ADDRESS><A HREF="c:ladd.html">X.Y.Z.</A><IADDRESS>
<P><ADDRESS> <P>
WEB DESIGNER<BR>
Tel (023) 122 123.
ADDRESS> <P>
These. are rendered as
X.Y.Z
WEB DESIGNER
Tel (023) 122 123.
An address cannot contain P, BLOCKQUOTE, FORM or other block elements, but
can contain text, text markup (emphasis, etc.), anchor elements or even images.

4. <BR> Inserts a single line break


Line Breaks:
The <BR tag is used when you want to end a line, but don't want to start a new
paragraph. The <BR> tag forcesa line break wherever you place it.
E,g. This <BR> is line breaks.
So here This and is line breaks will appear on two different lines.
The <BR> tag is an empty tag. It has no closing tag.

5. <HR> Defines a horizontal rule.


window.
Used to produce a horizontal line, the width of browser's
It allows to differentiate sections of your document.
you alter the thickness
SIZE and WIDTH attributes will let
covered by it.
And the percentage of the windows

e.g.<BODY>
<H1>This is my first web page</Hl>
WIDTH="20%">
<HR SIZE=5
<BODY>
HTML source code Comments in HTML.
O. <! Defines a comment in the your
a comment. You can use comments to explain
The browser will ignore a date.
can you when you edit the source code at later
Code, which help

E.g.<-- This is a comment -->


point after the opening bracket, but not
an exclamation
Note that you need
before the closing bracket. sequence "-" may not appear
double-dash
and the sure that
Comments do not nest, ->
closing tag. You must also make
inside a commnent except as part of the
start-of-comment string.
there are no sppaces in the
HTML
134

For example, the line


<!-- This is a valid comment -->
<!- This is not valid comment -->
is not, since there is a space between the left angle bracket and the exclamation mark.

7. Headings
<HI>---<H6> Defines heading 1 to heading 6.
Headings are defined with the <HI> to <H6> tags. <Hl> defines the largest
heading. <H6> defines the smallest heading (as shown).

Heading Size 1 Heading Size 2


Heading Size 3 Heading Size 4

Heading Size 5 Heading Size 6


E.g.
<H1STYLE="COLOR: blue">THIS is displayed in large font with blue color </HI>
<H1 STYLE="FONT-FAMILY:verdana">This is displayed in verdana font style
</H1>
<HISTYLE="FONT-SIZE:150%">You can define size in percentage also.</HI>
HTML automatically adds an extra blank line before and after a heading.

8. <PRE> tag
This tag preformats the text. The text appearing between <pre> and </pre> is
displayed in monospace form. Using this tag, we can position the characters. It can
also be used for columnar lists.
Eg. <PRE> Employee_name Employee_number Employee_address </PRE>
So output is displayed as :
Employee_name Employee_number Employee_address
4.g FONT TAGS IN HTML
To have different size and color to the text, rather than using headings tags,
many people uses <FONT>tag.
The <FONT> tag in HTML is deprecated. It is supposed to be removed in a future
version of HTML..
Font attributes:
Attribute Example Purpose
size="number" size="2" Defines the font size
size="+number" size="+1" Increases the font size
size="-number" size="-1" Decreases the font size
|face="face-name" face=*Times new Roman' Defines the font-name
color="color-value" color="#eeff00 Defines the font color
color="color-name" color="red" Defines the font color
HTML 135

C.g•
<P>
RONT SIZE=*5 FACE=VERDANA" COLOR="#AA0OFF"s
This is example of demonstrating fonts. <FONT>
<P>
<MARQUEE> TAG
MARQUBE, Supported only by the Microsoft Internet Explorer 2 (and later)
hrowser., is used to create a scrolling text marquee.

e.g. <MARQUEE ALIGN=top'">Scrolling text <MARQUEE>


creates a text marquee with the enclosed text scrolling along the frame.
The another attribute is DIRECTION defining direction of the marquee text.
e.g.<MARQUEE DIRECTION=RIGHT">WELCOME<MARQUEE>
So here WELCOME scrolls from left towards right. The default direction is right
to left.
But other commercial browsers, including Netscape Navigator, do not support this
element.

Character Formatting
HTML has two types of styles for individual words or sentences: logical and
physical. Logical styles tag text according to its meaning, while physical styles
indicate the specific appearance of a section. For example, in the preceding sentence,
the words "logical styles" was tagged as “strong." The same effect (formatting those
words in italics) could have been achieved via a different tag that tells
your browser
to "put these words in bolds." Try to be consistent about which type of style
you use.

Logical Styles:
<EM>
cannot reset your
for emphasis. Typically displayed in italics. (Consultants
password unless youcall the help line.)

<CODE
for computer code. Displayed in
a
fixed-width font. (The <stdio.h> header
file)

<STRONG> your
strong emphasis. Typically displayed in bold. (NOTE: Always check
for
links.)

<VAR>
you will replace the variable with specific information.
for a variable, where file.)
displayed in italics. (rm filename deletes the
Typically
136 HTML

Physical Styles
<B> bold text :It boldface text appearing between <B> and </B> tag.
e.g.<B>n Bold</B>
Output is In Bold

<>italic text : It italicize text appearing between <I> and </> tag.
e.g.<I>In Italics</>
Output is In Italics

<U>underline text : It underlines text appearing between <U> and <U> tag.
e.g.<U>Underlined<U>
Output is Underlined

<SUB> tag: It is subscript tag. The text encloed in <SUB>and </SUB is


displayed in subscript form. This is useful in representation of mathematical
formulae or chemical equations.
e.g. H<SUB>2</sub>S0<SUB>4</SUB>
output displayed as :H,SO4

<SUP> tag:- It is superscript tag. The text enclosed in <SUP>and SUP> is


displayed in superscript form. This is also useful in representation of
mathematical formulae or chemical equations.
e.g. volume of sphere is=(4/3)(3.14)r<SUP>3</SUP>
Output displayed as: volume of sphere is=(4/3)(3.14)r

4.6 DEALING WITH URLS


Hypertext Anchors
URL stands for Üniform Resource Locator, which may represent an
address
of document on web or Internet or simply a path to a document in a specific directory.
The World Wide Web uses Uniform Resource LOcators (URLS) to
specify the
location of files on other servers. A URL includes the type of resource
being accessed
(e.g., Web, gopher, FTP), the address of the server, and the location
of the file. The
syntax is:
scheme:/lhost. domain [:port]/pathl filename
HTML provides you to jump from a link to any document or image or any
local or WebPages by using special tag, called <a> i.e. Anchor tag.
Syntax is: <A HREF="URL'>name or image which can be treated as link</A>
Thus anchor is a piece of text or some other object (e.g. image), which
marks the
beginning and/or the end of a hypertext link. The <A> element is used to mark that
piece of text (or inline image), and to give its hyper textual relationship to
other
documents. The text between the opening and closing tags,
<A attributes> ...text..
JA> can act as start or a
destination (or both) of link. The HREF attribute (which IS
actually optional) marks the anchor as the start of a link to another document or
HTML
137
resource (it could point, for example, to an image file), or to a
particular place in
another docunent.
Syntax is:
KA HREF="URL (absolute or relative path)">anchor name <A>
An absolute or parial URL can specify the address of the referenced document:
e.g.

1)Link to a page on tle World Wide Web.,


<A HREF="http://www.yahoo.com">Enter your email-id</A>
The string Enter your email-id ' is a hypertext link to the website indicated by URL
specified

2) Link to an image by image as a link.


<A HREF="image2.jpeg"> <iMG SRC="imagel.gif">dA>
The image `imagel.gif is a hypertext link to the image file located in the same
directory This will allow you to use a small icon that links the user to a larger version
of the same image.

3) Link to document located in different directory


<AHREF-"d:Asoftla.html"> Click Here.<lA>
Here by clicking on Click Here link, destination page will be displayed which is
specified in the path given.
a
4)Link to the same page(Links toa Particular Place in Document)
<P><A HREF="#samepage">This is link to the same page. <JA></P>
<A NAME="'samnepage"><H2>Yes You are in the same
,
page.</H2></A>
Particular places in an HTML document can be marked as specific
destinations of hypertext links via the NAME attribute. Linksto SpecificSections
a a
Anchors can also be used to move a reader to particular section in
document (either the same or a different document) rather than to the top, which is the
a to create
default. This type of an anchor is commonly called named anchor because
the links, you insert HTML names within the document.

5)Links Between Sections of Different Documents to a specific section in


.

Suppose you want to set a link from document A (fileA.html)


another document (fileB.html).
a a anchor:
Enter the HTML coding for link to named
fileA.html:-
<P>
This is link
<A HREF-" fileB.html
#differentlink">referenced to a specific section </A in

different document.
HTML
138
as a tab wi. un the fileB.html file
Think of the characters after the hash (#) mark
at the top of the window when
This tab tells your browser what should be displayed
the link is activated.
Next, create the named anchor (in this example
"differentlink ") in fileB.html as:
<H2><A NAME=" differentlink "> to a specific section <Á><H2>
in place, you can bring a reader directly to , " to a
With both of these elements
specific section"word in fileB.html

Important Hint
You cannot make links to specific sections within a different documnent unless
or that
either you have write permission to the coded source of that document
document already contains in-document named anchors
Attributes for A and LINK :>The following are the attributes appropriate to
either Anchor or LINK elements. The other attributes are less common, and can be
omitted at an introductory reading.
1. HREF (link to object)
2. NAME (link from object
3. TITLE (TITLE of document)
4. METHODS (how to link -- this attribute has been dropped from the HTML
specification, and should not be used)

6) Link to Mail (Mailto)


Youcan make it easy for a reader to send electronic mail to a specific person or mail
alias by including the mailto attribute in a hyperlink.
Syntax is:
<A HREF="mailto:emaiid @host">Name</A>
e.g.
<A HREF="mailto:spc yahoo.co.in'">Mailme<A>
@

4.7 LISTSIN HTML


HTML supports ordered, unordered and definition lists.

Different List Tags are:


<OL> Defines an ordered list
<UL> Defines An Unordered List
<LI> Defines a list item
<DL> Defines a definition list
<DT> Defines a definition term
<DD> Defines a definition description
<DIR> Deprecated. Use <ÜL> instead
<MEN> Deprecated. Use <UL> instead
HTML 139
1.Unordered Lists
An unordcred list is a list of items. The list items are marked with bullets
(typically smali black circles). To make an unnumbered, bulleted list,
1. Start with an opening list <UL> (for unnumbered list) tag Enter the <LI> (list
item) tag followed by the individual item; no closing </LID tag is needed
2. End the entire list with a closing list </UL> tag
Inside a list item you can put paragraphs, line breaks, images, links, other lists,
etc.
e.g. <HTML>
<BODYs
<H4>This is Unordered List</H4>
<UL type = "circle">
<LbSunday</L>
<LbMonday</LI>
<LbTuesday</LI>
<UL>
<BODY>
<HTML>
sooutput given by browser is:
This is Unordered List:
Sunday
Monday
Tuesday
tag you can change shape of the bullet.
By specifying type attribute in the <UL>
The standard shapes provided
are "disk", "circle", and "square"

2.0rdered Lists a list of items. The list items are marked with
An ordered list is also
an numbered is identical to an unnumbered list,
numbers. A ordered list also called a you can put paragraphs, line
except it uses <OL> instead of <UL>. Inside list item
lists, etc. You can specify style of numbering for the list
breaks, images, links, other can take values "I" for uppercase
<OL> tag and it
Items by giving type attribute in
uppercase letters, "a" for lower case alpha
roman, ";" for lower case roman, "A" for
start attribute in <OL> tag is used to start the list from the
numeric letter. The
e.g. <OL start = "6"> will start the list items from number 6.
Tequired number.
e.g. <HTML>
<BODY> List<B><H4
<H4><B>This is an Ordered
<OL type = "i">
<LIbSunday</LI
<LIbMonday</LI>
<LI>Tuesday</LI>
<JOL>
140

</BODY>
</HTML>
so output given by browser is:

This is an Ordered List:


i) Sunday
ii) Monday
iii) Tuesday

3.Definition Lists a list of terms and explanation of


list is not a list of items. This is
A definition a definition list (coded as
starts with the <DL> tag. Thus
the termns. A definition list as <DT>) and a
alternating a definition term (coded
<DL>) usually consists of
description (coded as <DD>). Web browsers generally format the
definition
definition on a new line and indent it.
e.g.
<HTML>
<BODY>
<H4>This is a Definition List</H4>
<DL>
<DT>VB</DT>
<DD>Programming Language<DD>
<DT>VB SCRIPTDT>
<DD>Scripting Language </DD>
<DL>
<BODY>
<HTML>
so output given by browser is:
This is a Definition List:
VB
Programming Language
VB SCRIPT
Scripting Language
Inside a definition-list definition (the <DD> tag) you can put paragraphs, line
breaks, images, links, other lists, etc.

4.Nested lists
Lists can be nested. You can also have a number of paragraphs, each containing a
nested list, in a single list item.
C.g.
<HTML>
<BODY>
<H4>This example of Nested List</H4>
HTML
141
<UL>
<LIbScripted Programming</LI>
<LbStructured Programming.
<UL>
<LIbBasic</LI
<LI>Pascal</LI>
<SUL>
<LS
<LbObject Oriented Languages</LI>
<SUL>
<BODY>
<HTML>
ACWy Documentsla.html- Microsoft Inteinet Explorer
Help
Fe Edt View Go Favornes

Back Stop Reffesh Home SearchFavorikes Hislory Charnels Eullsaecn Edt


Foryard
Addressl)CMyDocumenlsla.hml

This example of Nested List

• Scripted Programming
• Structured Programming
o Basic
o Pascal
• Object Oriented Languages

4.8 TABLES IN HTML


tag, use the TR tag to define
The TABLE tag defines a table. Inside the TABLE use the TD
rows in the table, use the TH tag to define row or column headings, and
a CAPTION tag, which
tag to define table cells. The TABLE tag can also contain
specifies the caption for the table
you can specify the width of the border surrounding
(Individual rows and cells in
the table and the default background color of the table.
the table can have their own background color.)
You can use the CELLSPACING
in the table and the CELLPADDING
attribute to specify the distance between cells you
attribute to specify the distance between the border
and content of every cell. If
will do its best to make the table
Specify the width and height of the table, the browser
some cases this may not be possible. For example,
Iit the specified dimensions, but in
If the table contains cells that contain
non-wrapping long lines, the table may not fit in
a specified width.
Syntax :
<TABLE
ALIGN="LEFTRIGHTICENTER"
BGCOLOR="color"
BORDER="value"
CELLPADDING="value"
HTML
142

CELLSPACING="value"
HEIGHT="height"
WIDTH="width"
COLS="numOfCols"
HSPACE-"horizMargin"
VSPACE="vertMargin"

STABLE,
> 'Table Elements
<TABLE> </TABLE> defines a table in HTML. If the BORDER
attribute is present, your browser displays the table with a border
...
<CAPTION> <ICAPTION> >defines the caption for the title of the table.
The default position of the title is centered at the top of the table. The
attributes ALIGN=BOTTOM can be used to position the caption below
the table.
<TR>...JTR>> specifies a table row within atable. You may define default
attributes for the entire row: ALIGN (LEFT, CENTER, RIGHT) and/or
VALIGN (TOP, MIDDLE, BOTTOM).
...
<TH> <STH> > defines a table header cell. By default the text in this cell is
bold and centered. Table header cells may contain other attributes to
determine the characteristics of the cell and/or its contents.
TD> TD> >defines a table data cell. By default themay text in this cell is
aligned left and centered vertically. Table data cells contain other
attributes to determine the characteristics of the cell and/or its contents.

> Table Attributes


ALIGN
Specifies the horizontal placement of the table.
LEFT aligns the table on the left (the default).
RIGHT aligns the table on the right.
CENTER aligns the table in the center

BGCOLOR="color'"
sets the color of the background for the table. This color can be overridden by
a
BGCOLOR tag in the TH, TR, Or TD tags.

BORDER="value" indicates the thickness, in pixels, of the border to draw


around the table. Give the value as an integer. no border. means value 0

CELLPADDING="value"
determines the amount of space, in pixels, between the border of a cell and the
contents of the cell. The default is 1.
HTML
143

CELLSPACING='value" determines the amount of space, in pixeIs,"


between individual cells in a table. The default is 2.

HEIGHT="height"
specifies the height of the table. The default is the optimal height determined
by the contents of each cell. Can be a number of pixels, or a percentage of the
height of the page or parent element.

WIDTH="width"
defines the width of the table. The default is the optimal width determined by
the contents of each cell. Can be a number of pixels, or a percentage of the
height of the page or parent element.

COLS="numberOfColumns"
Indicates how many virtual columns of equal width fit in the width of the
window. If the WIDTH attribute is supplied, the COLS attribute indicates how
many virtual columns fit in the specified width. Suppose that the WIDTH
case, each column takes
attribute is "80%" and the COLS attribute is 4. In this
up 20% of the width of the window. Note, however, that if the minimum
an actual column is greater than the
width needed to display the contents of
to fit its
width of a virtual column, then the width of the column is expanded
contents.

HSPACE-"horizontalMargin"
the table and any
Specifies the distance between the left and right edges of
surrounding content.

VSPACE="verticalMargin"
the top and bottom edges of the table and any
Specifies the distance between
surrounding content. or
<TD>... </TD>
within <THS </THS
Similarly you can define Attributes
cells as-- Horizontal alignment of a cell..
ALIGN (LEFT, CENTER, RIGHT)
(TOP, MIDDLE, BOTTOM) Vertical alignment of a cell.
VALIGN a cell spans.
COLSPAN=n The number (n) of columns
rows a cell spans.
ROWSPAN=n The number (n)of

are
Important Hint
always have end tags. Although the end tags
1. TH, TD and TR should formatting of the table if
many browsers will mess up the
formally optional, always use end tags if you
you should
you omit the end tags. In particular,
a html document.
have a TABLEwithin
HTML
144

TABLE has no borders. By default, tables are drawn without borde.


2. A default
to the lines.
lines. Ycu need the BORDER attribute draw
a table is flush with the left margin. Most current browsers alsa
3. By default, values ars
ALIGN attribute. Allowed
supports table alignment, using the
"right", or "center", for example: <TABLE ALIGN="left">. The values
"left",
or right of the page, with text floy
"left" and "right" float the table to the left
allowed around the table.
4. Alignment atiributes
on TD or TH attributes override those alignments
specified by the TR:

> VARIOUS TABLE EXAMPLES


1.Table with no border and caption:
<HTML>
<BODY>
<TABLE>
<CAPTION>TABLE WITH NO BORDER</CAPTION>
<TR>
<TD>ABC</TD>
<TD>XYZ</TD>
<TD>PQR</TD>
STR>
<TR>
<TD>LMN</TD>
<TD>DEF</TD>
<TD>HYJ</TD>
<TR>
<JTABLE>
<BODY>
<HTML>

Output displayed by browser is:


TABLE WITH NO BORDER
ABC XYZ POR
LMN DEF HYJ

2.Table with background color and image no border:


<HTMLs
<BODY>
CH4>A BACKGROUND COLOR:</H4>
TABLE BORDER="T" BGCOLOR="BLUE">
<TR>
<TD>100</TD>
<TD>200</TD>
HTML 145

<TD>300</TD>
STR>
<H4>A BACKGROUND IMAGE:<H4>
<TABLE BORDER="1"
BACKGROUND=".CADESKTOPXYZ.JPG">
<TR>
<TD>SUNDAY<TD>
<TD>MONDAY</TD>
<TR>
<TR>
<TD>TUESDAY</TD>
<TD>WEDNESSDAY<TD>
TR>
<TABLE>
<JBODY>
<JHTML>
output displayed by browser is:
A Background Color:
100206l306:
A Background Image:
SUNDAY MORDAN
TUESBDAYWEDNESSDAY

3.Table With Cell spacing


<HTML>
<BODY>
<H4>WITHOUT CELLSPACING:<H4>
<TABLE BORDER="1">
<TR>
<TD>SUNDAY<TD>
<TD>MONDAYTD>
<STR>
<TR>
<TD>WEDNESSDAY<JTD>
<TD>THURSDAY<TD>
JTR>
STABLE>
CELLSPACING:</H4>
<H4> WITH CELLSPACING="10">
<TABLE BORDER="1"
<TR>
<TD> SUNDAYTD>
<TD> MONDAY <TD>
146 HTML

<JTR>
<TR>
<TD> WEDNESSDAY </TD>
<TD> THURSDAY </TD>
<TR>
<TABLE>
<BODY>
HTMLs
so output displayed by browser is:

WITHOUT CELLSPACING:
SUNDAY
MONDAY
WEDNESSDAYTHURSDAY
WITH CELL SPACING:

SUNDAY MONDAY
WEDNESSDAY THURSDAY

4.Table with cell padding


<HTML>
<BODY>
<H4>WITHOUT CELLPADDING:<H4>
<TABLE BORDER-"1">
<TR>
<TD>SUNDAY<TD>
<TD>MONDAY</TD>
<TR>
<TR>
<TD>WEDNESSDAY</TD>
<TD>THURSDAY</TD>
<STR>
STABLE>
<H4> WITH CELLSPADDING:<H4>
<TABLE BORDER="1" CELLPADDING="20">
<TR>
<TD> SUNDAY <TD>
<TD> MONDAY <TD>
STR>
<TR>
<TD> WEDNESSDAY <TD>
HTML 147

<TD> THURSDAY <TD>


<STR>
<TABLE>
<BODY>
<HTML>
so outputdisplayed by browser is:

WITHOUT CELL PADDING:


SUNDAY MONDAY
WEDNESSDAYTHURSDAY

WITH CELL PADDING:

SUNDAY MONDAY

WEDNESSDAY THURSDAY

5. Table showing use of colspan and rowspan.


<HTML>
<BODY>
<H4>WITHOUT CELLPADDING:<H4>
<TABLE BORDER="1">
<TR> LANGUAGE</TD>
TD COLSPAN=2 ALIGN=CENTER>PRGRAMMING
<TR>
<TR>
<TD ROWSAN=2>OBJECT ORIENTED LANGUAGE</TD>
<TD>JAVA</TD>
JTR>
<TR>
<TD>C++<TD>
</TR>
<TR>
ROWSPAN=2>STRUCTURED LANGUAGE</TD>
TD
<TD>CkTD>
<STR>
<TR>
<TD>BASIC</TD>
</TR>
<KTABLE>
HTML
148

</BODY>
SHTML>
so output dispiayed by browser. is :-
PRGRAMMING LANGUAGE
JAVA
OBJECT ORIENTED LANGUAGE
C++
C
sTRUCTURED LANGUAGE
BASIC

4.9 IMAGES IN HTML


The IMG tag specifies an image to be displayed in an HTML document.
An image can be a plain image that simply appears on the page. An image
can be embedded in an <A HREF> tag so that the user can click it to open a URL. An
image can also be an image map, which has multiple clickable areas that each link
to different URLS. The HEIGHT and WIDTH attributes indicate the dimensions of
the image. If you specify these attributes, Navigator uses them to reserve a place for
the image on the page and continues loading any text and other page elements instead
of waiting for the image to load. Most Web browsers can display inline images (that
is, images next to text)
Images can be in the following types of formats:
GIF (Graphics Interchange Format)
JPEG (Joint Photographic Experts Group)
XPM (X PixMap)
XBM (X Bitmap)

Syntax
<IMG
SRC="location"
ALT="alterntiveText"
ALIGN="alignment"
BORDER="borderWidth"
HEIGHT="height"
WIDTH="width"
HSPACE="horizMargin"
VSPACE="verticalMargin"
>
The SRC attribute is compulsory
SRC="location(URL)"
specifies the URL of the image to
be displayed in the document.
HTML 149

ALT="alternativeText"
specifies text to be displayed if the browser does not support the IMG
tag or if the user has suspended image loading in the browser.

ALIGN
specifies the alignment of the image in relation to the surrounding text. If you do not
specify a value for ALIGN, browser uses BOTTOM as the default LEFT aligns
an
image with the left margin.
RIGHT aligns an image with the right margin.
TOP aligns the top of an image with the top of the tallest item in the
current
line.
text in the
TEXTTOP aligns the top of an image with the top of the tallest
current line.
text in the
MIDDLE aligns the middle of the image with the baseline of the
current line.
text in the
BASELINE aligns the bottom of an image with the baseline of the
current line.
BOTTOM is the same as BASELINE.

BORDER="borderWidth'"
image. The value must
Specifies the width, in pixels, of border around the
a

be an integer.

HEIGHT="'height"
or as a percentage of the
Specifies the height of the image, either in pixels
HTML that contains th image.
height of the window, frame, or positioned block of
value as an integer, for example, "100". To
To indicate a number of pixels specify the
a percentage, specify the value as an integer followed by the percentage sign,
indicate
for example "20%".

WIDTH='"width'"
the width of the image either in pixels or as a percentage of the
Specifies a
or positioned block of HTML containing the image. To indicate a
window, frame,
as an integer, for example, "100". To indicate
number of pixels specify the value
the value as an integer followed by the percentage sign, for
percentage, specify
Cxample, "20%".

HSPACE-"horizMargin"
a margin in pixels between the left and right edges of the image and
Specifies
value as an integer
Surrounding text and images. Give the
150

VSPACE="verticalMargin" top and bottom edges of the image


Specifies a margin in pixels between the
as an integer.
and surTOunding text and images. Give the value

Dummy Images
an imnage that does not exist, your browser
When an <IMG SRC> tag points to your final review of
software substitutes a dummy image. When this happens during hyperlink
your files, make sure that the referenced image does in fact exist, that the
permission is set
has the correct information in the URL, and that the file
appropriately.

External Images, Sounds, and Animations


as a separate document when a user
You may want to have an image open
activates a link on eitherword or a smaller, inline version of the image included in
your document. This is called an external image, and it is useful if you do not wish to

slow down the loading of the main document with large inline images.
To include a reference to an external image:
<A HREF-"ExtImg.gif">text or link<lA>

You can also use a smaller image as a link to a larger image:

<A HREF="Biglmage.gif"><IMG SRC="Snialllmage.gi"'><lA>


The reader sees the Smalllmage.gif image and clicks on it to open the BigrImage.gif
file.
Youcan use the same syntax for links to external animations and sounds, The
only difference is the file extension of the linked file like:
<A HREF-"K3GtheFilm.mov">link anchor</A>
specifies a link toa QuickTime movie. Some common file types and their extensions
are:
1) plain text :--.txt
2) HTML document i-- html
3) GIF image -- -gif
X
4) Bitmap image --xbm
5) JPEG image --
JPg or jpeg
6) AIFF sound file .aiff
7) AUsOund file .au
8) WAV sound file .Wav
9) QuickTime movie :- „Imov

10) MPEG movie -- mpeg or .Impg


HTML 151
> Examples
Inserting Image as an background:
Newer versions of Web browsers can load an image and use it as a background when
displaying a page. some people like background images and some don't. In general, if
you want to include d background, make sure your text can be read easily when
displayed on top of the image.
Background images can be a texture (linen finished paper, for example) or an image
of an object (a logo possibly). You create the background image as you do any image.
<HTMLs
<BODY BACKGROUND="background Image.jpg">
....text within a body
<BODY>
</HTML>

Both gif and jpg files can be used as HTML backgrounds.


If the image is smaller than the page, the image will repeat itself.

Different sized images:


<HTMLS
BODY>
<P>
<IMG SRC="c:\MyDoc\bulb.gif" width="12" height="20">
<P>
<P>
<IMG SRC="c: MyDoc\bulb.gif" width="50" height="70">
<P>
SBODY>
<HTML>
SO output displayed by browser will be:

values in the
you can make a picture larger or smaller changing the
Ihus
HEIGHT"
and "WIDTH"
attributes of the img tag.
152 HTML

Images from different location:


You can insert images from different locations
either from web or fron
different directories on your local machine>Here you have to
attribute, where image lies. give the full path to src
<HTML
<BODY>
<P>
Image from local disk,but different directory....
<IMG'SRC="c:\MyDoc\vk\images\bulb.gif>

>
Image from net...
<IMG SRC="http://www.yah00.com/Logo.gif"
WIDTH="73"
HEIGHT="68">
P>
<BODY>
<HTML>

Image as a link:
You can have image as a link to some
other image or document.
<HTML>
<BODY>
Click on Icon.gif file to get your destination
document.
<A HREF="DestinationPage.htm">
<IMG BORDER"0" SRC="ICONT.GIF"
WIDTH="20" HEIGHT="38">
<JA>
<P>
Click on Logo.gif file to get
resultant image you want......
<A HREF="ResultantImage.jpg">
<IMG BORDER="0" SRC="ICONT.GIF"
WIDTH-"20" HEIGHT="38"'>
JA>
<BODY>
<HTML>

Alternate text:
Text-only browsers will only
"This is Alternative Text".(in display the text in the "alt" attribute,
this example) or Some World which is
as Lynx (text Wide Web browsers such
only browser) cannot
loading even if their software can display images. Some users turn off image
display images (especially
modem or have a slow connection). they are using a
HTML provides a mechanismifto
tell readers what
HTML
153
they are missing on your pages if they can't load images The
ALT attribute lets you
specify text to bc displayed instead of an image. Note that if you hold
the mouse
nointer over the image it will display the text called tool tip.

<HTML>
<BODYS
<IMG SRC="ICON.GIF" ALT=" This Is Alternative Text " WIDTH="30"
HEIGHT="30">
<BODY>
<<HTML>

Images without Text


To display an image without any associated text (e.g., your organization's
logo), make it a separate paragraph. Use the paragraph ALIGN= attribute to center
the image or adjust it to the right side of the window

<HTML>
<BODY
<PALIGN=CENTER>
<IMG SRC = "ICON.GIF" ALT="NOTEXT">
</P>
<BODY>
SHTML>

4.10HTML SCRIPTS
HTML pages with scripts are used to make them more dynamic and interactive.

VBScript
Microsoft Visual Basic Scripting Edition brings active seripting to a wide
variety of environments, including Web client scripting in Microsoft Internet
Service.
Explorer and Web server scripting in Microsoft Internet Information

Easy to Use and Learn


If you already know Visual Basic or Visual Basic for Applications (VBA),
once you learn
VBScript will be very familiar. Even if you do not know Visual Basic,
VBScript, you are on your way to programming with the whole
family of Visual
VBScript
Basic languages. VBScript is integrated with World Wide Web browsers.
a general scripting language in other
and Windows Script can also be used as
applications.
With Windows
VBSCript talks to host applications using Windows Script.
Script, browsers and other host applications do not require special integration code
enables a host to compile scripts.
for each scripting component. Windows Script
HTML
154

obtain and call entry points, and manage the namespace avail able to the developer,
With Windows Script, language vendors can create standard language run times for
scripting. Microsoft willprovide run-time support for VBScript

Insert a Script into HTML Page


A script in HTML isdefined with the <script> tag. Note that you will have to
use the type attribute to specify the scripting language
e.g.
<HTML>
<HEAD>
<TITLE>JAVA SCRIPT</TITLE>
<HEAD>
<BODY>
<SCRIPT TYPE="text/javascript">
document. write("Hello World!")
<<SCRIPT>
<SBODY>
<HTML>

The script above will produce this output:


Hello World!

A new browser willunderstand that the script should be executed, even comment
if
tags surTound it.

Various tags in VB seript


The <NOSCRIPT> Tag
In addition to hiding the script inside a comment, you can
also add a
<noscript> tag.
The <noscript> tag is used to define an alternate text if a script is NOT
executed. This tag is used for browsers that recognize the <script> tag,
support the script inside, so this browser will display the text
but does not
inside the <noscript> tag
instead. However, if a browser supports the script inside the
<script> tag it will ignore
the <noscript> tag.
e.g.
<SCRIPT TYPE="text/vbscript">
<!-

document. write("Hello World!")


-->
SCRIPT>
NOSCRIPT>Your Browser Does Not Support Vbscript!</NOSCRIPT>
HTML 155

Seript Tags:
<SCRIPT> Defines A Script
<NOSCRIPT> :- Defines An Alternate Text If The Script Is Not Executed
<OBJECTS Defines An Embedded Object
<PARAM> Defines Run-Time Setings (Parameters) For An Object
<APPLET> Deprecated. Use <object>

The <SCRIPT> Tag


VBScript code is written within paired <SCRIPT> tags. For example, a
procedure to test a delivery date might appear as follows:
<SCRIPTLANGUAGE="VBScript">
<l-
Function CanDeliver(Dt)
CanDeliver = (CDate(Dt) - Now)) > 2
End Function
-->
<SCRIPT>
Beginning and ending <SCRIPT> tags surround the code. The LANGUAGE
attribute indicates the scripting language. You must specify the language because
function is
browsers can use other scripting languages. Notice that the Can Deliver
>). This prevents browsers that don't
embedded in comment tags (<! and
understand the <SCRIPT> tag from displaying the code.
page. You cn put them
You can use SCRIPT blocks anywhere in an HTML
in both the BODY and HEAD sections. However,
you will probably want to put all
in order to keep all the code
general-purpose scripting code in the HEAD section ensures that all code is read and
together. Keeping your code in the HEAD section
section.
decoded before it is called from within the BODY you may
want to provide inline
One notable exception to this rule is that
events of objects in your form. For
scripting code within forms to respond to the
to respond to a button click in a form:
example, you can embed scripting code
<HTMLs
<HEAD>
<TITLE>Test Button Events</TITLE>
SHEAD>
<BODY>
FORM NAME="Form1">
TYPE="Button" NAME="Button1" VALUE="Click">
<INPUT
FOR="Button1" EVENT="onClick" LANGUAGE="VBScript"
<SCRIPT
MsgBox "Button Pressed!"
JSCRIPT>
<FORM>
</BODY>
SHTML>
HTML
156

Most of your code will appear in either Sub or Function procedures and
witt

be called only when specified by your code. However, you can write VBScript code
outside procedures, but still within a SCRIPT block. This code is executed only once,
when the HTML page loads. This allows you to initialize data or dynamically change
the look of your Web page when it loads.

e.g Random number generator using VB Script (Specimen paper)

<%@ LANGUAGE-"VBSCRIPT" %>


<%
X=0
y=0
dim xarr(9)
Do While x < 10
Randomize
Myval= nt(100 * Rnd) + 1)
Y=0
For y=0 to 9
If MyVal=xarray(y) then
Match = True
Exit for
Else
Match = False
End If
Next
If Match=False then
xarray(x) = MyVal
X=X+1
End If
Loop
%>
<HTML>
<BODY>
<TITLE>RANDOM GENERATOR</TITLE>
<%x=0'for x=0 to 9%>
<P<%response.write(x+1)%>) &nbsp:<%response.write(xarray())%> <P>
<%'next%>
<BODY>
<HTML>
HTML
157

SOLVED EXAMPLES
1) Write HTMLcode to display a Message using different Font attributes.
<HTML>
<HEAD>
TITLE> HTML Document <TITLE>
</HEAD>
<BODY><FONT SIZE="7" face="Comic Sans MS">This is font size 7 with comic
sans ms font</FONT>
<p><FONT SIZE="5"COLOR="red">This is red colored text with font size
5</FONT><p>
<BODY>
<SHTML>
Output is:
eHTML Document Microsoft Internet Explorer
Eile Edit View Favorites Iools Help

Bedk Fovard Stop Refresh Home Seach Favates History Mal Prnt Discuss

Address DAONEne\hil fiesMonl htr eGo |Links

This is font size 7 with comic


Sans ms font
This is red colored text with font size 5
E My
Done CompateA
2) Write HTML code to explain Different leveis of headings with different
alignments.
<HTML>
<HEAD>
<TITLE>Headings <TITLE>
<HEAD>
<BODY>
<HI align="left">First level left aligned Heading</HI>
<H2align="center'>Second Level center aligned heading<H2>
<H3align="center">Third level center aligned heading</H3>
<H4 align="right'>Fourth level right aligned
heading</H4>
<H5 align="right">Fifth level right aligned headingH5>
heading</H6>
Hó align="left">Sixth level left aligned
SBODY>
JHTML>
158 HTML

Output is:
Headings Microsoft Internet Explorer
Elle Edit Vew Favorites Iools Help

Faspd Stop
Retesh Home SearchFavontes History Mal Pint Ed Discuss
Address DAONinehin! fleslheadngs.hl
GoLinks

First levei left aligned Heading


Second Level center aligned heading
Third level center aligned lheading

Fourth level right aligned heading

FIAh level right aligned heading


Strh Lavd
lt indttng
TDons

3) Write HTML code to explain


Different Lists in Html.
<HTML>
<HEAD>
TITLE> lists </TITLE>
<SHEAD>
<BODY BGCOLLOR="#FFFFFF">
<H3>Sample of Unordered lists</H3>
<UL type="disc">
<LILHI
<LILHELLO
<UL>
<H3>Sample of Ordered lists</H3>
<OL type="A" start=3>
<LISWELCOME
<LI>NAMASKAR
<JOL>
<H3>Sample of Definition lists</H3>
<DL>
<DT>HTML
<DD>HYPER TEXT MARKUP LANGUAGE
<DTSURL
<DD>UNIFORM RESOURCE LOCATOR
<SDL>/BODY>
<SHTML>
HTML 159

Output is:
lists- Microsoft Internet Explorer
Eile Edit View Favorites Iools Help

Beck Foyard Stop Reftesh Home Seach Favontes Histoy 1


Mad Print

Address ] DAONine nm
htnd
lies\ists.htm EGoLinks
Sanple of Unordered lists

ELLO

Sanple of Ordered lists


C. WELCOME
D. NAMASKAR

Sample of Defiuition lists

HIML
HYPER TEXT MARKUP LANGUAGE
URL
UNIFORM RESOURCE LOCATOR
wy Computei
Done

(March 2002)
4) Write HTML code for the following:
YEAR
19981999 2000
UNITS 400 |1000
500
SALES
INCOME|1000|800 2000
<HTMLs
<BODY>
<TABLE BORDER>
<TR> COLSPAN="2">
<TH ROWSPAN="2"
COLSPAN="3">YEAR
<TH
<TR>
<TH>1998
<TH>1999
<TH>2000
STR>
<TR> ROWSPAN="2">SALES
<TH
<TH>UNITS
<TD>500
<TD>400
160 HTML

<TD>1000
<TR>
<TR>
<TH>INCOME
<TD>1000
<TD>800
<TD>2000
<STR>
<TABLE>
</BODY>
</HTML>

5) Write the exact output of the following HTML code


with font specifications i
brackets: (March 2002)
<HTML>
<BODY>
<H1> LIST OF BOOKS </H1> <HR>
<UL TYPE = "CIRCLE">
<LI> How to solve it By computer
<LI> HTML in Easy Steps
<LI> C++ Programming
<UL>
<OL type = "A">
<Lb Microprocessor Programming
<LIb Networking Essentials
<LIL Microcontrollers
<IOL>
<BODY>
<HTML>

Output given by browser is:


List of books (text size hl)
How to solve it By computer
HTML in Easy steps
C ++ Programming

A. Microprocessor Programming
B. Networking Essentials
C. Micro Controllers
HTML
161

QUESTIONS
Select the correct alternatives:
1) The tag contains general information,or meta-information,
about the documnent.
a) <HEAD> b) <MARQUEE> c) <TITLE> d)<BODY>
2) The block-level elements contain
tag.
a) <PRE> b)<BODY> c) <MARQUEE> d)<HTML>

3) Attribute is used for setting color for visited hyperlinks


a) VLINK b)LINK c)HLINK
4) specifies the distance between the left and right edges of the table and
any surrounding content.
a) CELLSPACING b)CELLPADDING c)HSPACE d)VSPACE
5) A, tag, specifies the title for the table
a) CAPMTION b)TITLE c)HEAD
6) In type of list, list items are marked with bullets.
a) ORDERED b)DEFINITION c) NESTED d)UNORDERED
7) attribute in the body tag specify an image file to use as a background.
a) BGCOLOR b) BACKGROUND c)BGIMAGAE d) BACKGROUNDIMG
8) <a> tag has attribute. which defines URL of the document to be linked.
a) SRC b) HREF c)VREF )REF
9) Bulleted list in HTML is created by tag. (March 2019)
a) <UL>, b)<0L>, c) <B>, d) <BR>
10) HREF attribute in <A>tag stands for (March 2002)
a) Horizontal reference b)Hypertext reference
c)Hyperlink reference d)Hypermedia reference
11)To place the image into an HTML file attribute is used in IMG tag.
a) < URL>, b)
<
ALT >, c),
<
SRC>, d)< HREF> (March 2007)
12) tag is used to put a line break in HTML Code. (March 2003,2017)
a)<HR> b) <BR> c) <P> d)<TR>
I3) <A> tag has attribute which defines URL of the document to be linked.
c) VREF d) REF (March 2008)
a) SRC b) HREF
14) BORDER is attribute used in tag of HTML. (March 2016)
>, c), <TABLE>, d) < CAPTION>
a) < PRE>, b)< ADDRESS
a table. (March 2020)
15) tag is used to create rOw in
c) <t> d) <tts
a) <t> b) <th>
162 HTML

2 What is HTML?Stac advantages and disadvantages of HTML. (Oct.2003)


3) What is ALT attribute? Why it is used?
4) Explain cellspacing, cellpadding, colspan and rowspan attributes.
5) How can you include image as an background and as an hyperlink? Explain
giving examples?
With syntax diagram explain the structure of html webpage. (March 2017)
7) What are comments in HTML? Why they are required?
8) How can youhave a link to a image by having image as a link?
9) Explain with example Nested lists in HTML.
10) Explain the following HTML tags with one example of each:
i) <PRE>, ii) <SUP>, iii)<MARQUEE> (Mar.2004)
11) Explain the use of following HTML tags with example: (Mar.2005)
i)<0L> i)<TR> i) <B>
12) Explain the following HTML tags with one example of each: (Mar.2007)
i) <P> ii)<Ls iii) <PRE>
13) Explain the following HTML tags with one example of each: (Mar.2008)
i) <MARQUEE> ii) <SUB> iii) <BODY>
14) What is character formatting HTML?
in
15) Explain following tags with example:
<sup> <marquee> <hr><br <p> <script> (March 2002)
16) What are types of ist? Explain with the example
17) What is script? Why it is required?
18) Explain changing color scheme of web pages.
19) Write advantages and disadvantages of HTML. (March 2019)
20) Explain general structure of HTML page. (March 2020)
> Write HTML code to do following:
1.Write HTML code to do following..-
a) Give title to your web page as "Exam".
b) Include background color as pink and text in green colour. Have a different
font for page title and contents of the page.
c) Have a hyperlink to different page having url as "Result1.htm"
d) The resultant web page of this hyperlink should contain scrolling text as “All
THE BEST" inbold, italic and black color and light blue as a background color.
2.Write HTML code to do following.:-
a) Give title to your web page as "TUTORIAL'".
b) Include background color as light blue and
c) Text in red color.
d) Have a image “IMAGE.JPG" as an hyperlink.
e) The resultant web page of this hyperlink should contain scrolling
text as"Best Of Luck" in bold, italic and green color. Ano
"IMGNEW.JPG" image as the background of the page.
HTML
163
3. Write HTML code for following.:--
Collge Name:S.P.College.

Admission data.

Streams capacity
Commerce 150
Science 100
Arts 100
Here Admission data. Should be the scrolling text.
Collge Name:S.P.College should be in bold, italics and in red color.
It should be hyper linked with th page containing college information.

4,
Write HTML COde for following.:-..
Collge Name:Cummins College Of Engg.

CCOEW

Courses No.of students.


Computer 120
Instrumentation 80
E& TC 60

as: CCOEW
Where image LOGO.JPG" is shown

5. Write HTML code to do following:

Todays Special;--
With toppings Rs.150.
PIZZA Rs.125.
Without toppings
(Domino's) Rs.40.
Mashroom PavBhaji
Cheese PavBhaji Rs.42. (WithButter) Rs.40.
PavBhaji Jain PavBhaji Rs.40.

(Mar.2004)
Write the HTML code for the
following table:
Year
2000 2001
1999
750 1,200
300
Units Rs. 12,0J0
Sales Rs. 3,000 Rs. 7,500
Income
164 HTML

7. Write a the HTML code for


the following: (Mar.2006)

Faculty

Arts Science Commercel

Boys 100 400 500


Students
Girls 300 300 400

8. Write the exact output of the following HTML code with font spcification in
brackets: (Mar.2006)
<HTML>
<TITLE> Introduction </TITLE>
<BODY>
<H> <B> Computer Science </B></H1>
<HR>
<U> EBalaguru Samy </U>
<iHR>
<IA> Achut S Godbole </H4>
<BODY>
SHTML>
9. Write the HTML code for the following table.
(Mar.2008)

Year
2000 2001 2002
Units 500 1000 1500
Sale
Income Rs. 5,000
Rs. 10,000 Rs. 15,000

Answers Q. (1)
1) <HEAD>, 2) <BODY>, 3) VLINK, 4) HSPACE, 5)
UNORDERED,
6)BACKGROUND, 7) HREF,8) Uniform Resource Locator,
9) <UL> 10))<BR> 11) < SRC >12) <BR> 13) HREF
14)<TABLE> 15) <tr>

O00
PAPER-I
PRACTICALS
INTRODUCTION
The students ofering this vocational Computer Science (D9) course are expected to
be more perfect in practical. The course is more practical, and work experience
oriented. The syllabus is arranged keeping in view that after completing this course,
the candidate can write simple programs in assembly language, C++ and Visual Basic
HTML code as well as execute the programs independently. This course would be
definitely helpful with additional advantage to the students who will go for higher
education i.e. Diploma and Degree course.
All practical for S.Y.J.C. Computer Science course are based on C++, HTML and VB
for Paper-I and an assembly level language programming of 8085 for Paper-II. In this
part of the book, guidelines for performing practical, scheme of examination, marks
distribution, and other information are discussed.
are provided.)
(Note : For paper-II an instruction set with Opcode chart, ASCII chart

Scheme of Examination
paper.
The time duration for theory and practical examination is 3 Hours for each
one experiment from those
During the examination, candidate has to perform only
year.
experiments, which have been conducted during the
on the basis of
The term work 40 marks will be given by the internal teacher year.
performance of the student and the journal competed during the

HINTS FOR PRACTICAL (PAPER-I)


A) C++ Programming
on your answer paper.
1) Write down problen statement stepwiselalgorithmic format.
2) Try to analyse the problem and implement it in
answer paper)
(need not draw algorithm/flowchart in
3) Accordingly write C++ program.
program and try to find the output of it.
4) Paper trace the
5) Code the C++ program in PC
youcan use VC++ editor or standard tcc (C++
IDE) editor
6) Save the file as filename.CPP your program.
7) Include all the standard library files (e.g. string.h, io.h, etc) in
any syntactical errors like missing
8) Compile the program. If it contains
etc., try to remove them.
semicolon, use keyword for declaring variables,
9) After removing all the
errors, run the program. If you are still not getting the
may contain logical errors. So use Debug
required output, your prOgram program.
utility for stepwise debugging of the copy it.
progran and take Hard of
10) Finally run the
166 Practical (Paper

B) HTML
1) Write HTML code in Notepad (or any
standard text editor) if you are using
windows operating system
2) Save that file as filename HTML
3) Open the same file through web browser loaded on your
machine. (in Internet
Explorer)
4) Output HTML file is interpreted by the browser
5) If you make changes in source code (HTML)
file, and see the output for this
change code, click on Refresh button in browser's window.

C) VISUAL BASIC
1) Read the problem statement
and analyse visual design (i.e. which controls are
to be used) and associated event
procedures that forms coding part.
2) Using VB create a new project.
a) First draw design-using controls on form
and then write code in code
window
b)Run the project
3) Extension for form file is .frm
and for project .vbp
4) During run mode you may get some errors.
watch facility. Correct it and execute again use

Some Common Errors:


1) Try to avoid using keywords
for variable names.
2) Try to match the brackets
of the loops.
3) Indentations in a program helps you
to
of{ brackets in a loop; so indent yourfigure out the mistakes mismatching
program. in
4) Declaration of all the variables
that you use in your program must.
5) Give necessary comments is
(especially for çomplex logic)
After successful running of program you can whenever necessary.
6) If you use standard remove them.
library functions like clrscr(),
(ctrl+Flin C++ IDE editor) getch), by seeing the help
include required header
7) In case of HTML indent your files in your program.
code. Give tags whenever necessary.
8) The order of nested tags
should be proper.
9) If you have included
-image/document to be linked
document, give the whole path. with some part of your
10) Try to avoid big/large-sized
images, since it increases
11)To see the desired the size of memory.
effect for a wave page, modify
output interpreted through the source code and see the
error has occurred. browser. Since browser cannot show you
where
12) In VB If there are
multiple forms in your
only forms in that project. project and if you want to execute
Always check startup
properties option. object in project i.e.
Practical (Paper-I)
167
C++ PROGRAMMING PRACTICALS
Slip No.1.SWAPING
Write a function in C++ that exchanges data (passing by reference) using
Swap function to interchange the given two numbers.
#include<iostream.hs
#include<conio.h>
//clrscr() ;
void swap (float &x, float &y)

float t=x;
K=Yi
y=t;

void main()
{void swap (Eloat &,float &) ;
float a,b;
cin>>a>>b;
cout<<"a="<<a<<"b="<<b<<endl;
Swap (a,b);
cout<<"a="<<ax<"b="<b<<endl;

Output:
2
4
a=2b=4
X=4y=2
a=4b=2
Press any key to continue

Slip No.3 BINARY SEARCH


an array of given 10-sorted real
Write a program in C++ that first initialise
a belongs this array or not.
numbers. The program must verify whether given element
technique. The element (to be searched) is to be entered at the
using Binary Search
program should print its position in the
time of execution. If the number is found, the
not found,"
array otherwise it should print, "The number is
#include<iostream. h>
#include<conio.h>
#includesstdiib.h>
void main()
float a[10]Pi
lnt i, top, bot,mid;
168 Practical (Paper

cout<<"Type the number in ascending


for (i=0;i<10;i++) {cin>>a [il;) order"<<" \n";
top=0; bot=9;
Cout<"Type the no you want to search \n";
cin>>P;
mid= (top+bot)/2;
while( (top<=bot) && (a [mid] !=p))

if (p<a [mid] )

bot=mid-1;
else
top=mid+1;

mid= (top+bot) /2;

if (a [mid] ==p)
Cout<<"The number is at
position" <<(mid+1)
<<"\n":

else
cout<<"the number ig not found\n";

Output
Type the number in ascending
1 order
2

4
5
6
7
8
9
10
Type the no you want to search
7
The number is at position7
Practical (Paper-I) 169

Slin No.7 RATIOAND RECIPROCAL


Write a program in Ct+ with a ratio class using member functions like assign
() function to initialize its member data integer numerator and denominator), convert(
) function to convert the ratio into double, invert ( ) function to get the inverse of the
ratio and print () function to print the ratio and its reciprocal.

#include<iostream.h>
class ratio
(public:
void assign (int, int ):
ouble convert ()
void invert();
void print ();
private:
int num ,den;

void main()
{ratio x;
x.assign (22,, 7) ;
cout<<"X="i
x.print ();
cout<<"="<<*.convert()<<" \n";
x.invert ();
cout<<"1/x=" ;X.print () ;
cout<<"\n"

void ratio: :assign (int numerator, int denominator)


num=numeratori
den=denominator;

ouble ratio::convert ()
(
return double ( (num) /den);

void ratio: :invert()


{int temp=nun;
num=den;
den=temp;

void ratio: :print ()


{cout<<num<<"/"<<den;
170 Practical(Paper

Output:
X=22/7=3
1/x=7/22
Press any key to continue

Slip No.8 CIRCLE AREA


Implement a circle class in C++. Each object of this will represent a circle
storing its radius and X and Y co-ordinates of its centers as floats. Include a default
constructor, access functions, an area and circumference of the circle.

#include<iostreamo. h>
#include<conio.h>
class circle
{ private:
£loat X,Y,r;
float areal, circum;
public:
void assign()2
void area()
void circumnf () ;
'void print ():
}:
void circle::assign()
{cout<<"type the x & yco-ordinates
\n": of the centre
cin>>X>>Yi
cout<<"type the radius";
cin>>r;

void circle: :area()


{area1=3.14*r*r;)
void circle: :circumf ()
circum=2*3.14*r;
void circle: :print()
cout<<"X,y co-ordinate "<<x<<"\t"<«y<<endl;
cout<<"the radiug is"<«r<«endl;
Cout<<"the area is"<<areal<«endl;
cout<<"the circumference ig"<<circum<<endl;
void main()
{clrscr() ;
Practical (Paper-I) 171

circle cl;
c1.assign() ;
c1.area();
c1.circumf ();
c1.print ();

Output:
type thex &&y c0-Ordinates of the center
2
1

type the radius2


x,y co-ordinate =2 1

the radius is2


the area is12.56
the circumference is 12.56 Press any key to continue

Slip No.9 OBJECT IS BORN


Write a program in C++ that initialises a Ratio class with no parameters, as a
default constructor the program must print the message "OBJECT IS BORN" during
initialisation. It should display the message "NOW X IS ALIVE", When the first
member function Ratio x is called. The program must display "OBJECT DIES" when
the class destructor is called for the object when it reached the end of its scope.

#include<iostream.h>
class ratio
public:
ratio ()
{cout<<"object is born\n";)
~ratio()
{cout<<"object dies \n":)
private:
int num, den;

void main()
(ratio X;
Cout<<"now x is alive \n";
cout<« "at end of program \n"i

Output:
object is born
now x is alive
at end of program
Practical (Paper-n
172

object dies
Press any key to continue

Slip No.10 COMPLEX NUMBER AND SUM


Write a program in C++ with a complex constructor to add the given two
complex numbers. The program should print the given complex number and their
Sum.

#include<iostream. h>
class complex{
£loat *,yi
public:
Complex() {)
complex (£loat real, float img)
{x=real;y=img;

complex operator+ (complex):


void display (void) :
};
Complex complex: :operator +(complex c)
{complex t;
t.x=X+C.*;
t.y=y+C.Yi
return(t);

void complex: :display (void)

cout<<X«<"+j "<<y<<"\n":

void main()
{complex cl, c2, c3;
cl=complex (2 .5,3.5) ;
c2=complex (1.6,2.7):
c3=c1+c2;
cout<<"cl="; c1.isplay ( ):
cout<<"c2="; c2.display ();
cout<<"c3="; C3.display ():
Output:
cl=2.5+j3.5
c2=1.6+j2.7
c3=4.1+j6.2
Press any key to continue
Practical (Paper-I) 173

Slip No. 11 ADDITION AND DIVISION OPERATOR.


Write a program in C++ to implement the addition and division operator for
the ratio class. Hence print the given two ratios x&y, their sum(x +y) and
division(x/y);

#include<iostream. h>
class ratio
(Eloat X,Y;
public:
ratio (0)
ratio (£loat p, float g)
{x=pi
y=g;

ratio operator + (ratio);


ratio operator / (ratio);
void display (void) ;

+
ratio ratio: :operator (ratio c)
{ratio t;
t.x=x+C.X;
t.y=y+C.y;
return (t);

ratio ratio: : operator / (ratio c)


(ratio t
t.x=X/c.x;
t.y=y/c.y;
return(t);

void ratio:: display (void)


{coutK<"X="<<*<<"\t"<< "y="<<Y;

void main()
(ratio r1,r2,r3,r4;
rl=ratio (2.5,3.5) i
r2=ratio (1.6, 2.9):
r3=r1+r2;
r4=r1/r2;
Cout<<"rl=";r1.display ();cout<<"\n":
Cout<<"r2="r2.isplay(); cout<<"\n"; z
Cout<<"r3=";r3.display cout<<"\n": 0
174 Practical (Paper-)

cout<<"r4=";r4.display () ;

Output:
rl=x=2.5 y=3.5
r2=x=1.6 y=2.9
r3=x=4.1 y=6.4
r4=x=1.5625 y=l.2069Press any key to continue

Slip No.i2CLASS HIERARCHY


a) Write a program in C++ to implement the following class hierarchy: Class
student to obtain Roll Number, Class Test to obtain marks scored in two
different subjects, Class sports to obtain weightage (marks) in sports and Class
Result to calculate the marks. The program must print the roll number,
individual marks obtained in two subject, sports and total marks.

Student

Test Sports

Result

#include<iostream.h>
class student
{

int roll_no;
public:
void get no (int a) {
roll_no=a;
void put_no (void)
{cout<<"rol1_no: 0"<<roll_no ;

class test:public student


{public:
£loat s1, s2;
public:
void get marks (£loat X, £loat y)
{sl=x; s2=y;

void put_marks (void)


{cout<<"marks odtained \nsl="<<sl<"\n s2="<<s2;
Practical (Paper-I)
175

class sports

public:
int SCore;
void get_score (int x)
{score=x;}
void put_score (void)
{cout<<"sports marks:"<<score;
}

class result :public test,public sports


(float tot;
:
public
void display (void)
{tot=s1+s2 +9core;
put _no ();
put marks ():
put _score ();
Cout<<"total scOre="<<tot;

void main()
{result st1;
st1.get_no (101) ;
st1.get marks(39, 65) ;
st1.get _scOre (29);
st1.display();

Output:
roll_no:0101marks obtained:
sl=39
S2=65sports marks:29total score=133
Press any key to continue

Slip No.13 VIRTUAL FUNCTION


program must declare p to
Write a program in C++ using virtual function. The
a pointer to objects of the base class person. First, the program must
p to point an
person. The program must then
instance x (name of the person e.g. "BOB")of class
e.g. "TOM") of the derived
assign p to point at an instance y (name of the student,
class student.
176 Practical (Paper
Dcfine a print () function in the base class such that it invokes
the same base class
function to print the name of the person by default. The second call
should evoke the derived class the name of the student.
for the same

#include<iostream.h>
#include<string.h>
class persOn{
public:
person (char* s)

name=new char [strlen (s+1)];


strcpy (name,s);

void print ()

Cout<<"my name is"<<name ;


protected:
char * name
-};
class student : public person{
float rno;
public:
student (char *s, float r):person (s),rno (r)
void print ()

Cout<<"my name is "<<name <<" my


rno
is"<<rno;}
}

Void main( )
{person *p;
person x("bob");
p=&x;
p ->print () ;
student y
("tom",101);
p=&y;
p->print () ;

Output:
My nanme bob my name tom
Practical (Paper-I)
177

Slip
No.14 VISUAL BASIC
a) Write a program in VB to find the sum of first 100 numbers
entered using
DOLoop.

Rem *
*
r**Do-Loop***
Private Sub Form_Load(0
Dim a, sum As Integer
Sum = 0
a = 1
Do
Sum = Sum + a
a
a + =

Loop While a <= 100


MsgBOx ("The sum of Sum &
first 100 numbers ig

","), vbInformation
End

End Sub

Slip No. 15 HTML


a) Create simple HTML pages on
any of the following topics.
or Software Development Company.
College profile, Computer Manufacturer,
page must at least 3 paragraphs of text. The page must have an appropriate
The of and hyperlinks to other pages. The
title, background color or background image,
must have text consisting of different colors and style in terms of
paragraphs
alignment and Font size. of the
Save the file and view the
same using any HTML Browser. Verify functioning
hyperlinks.
b) Obtain a hardcopy of the HTML code only.

HOmepage : binary_soft.html
Source Code of Binarysoft.html
<html>
<head> SOLUTION</h1>
<nl align="center">BINARY
</head>
<body bgcolor-"skyblue">
<p>
<font size=5 color="red"> a software devlopment
is
SO>Binary Solution</b> Website devlopment.
COmpany, It focuses on Net
&
provide solutions using Web and Dot
software
Technology.
178 Practical (Paper.

It's head office is at Pune The company have offices all


over India and UsA
</font>
</p>

<p>
<font size+2 color="green">
<i>It is company which provides creative atmosphere for
employees.
It alsoprovides different faclities to their
employees.Employees can
Work and develop their own ideas.Ths they can convert
their virtual ideas
into reality.</i>
</font>
</p>

Further you can contact at following address:


<pre>
Binary Solutions,
25,Anand Society,
Sinhagad Road,
Pune.
Phone :24359871
Email :binary [email protected]
</pre>
<A HREF="c: \taraka\clients.html ">
<align="right"><h2 >CLIENTS</h2></align> </A>
</body>
</html>

Link Page: clients.html


<html>
<head>
<h1 align="center">BINARY SOLUTION</h1>
</head>
<body bgcolor="skyblue">
<hl>clients</hl>
<ol>
<li>Borgaon Sugar Factory</li>
<li>Indo Instruments</1i>
<li>Nehru English School</li>
<li>ABC Publications</li>
Practical (
179
<lis Indian Insurance Company</li>
¿lisToyato Lini ted</1i>
</ol>
</body
</html>

Output:
FD-XICompu04\paperilhtml home.html- Microsoft Internet Explorer
File Edt Yiew Favorites Iools Helo
Address DICompu04\paperilhtml_home.html EGOLinks 2
l
BINARY SOLUTION
Binary Solution is a software devlopment companyIt foçuses on Website deviopment. It provide software solutions using Weo and Dot Net
Techaology.I's he ad office is at Pune .The company haye offices all over Irdia and USA

Ls compary which provides craative atiosphere for employces.


Pheir empioyecs.Employees can work cnd develop their own ideas.Tus they can t also provdescomert
duerentfactiesto
their virual
ideas into realiy.

Futher you ca contact at following address:


Binary Solutions,
25, Anand Society,
Sinhagad Road,
Pune.
Phone:24359871
Email:binary s@rediffmail:com

CLIENTS

IMComputer.3SOAyGE 536PM

DO0.

You might also like