CS 1 Compressed
CS 1 Compressed
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.
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:
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.
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.
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
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.
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
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
File Name
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.
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.
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
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
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.
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
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
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,.
Process A
(ii)
ProcessB
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.
0
O/S
(Monitor)
P
User Process
Area
max.
Fig. (1.11) Single contiguous memory management
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
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
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
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) 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
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)
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
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.
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.
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.
Status Bar
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 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.
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.
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.
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
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) 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.
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
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:
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
No
Condition
Yes
Module A
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
Multiple Alternatives
If condition [1] then:
[Module A1]
Else if condition [2] then:
[Module A2]
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
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]
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 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.
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
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.
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 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.
Here elements in arrays name, address, phone, and stream, with same
subscript belong to the same record.
START
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
Level 0
1
Level
D Level 2
Leve! 3
M Level 4
subtree.
LEVEL The distance from the ROOT. The ROOT is always at
zero (0) level.
50 pata Struct
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
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
-
->
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
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
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
4) B is deleted:
D E
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'
9. Write the difference between linear search and binary search. (Mar. 2017)
10. Explain any.four data structure operations.
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
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)
26. What is binary tree? Draw the tree structure for the following expression:
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
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
> 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.))
> 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
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:
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.
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.
private:int number;
protected:int data;
public: void getdata()
void putdata()
};
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( ).
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.
public: int i;
void display( )
void main( )
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.
#include <iostream.h>
class ABC
cout<<"Enter number:'";
cin>>data;
cout<<"You entered:"<<data;
obj.data = -obj.data;
cout<<"Now number is changed to:"<<obj.data;
}
void main( )
ABC objl;
objl-getdata( );
obj1.putdata(objl);
}
private:int number;
public:void getdata()
cout<<"\nEnter number:";
cin>>number;
cout<<number;
void putdata()
};
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:
public:
int data;
void getdata()
{ cout<<'"Enter number:'";
cin>>data;
void putdata( );
void ABC::putdata()
void main()
{
ABC obj;
obj-getdata( );
obj.putdata();
}
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.
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
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.
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()
};
B bobj; Ilvalid.
void display()
bobj.getbdata( );
}};
void main( )
{
A aobj;
I/B bobj; Iinvalid.
aobj-getadata( );
aobj.display( );
}
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( )
{
int data;
public: ABC) I/ default constructor
void main( )
{
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
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
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
width = 5;
height = 5;
}
void main ()
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:
ABC::~ABC ()
delete width;
delete height;
void main ()
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:
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.
++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( );
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
compiler to use public inheritance. The type of inheritance influences the acce,:
rights to clements of the various super classes
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.
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
Derived
Derived
Derived1.
Derived 1
Derivedn
Derivedn
5.Hybrid Inheritance
Base 1
Derived1 Derived 2
Derived
I/ body of class
e.g:
class A
82 C++ Program
{
Ibody of class A
class B : public A
I/ body of class B
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
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.
#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";
};
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.
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,
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.
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
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
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
include <iostream.h>
çlass basel
void main( )
derived obj;
obj.show(0; llambiguous to the compile
obj.base2::show( ); I/function from base2 class.
}
protected: int j;
public:
Base(int y)
j=y;
cout << ""Base class constructor
called.n";
C++ Programming 89
-Base( )
{
:
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);
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;
class Base
public:
int a;
public: int b;
};
C++ Programming 91
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
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)
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.
Derived1 objl;
Derived2 obj2;
Base *ptr;
ptr=&objl;
ptr->display0;
ptr=&obj2;
ptr->display0;
};
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.
#include<iostream.h>
class Base
{
Derived1 objl;
Derived2 obj2;
Base *ptr;
ptr=&objl;
ptr->display0;
ptr=&obj2;
ptr->display0;
}
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,
Medical Enggineeing
(CEISore ,Div) (PCM &ore, stream, name)
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
{
data=100;
friend class B;
};
class B
void main ()
B obj;
A objl;
obj.friendclass (obj1);
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
class B
98 C++ Programm,
return (aobj.data+bobj.data);
void main()
A objl;
B obj2;
cout<<friendfunction(objl,obj2);
}
Exercise: Writer a program in C++ to swap private data values in two classes
using friend function.(Assume single integer data member )
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.
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.
#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( );
#include<string.h>
#include<iostream.h>
class String
private:
int size;
102 C++ Programmi
char str[80];
int nol,no2;
public: String)
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 r;
r.n n2.d+d*f2.n;
=
r.d = d*f2.d;
return (r);
fractionr;
r.n =n*f2.d;
r.d= d*f2.n;
return (r);
void fraction::getfr(void)
cin >> d;
void fraction:printfr(void)
long double r;
r=long double(n/d); .
cout <<n<«
"" <«d<<"="<<r<<" ":
void main)
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.
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.
fun
statements
float result = 0;
for (int cnt = 0; cnt < size; cnt++)
result = result * cnt;
return result;
C++ Programm
106
private:
char str [size];
public:
string ()
{
str[0] = "\0';
void display()
};
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
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.
(destination) (source)
We can put conversion routine in either destination
or source class.
private:
double radius;
double angle;
public:
polar ( )
radius = 0.0;
angle = 0.0;
radius =r;
angle = a;
void display ( )
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;
void display ()
void main ()
rec reccord;
polar polcoord (10.0, 0.7855398);
reccord = polcoord;
cout <<"nPolar coordinates:\n";
polcoord.display ( );
cout<<"nRectangular Coordinates: \n";
reccord.display ( );
istream ostream
fstreambase ofstream
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
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;
# include <fstream.h>
#include< string.h>
void main)
{
char ch;
ifstream f1 (Test.txt);
while (f1)
{
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.
need to use some devices like floppy disk/hard disk to store the data. This data is
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.
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
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.
:
seekg( ) fun with two arguments
Begin End
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;
if(fin1.eof) != 0)
finl.getline(line, SIZE);
cout << line << "\t";
if(fin2.eof) !=0)
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
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;
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
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
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 ++;
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
(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.
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
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.
HTML Editors
HTML Editors are programming tools for Hyper Text Markup Language
(HTML) documents.
There are three categories of HTML Editors:
1. Text Editors
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.
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
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>
Syntax
<HEAD>...SHEAD>
HTML
130
C.g. <HTML>
<HEAD>
<TITLE>WELCOME TO FIRST WEBSITE<TITLE>
HEAD>
<HTML>
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.
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.
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
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).
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.
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
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)
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:
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
• Scripted Programming
• Structured Programming
o Basic
o Pascal
• Object Oriented Languages
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.
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.
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
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
<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
<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
SUNDAY MONDAY
WEDNESSDAY THURSDAY
</BODY>
SHTML>
so output dispiayed by browser. is :-
PRGRAMMING LANGUAGE
JAVA
OBJECT ORIENTED LANGUAGE
C++
C
sTRUCTURED LANGUAGE
BASIC
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
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.
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>
values in the
you can make a picture larger or smaller changing the
Ihus
HEIGHT"
and "WIDTH"
attributes of the img tag.
152 HTML
>
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>
<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
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
A new browser willunderstand that the script should be executed, even comment
if
tags surTound it.
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>
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.
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
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
Output is:
lists- Microsoft Internet Explorer
Eile Edit View Favorites Iools Help
Address ] DAONine nm
htnd
lies\ists.htm EGoLinks
Sanple of Unordered lists
ELLO
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>
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>
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
as: CCOEW
Where image LOGO.JPG" is shown
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
Faculty
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
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
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
if (p<a [mid] )
bot=mid-1;
else
top=mid+1;
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
#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"
ouble ratio::convert ()
(
return double ( (num) /den);
Output:
X=22/7=3
1/x=7/22
Press any key to continue
#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;
circle cl;
c1.assign() ;
c1.area();
c1.circumf ();
c1.print ();
Output:
type thex &&y c0-Ordinates of the center
2
1
#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
#include<iostream. h>
class complex{
£loat *,yi
public:
Complex() {)
complex (£loat real, float img)
{x=real;y=img;
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
#include<iostream. h>
class ratio
(Eloat X,Y;
public:
ratio (0)
ratio (£loat p, float g)
{x=pi
y=g;
+
ratio ratio: :operator (ratio c)
{ratio t;
t.x=x+C.X;
t.y=y+C.y;
return (t);
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
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 sports
public:
int SCore;
void get_score (int x)
{score=x;}
void put_score (void)
{cout<<"sports marks:"<<score;
}
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
#include<iostream.h>
#include<string.h>
class persOn{
public:
person (char* s)
void print ()
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 + =
","), vbInformation
End
End Sub
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.
<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>
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
CLIENTS
IMComputer.3SOAyGE 536PM
DO0.