WILLINGDON COLLEGE, SANGLI
ELECTRONICSELECTRONICS (B. Sc.-II)
OS, DS, C++, HTML
Moodle
9
ELECTRONICS
OPERATNG SYSTEM, DATA STRUCTURE, C++ and HTML
Moodle developed
By
Dr. S. R. Kumbhar
Department of Electronics
Willingdon College Sangli
For B. Sc. I Electronics, Computer Science Students
3
Moodle 9
Index
S.
No.
Chapter
No.
Moodle content Name Pages
1 CH1 Operating System 4-24
2 CH2 Data structure 25-38
3 CH3 Introduction to C++ 39-76
4 CH4 HTML Programming 77-96
4
CHAPTER - I
OPERATING SYSTEM
What is operating system
An operating system is a program which acts as an interface between user of computer and computer
hardware. The OS provides the environment in which the programs are executed. Operating system is a set of
software programs normally supplied along with the hardware for the effective and easy use of machine. Here are
two benefits of operating system that enhances its utility are –
To make the computer system convinent to use in efficient manner
Fig. 1.1 Components of O.S.
The OS is divided into 4 components
1) hardware (CPU, memory, I/O devices)
2) Operating system
3) Application programs
4) The user ( People, machines or computer )
1) The basic resources of the computer system are provided by the hardware, software and data
2) It provides the proper use of resources in computer system.
3) It works as resource allocator. The resources like CPU time, memory space, file storage, I/O devices are
allocated to the program and user by operating system.
4) It is viewed as control program
5) Provision of security / confidentiality of information to the users.
6) Elimination of duplicate efforts by hundreds of programmers in developing tidious and complicated routines.
7) It keeps the track of all files and all sectors allocated to them.
8) It also keeps the rack of free sectors and files to be allocated
Different services of operating system
Operating systems have different types of services that can provide user to read and write records. From a
system programmer’s point of view, the operating system can be considered to be a collection of many such callable
programs or services, which are, categorized under 3 heads-
1) Information Management (IM)
2) Process Management (PM)
3) Memory management (MM)
1) Information management services :
Information management is a set of services used for storing, modifying, retrieving or moving the
information of various devices. The organization of the information in terms of directories and file, allocating and
Application program
O. S.
User
5
deallocating the sectors to various files, maintaining and enforcing the access control to ensure the right person have
to access the information and driving the various devices. These are normally provided with single usr or multi-user
operating systems.
1) Create a file
2) Create a directory
3) Open a file.
4) Close a file
5) Write data to buffer from file
6) Read data from file to buffer
7) Move the cursor ( file pointer)
8) Read and returns the file status
9) Create a pipe.
10) Create a link
11) Change working directory.
2) Process Management (PM) :
If the operating system supports multiple users in case of UNIX then services provided through the process
management are very important. In modern multi-user operating system a number of users located at different
terminals, which can run same or different programs with the help of attributer. A computer has only one CPU,
which has one set of IR, PC, MAR, MBR and other registers, So it can execute only one instruction at a time.
The main function of the operating system in this regard is to keep track of all the competing processes, schedules
then, dispatches them one after the other, but while doing so try to give each user an impression that he has the full
control of the CPU. The process management calls are as follows –
1) Create a child process identical to parent.
2) Wait for a child process to terminate.
3) Terminate the process.
4) Changing the process priority.
5) Process blocking.
6) Ready process.
7) Dispatching a process.
8) Suspending a process.
9) Resuming a process.
10) Delaying a process.
Memory Management
The services provided under memory management are directed to keep track of memory and allocating /
deallocating it to various processes. The operating system keeps a list of a free memory management locations before
program is loaded in the memory from the disk. This memory management module consults the free lists, allocates
the memory to the process, depending upon the program size and updates the free memory list.
1) Allocate a chuck of memory to processor.
2) Free a chuck of memory from processor.
6
LINUX
It is a fast developing operating system similar to UNIX. LINUX was developed by a student Linus Torvalds
in 1991. He wrote kernel for 32 bit Linux. Linux system was freely available on the Internet so a lot of developers
contributed in the development of Linux. The basic Linux system is standard environment for applications and user
programming. The Linux kernel is distributed under General Public License. It is not a public domain software. It is
a free software i.e. the people can buy it without copy write, modify it and use it in any manner.
Linux is composed of Kernel, system libraries and system utilities.
1) Kernel : It maintains all important abstractions of operating system such as process and virtual memory.
2) System library is a standard set of functions through which the application can be interact.
3) The system utilities are the programs that perform individual, specialized management tasks.
Features of Linux
1) It is free software
2) It has wide applications.
3) It has a standard interface to user and programmer.
4) It is a multi-user, multitasking operating system.
5) It can run on wide variety of platforms.
6) It provides large functions from limited resources.
7) MMU uses page sharing and pages are available on demand.
WINDOWS –98
Microsoft developed the operating system referred as MS-DOS or PC DOS for Ist IBM computers, which
released its 1.0 as a version in 1981. Later on Microsoft developed higher versions of DOS. The graphical user
interface called windows 3.0 version was developed by Microsoft, which was more user friendly than the DOS. The
Microsoft developed more user-friendly softwares called as windows –95, windows-98 is upgraded version of
windows operating system. The features of win 98 are –
Faster in speed, by using maintenance wizard the computer speed and efficiency can be improved.
Easier to use and multitasking operating system.
True web integration : using World Wide Web is easier and faster. The connection to web is simple.
More entertainment : Win-98 supports DVD and digital audio. TV broadcast can also be observed on
computers.
WINDOWS NT
As MS-DOS environment can not write many applications as per requirement. To overcome these
difficulties of MS-DOS Windows NT was developed.
1) It is a full-fledged operating system like windows.
2) It cam work on wide variety of platforms.
3) It does not need MS-DOS to run underneath.
System utilities
System libraries
Kernel
7
4) It is also a portable operating system like UNIX and has ability to run on other hardware platforms. This ensures
consistency of applications across a variety of platforms. The hardware currently supported by Windows NT
includes Intel X86 family, silicon graphics, MIPS RS400, RISC and digital equipment corp’s Alpha processor.
5) Windows NT is a multi-user and multitasking operating system.
6) It includes virtual memory management, threads, primitive multitasking, symmetric multi-processing and built in
networking.
7) It has multiple fast response for multiple running applications.
8) The tasks are scheduled by the operating system by giving a time slice to each task and when its time slice is
over next one is started.
9) It is a 32-bit operating system.
10) It supports virtual memory management.
11) The file name may have the length of 256 characters.
12) Windows NT has a modular architecture divided into different subsystems and layers.
The lowest layer is hardware abstraction layer which provides all the hardware specific functions. This layer
handles the interrupts, DMA memory management and multiprocessor synchronization. Next to this layers, the
Windows NT kernel; provides the basic operating system services like scheduling threads and tasks, which together
forms the executive. These have a well defined interface and one module can be replaced by another to handle the
same function when upgrading.
Architecture of Windows NT
User mode
Kernel mode
Hardware Services.
Fig. 1 Architecture of Windows NT
The six sub systems are as follows.-
Object manager : Which creates, manages and deletes objects, which are processes, threads, named pipes and
files.
Process manager : Creates, terminates, suspends and resumes processes, tasks and threads.
Log on process Win – 16 Posix appl
Security sub sys
Win – 32 subsystem
Object
Manager
Process
Manager
Local procedure
call facility Virtual
manager
security
Manage
r
Kernel
HAL Hardware Abstraction Layer.
authentication
OS/2 sub sys
OS/2 appl
Win16 Vdm
Win – 32
POSIX
subsystem
I / O Manager
File system
Cache mem
Device driver
8
Virtual memory manager. : It manages the memory for the process. It allocates and frees memory. This
subsystem also handles paging and memory protection from other processes. Each process can access upto 2 GB
of virtual memory.
Security reference monitor : Enforces security policy and keeps track of file access rights based on the
ownership and permissions for the user.
Local procedure call facility : Used to pass messages between client systems and subsystems on one system.
I/O subsystem handles the device drivers and passes data to and receives data from the devices of all the
subsystems.
Concepts related to Information Management
Information management system can be of two types-
1) File systems (FS)
2) Device drivers (DD)
1) File system: The file system in the information management allows the user to define files and directories and
allocate / deallocate space to each file. For convenient use of computer system, the operating system provides
uniform logical view of information storage. A file is a collection of related information. It may either data or
program. The given data may be numeric or alphanumeric. The file consists of sequence of bits, bytes, lines or
records. A file is named and is referred by its name.
File type:
File is nothing but it is a definite structured record used in daily life. Generally it contains record of similar
information. Example: Employee file or sale file, bill file, etc. The user programmer needs to define various files to
facilitate his work on the computer.
A text file is organized by number or lines while the source file has sequence of subroutine and functions
consisting of executable statements. The object file is sequence of words organized into loader record blocks
Tape base systems :
Early file were tape based system which are simple but inefficient. The large no. of file can be stored onto
the disk as the length of the real is very long, so there is necessary to add the directory of list of files and their storing
device. Finding file on the tape-based devices is time consuming. Entire tape is to be copied while the modification
of file. The tape based system is useful in machine to machine data transfer of backup file.
Disk based systems :
Tape based systems has number of problems which was solved in disk based system in which a circular disk is
divided into tracks and the number of tracks are also further divided into number of sectors, which is the smallest
unit of information. The sectors ranges from 32 bytes to 4096 bytes and 4 to 32 sectors per track and also disk has 75
to 500 tracks per disk surface.
0 1st sector
Track 0
7 2nd sector
Last track
6 3rd sector
9
5 4th sector
Fig. 3 Tracks and sectors
Hard Disk :
Read write mechanism is shown in the fig. 4. Hard disk contains large no. of disks which are placed close
compact on the spindle and can be made to rotate when desired. Each disk has two surfaces and we have to specify
the disk space and surface to access the data from disk. After providing the surface and disk number the read write
head moves to correct location and time required to move to correct position is called seek time. The time required
to go to the requested sector below the heads is called rotational delay ( Latency time ).
Arm
Rotor
Cylinder Read write head
Rotor
Fig. 4 Hard disk.
Blocks : Disk is divided into number of blocks in terms of size of sector. All disk I/O are same in size. A UNIX
consists of 512 bytes per block. Therefore a file of 1750 bytes is allocated in 4 blocks, 298 bytes goes to waste. This
is internal fragmentation. Larger block sizes causes more internal fragmentation.
File operation :
File operation is related with system calls that can be used to read, write, create, rewind, and delete a file.
1) Creation of file : For file creation space must be created and then new name must be added in the directory. The
directory records, names, size, date, location, etc.
2) Writing a file : Write file specifies the name of the file and information to be written to the file. The written
information is always pointed by a pointer which must be updated.
3) Reading a file : This file specifies the name of the file from where information is to be read and next block is put
into the memory. Again directory is searched and pointer is moved to the next block to the read. Every time
pointer is updated.
4) Rewind a file : From the current position the pointer resets to beginning of the file is called rewind a file.
5) Delete a file : To delete a file directory searches for a file for its name and information of that file along with
name is deleted and space is created.
DEVICE DIRECTORY
The directory keeps the list of the following information.
* File name - It should be symbolic in form.
* File type - Type of file system
* Location – A pointer to device and location of that device on the file.
10
* Size : In bytes, words, blocks.
* Current position : Read / write position in file.
* Protection : Protection against reading writing and exceeding.
* Time, date and process identification.
* Usage count
Access methods:
The stored information is retrieved for further use, modification, reading, etc. from the stored devices and the
retrieval property of that particular device is either sequential or direct.
1) Sequential Access : In sequential access read or write is in sequence. The program keeps the forward or
backward for n records. It is a time consuming process. This type of access is used in tape based system which
are slower.
2) Direct access : In the direct access method a disk is divided into no. of blocks which has specific address and by
giving the address a particular information is read or written. There is no need to maintain the order addressing
to access the block. We may read block 2 then block 54 and then write 9. No restriction of order.
This also has a index of files. The index contains the pointers to the blocks.
Free Space Management :
Files are frequently deleted or created during the computer operation and the space is limited so one must
manage the free space created by deleting a file. So to keep the track of free space the file system maintains free
space list. This adds the free space to the blocks to allocate new file; when file is created then space is removed from
free space list. If the block contains 0 bit then free space is available and if block contains 1 bit then no free space is
available.
Full block
Example : 0 0 1 1 0 1 0
Free space
ALLOCATION METHOD
The direct access method of disk allows to store many files on same disk. The utilization of free space is the
best-suited accessing method, which is divided into 3 types.
1) Contiguous 2) Linked 3) Indexed.
Contiguous Allocation Method
In contiguous allocation adjoining address on the disk is stored as a set of contiguous blocks. In contiguous
allocation file is defined by disk address of the first block; if length of the file is n blocks and start bit is of A location
then it occupies blocks
A, A+ 1, A+2, A+3, -------------- A+ n-1.
.
Directory
Block 0 Block 1 Block 2 Block N
D
0 1 2 3
4T 5 6 7
B
8 9 10 11
12 13 14 15
X
16 17 18 19
file start length
B 9 3
C 17 3
D 0 2
T 4 5
Z 24 4
X 12 2
11
Fig. 5 contiguous allocation
There is directory which stores file type, start address and length of the file. Accessing a file which has been
continuously allocated is easy. It is difficult to find out the space for newly created file for that we have to find the
‘0’ bit in row. In dynamic storage allocation, disk space is viewed as a large array of disk blocks. Some of the blocks
are allocated to files and some are free and now the free space is called hole. A dynamic storage allocation problem
is how to satisfy a request size from a list of free hole. The solution of this problem is by searching hole first.
The set of holes is searched to determine which hole is best to allocate. First fit, best fit and worst fit strategies are
employed
1) First fit : This allocates the hole, which is big enough. Searching starts from beginning or previous first-fit ends
and as soon as it gets large enough hole then stops searching.
2) Best-fit : This searches entire list that smallest hole can be best fitted.
3) Worst fit : This allocates to largest hole. This can be achieved by external fragmentation, files are broken into
pieces.
Compaction
To prevent loosing the significant amount of disk space to external fragmentation, the user must run a
repackaging subroutine which basically done by storing files on some other disk and then again these files are
copied accordingly on same disk so while storing the free space is not left in between two files.
Linked Allocation Method :
In this allocation each file is linked with the disk block which may be scattered anywhere on disk. The
directory contains pointer for the first and last blocks. Each directory has a pointer, which is linked to the next file
and the last file to the end of the directory. The first disk block is used to specify the empty file. The write file
operation removes free block from free space list and writes to it. The new block is linked to the end of the file.
There is no need to specify the size of the file created, one can go on continue to grow as long as free blocks are
there. There is no external fragmentation with linked allocation. Any free block is used to satisfy the request.
The main disadvantage is that it is a sequential access. So it takes more time to access the particular location.
The other disadvantage is the pointer requires a space and if pointer is lost then it will create a big problem as well as
files are linked by the list. No reliability. It file pointer is lost there will be a chaos
Directory
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19
20 21 22 23
file start End
KHS 9 3
12
Fig. 6 Linked allocation
Indexed allocation
Indexed allocation all pointers are brought together in one location called index block and every file has its
own index block. The block stores the index of the allocated blocks. It does not suffer from external fragmentation.
The directory contains the name of the file and index block. Read or write operation is direct one. Here the main
advantage is that the list of the allocated file can be seen on one block and wastage of memory is very less. But the
disadvantage is that if the access to index block fails then all the allocation work fails. The list of all the blocks is
stored in the index block. The directory contains the address of the index.
Directory
Fig. 7 Index allocation
DEVICE DRIVER
Each I/O routines performed by computer is important. Each I/O has its own characteristics which requires
careful programming. The special subroutine written for each I/O device is called device driver. A device driver
knows how buffer, flags, registers, control & status bits should be used in the particular device. Each different type
of device has its own driver.
Terminal I/O
A terminal or VDU is a common I/O medium. The keyboard and the VDU are the two terminal I/O devices,
The keyboard is used as the input and screen is used as the output device. The terminal may be dumb or intelligent.
The dumb terminal consists of microprocessor and limited memory. It does not process I/O characteristics. The
intelligent terminal can carryout some processing on input. It is more powerful hardware as well as software.
Classification of terminal is as follows-
Terminal
RS-232 Memory mapped
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19
20 21 22 23
24 25 26 27
28 29 30 31
file Index
block
KHS 17
17
3
15
1
30
20
16
23
-1
13
Hard Copy Glass Alphanumeric Graphics
Character oriented bit oriented.
The terminal I/ is of two types RS-232 and memory mapped. The memory mapped I/O has two parts i.e.
alphanumeric and graphic bit oriented type. A typical alphanumeric screen display 25 lines each consisting of 80
characters i.e. 25 x 80 - 2000 characters. The required video RAM is 2000 bytes. At any time all the 2000 characters
stored in the RAM are displayed on the screen by Video Controller.
Concepts related to process management :
Process :
A program under execution, which has ability to computes for the CPU time and other resources, is called process.
Multiprogramming. :
A single user can’t keep either I/O or CPU busy at all the times. The task of multiprogramming is used to
increase CPU utilization. In multiprogramming two or more process are running simultaneously. If the process one
waits for an I/O, CPU will remain active as long as there is some thing to execute. The figure 2 shows the utilization
of three processes.
In multiprogramming two or more processes can be run simultaneously. If I/O process 1 is executing I/O
process 2 waits and if Process 2 is executing then process 1 waits. In this condition CPU can’t remain in idle as long
as there is some information is to execute. Some time is lost during switching from process 1 to process 2 is called
context switching. Fig. 2. Above shows the context switching process. The three processes are running
simultaneously. Keeping track of various processes running simultaneously and competing for CPU is known as the
degree of multiprogramming. As the degree of multiprogramming increases the CPU utilization increases and
process may get delayed.
RUN RUN RUN
Context switching:
Context switching means providing attention of the CPU from one process to another process. While context
switching, some time is lost and memory contents of old process are stored somewhere before loading otherwise
resetting this would be impossible even after context switching the old program will remain in main memory. The
status of the CPU registers and pointers to memory are stored in specific memory area called register save area and
then CPU start another process of execution. Both the processes remains in the main memory even after the context
switching.
Process states :
There are three basic states which manages the switching between processes.
1) Running : The process which is executed by the CPU at any moment is called process. In multiprocessor many
processes are running and operating system will have to keep track of them.
2) Ready : The process which does not wait for external event and which is not running is called ready state. He
operating system make a list of all ready process and when CPU becomes free dispatches one to ready process to
for execution.
1 2 3 idle 1 2 3 idle 1 2 3 idle
Fig. 2 Context switching
14
3) Blocked : When the process is waiting for an external event such as I/O operation then such a process is called
blocked state. The main difference between the blocked and a ready process is that blocked process can’t be
scheduled even if CPU is free. In addition to these process states new and halted stated exists.
Process scheduling :
The process scheduling has many objectives for the operating system for various process and before
designing we have to choose a set of objectives.
Fairness
Good CPU utilization (throughput)
Low turn around time.
Low waiting time
Good response time.
Here the fairness refers to give reliable services to all the users in terms of CPU time. Throughput means total
productive workdone by all the users put together. The CPU utilization is fraction of time that the CPU is busy on
average, executing the user processes or operating system.
The elapsed time between a program or a job submitted and the time when the job is completed is called
turnaround time. Waiting is a job time spends waiting in a queue of newly admitted process for the operating
system to allocate resources to it before connecting its resources. The response time is the time required to get the
result of particular job of the process. It is very useful in time sharing or real time systems.
Concept of priority:
As many processes are competing for the same available resources like CPU and memory then the concept of priority
phenomenon is useful . There are two types of priorities –
1) Global ( external) priority.
2) Local (internal) priority.
The external (global priority is specified by user externally at the time of initiating the process. In many
cases the external priority may be changed, otherwise default priority is specified. The urgent jobs are permitted to
do the jobs at the earliest. The highest priority process running indefinitely is prevented by deciding the time interval
depending up on the CPU utilization.
The concept of internal priority is used by some scheduling algorithms. They are based up on the
calculations of the current based states of process. Here the expected time of job execution is considered. Smaller
jobs are finished faster and larger has a low priority. If smaller jobs are on the queue the larger jobs may be
postponed for longer time as smaller incoming jobs have highest priority. In such conditions larger important jobs
has be given the highest priority, so they may execute first. Another advantage of internal priority is that when
smaller jobs are finished faster then the number of processes of competing CPU will decrease. The operating system
calculates the resultant priority based on both external and internal and assigns them.
Multi-tasking :
The task can be defined as an asynchronous code path within a process time in operating systems which
supports multitasking, A process consists of multiple tasks which can be run simultaneously in similar way as multi-
user operating system supports the multiple processes at the same time. In multitasking multiple states able to run
within a process which allow more flexibility and improve the CPU utilization.
Time sharing.
15
The time sharing concept uses a smaller portion of time-based computer. Each user has a separate program in
the memory, even program executes for only short time before it finishes or needs to perform I/O. In time sharing
operating system allows many users to simultaneously share the computer. Here each action of command is very
short and needs very little time of CPU. The operating system will rapidly switch the CPU to the program of some
other user. A time shared operating system allows many users simultaneously share the computer. Each action is
very small only a little time is needed for each user. Therefore it appears as all processes are running simultaneously.
CONCEPTS RELATED TO MEMORY MANAGEMENTS
The management of memory is very important and it can perform the following functions.
To keep track of all memory locations – free as well as allocated and if allocated then to which and how many.
To decide the memory allocation policy to allocation of which process and how much memory, when, as well
as where.
To use techniques and algorithms to allocate and deallocate memory locations.
The various memory management units are –
Contiguous, real memory management system has the following forms-
1) Single contiguous memory management unit.
2) Fixed partitioned memory management unit.
3) Variable partitioned memory management unit.
These systems are divided into two major parts
contiguous and non-contiguous.
Memory map of single user computer.
The operating system like MS-DOS is a single user operating system in which only single task at a time is
executed. The operating system loads the program into the main memory and assigns much memory to the system.
The typical memory map of singe user computer is shown below.
Fig. 8 Single user memory map. It consists of free memory, process, command interrupter and kernel. The kernel provides the basic operating system
services. The command interrupter interrupts operating system commands.
Partitioning :
To allow multiprogramming several operating system uses partitioning memory management method. Here
the term partition means dividing the main memory into various sections. These partitions may be of different sizes
and once divided they could not be changed are called fixed partitioning. These partitions can be allocated to process
by Operating system.
Example : 64 Kb memory can be divided into following sizes.
Free memory
Process
Command interrupter
Kernel
10 K
12 K
17 K
25 K
Monitor
Very small job
Average job
Large job
16
As the job files are entered on the system, they are put in queue. The job schedule takes place according to the
requirement of each job.
Fixed partition memory management
In fixed partition main memory is divided into various parts called partitions. In this method the partitions
are fixed at the time of generation and they can’t be changed. To change the partitions the operations should be
stopped and operating system has to be generated with different partition specifications. These partitions are also
called static partitions and operating system creates the partition description table.
17
P0
P1
P2
P3
P4
P5
Fig. 8 Fixed partitions
Limitations of fixed partitions
1) If partition size 200K is allocated to a process size of 189 K then 11 K space of that partition is wasted and can’t
be allocated to other process. This is called internal fragmentation. If 50 K is recommended and available partitions
are 30K and 20 K even though it can’t be allocated. To allocate 50 K, 50 K or more than 50 K memory partition is
necessary.
Variable partitioning
As fixed partition suffer from internal fragmentation and restriction on the number of resident processes
which puts the restrictions on degree of multiprogramming and run time CPU utilization. In variable partitions, the
number of partitions and their sizes are variable. At any time any partition of memory can be either free or allocated
to some process. In variable partition the size is not fixed. Fig. below shows the variable partitioning.
delete
job 1 allocate Job2 job 10
Delete
Advantages
This schemes waste less memory than the fixed partition.
Access time is same as that of fixed partition.
Time complexity is higher than that of fixed partitions due to various data structures.
Paging :
As the variable partitions suffer from the external fragmentation and fixed partition suffers from internal
fragmentation i.e. wastage of memory. So this wastage of memory problem can be solved by the two methods.
1) Compaction 2) Paging.
In compaction memory allocation changes to makes free space contiguous. The logical and virtual address space of
the program is divided in equal size pages and physical main memory is also divided into equal sized page frames.
Here the page is equal to the page frame, so it exactly fit into the page frame, so it can be assigned to any free page
frame.
OS
Process A
Process B
Process C
0K
100K
300 K
400K
600K
700 K
800K
Monitor
Job 2
Job 1
Job 2
Job 3
Monitor Monitor Monitor
Job 1 Job 1
Job 10
Job 3 Job 3
Job 3 Job 3
Job 10
18
Frame numbers
Fig. 9 shows the paging model
Physical memory
SEGMENTATION :
Segmentation and paging is almost similar except that pages are physical in nature and hence are of fixed
size, but segments are logical divisions of program and are of variable size.
Example : Now consider that each program in its executable form can be considered to be having 3 major segments
such as code, data and stack. Each is further divided into segments i.e. main programs and subprograms. Each
segment is complied with respect to 0 as starting address for the segment. Fig. 10 shows the example of
segmentation.
Seg.
0 0 0
999 999 499
0 0
799 799
Physical memory
Fig. 10 Memory segmentation Steps followed during initialization of process are –
1) At any time there is possibly some physical memory which is free and allocable.
2) When new process is to be created the process management module talk to Information management and access
the executable image for that program.
3) Consultation of memory management to allocate different segments.
4) After memory is allocated it built a segment map table or segment descriptor table.
Virtual Memory :
The virtual memory is a technique that the execution of the processes may not be on the disk or other storage
device. This has the advantage that can have run larger physical memory but virtual memory is difficult to implement
and it decreases the performance. This can be used in paging, segmentation method. The program is divided into
pages and loaded into memory while rest is on disk and whenever they are required loaded into memory.
If there is no page frame free in physical memory to accommodate the new page, the operating system has to
overwrite it. It looses all the updated information and later on this page is brought back on the disk.
Page 0
Page 3
Page 2
Page 1
Page 4
0
1
2
3
4
5
6
7
8
9
Page 0 0 1
Page 1 1 6
Page 2 2 4
Page 3 3 3
Page 4 4 8
Logical page table
memory
Main
Program
segment
Code
segment
1
Sub
prog.
Segmrnt 2
Data
segment
Stack
segment
Seg
Number
Size
0 1000
1 800
2 1000
3 800
4 500
Total 4100
0
1
2
3
4
5
6
1000
800
1000
800
500
4100
19
The terms of virtual memory
1) Locality of reference: The basic principle behind the virtual memory is called locality of reference. This is
forecast whether the page is likely to be used in future based on its past behavour.
2) Page fault : When the process is executing with only few pages in memory and encountered instruction which
refers to any instruction or data in some other page which is outside main memory then page fault occurs.
3) Working set : The process has number of pages in the physical memory and all of these are not referred actively.
So the pages which are actively referred are called working set.
4) Page replacement policy: As large no. of pages are in the physical memory which get occupied all page frames
and new page is to be created then overwriting the existing page in the memory called page replacement policy.
5) Dirty page : If the page is modified after it was loaded from the disk is called dirty page.
6) Demand paging : This is brought when demanded. When page fault occurs then only page is loaded in memory.
GUI ( Graphical User Interface )
In early days of computer development only certain literate people could use the computer. The cryptic
commands were used in which one has to remember commands. Now a days interface is more user friendly. These
cryptic commands were converted into graphical representation such interface is called graphical user interface
which almost eliminates cryptic commands by graphics. GUI was first developed by Xerox corporation for Xerox
star computer. Then it was a common usage. The Microsoft developed a GUI called MS-windows. A typical GUI is
shown in fig. 11.
Fig. 11 GUI Environment. Window. : It is a devivce on which a different applications are shown on screed by icons. The screen is divided it in
different portions, having different sizes, each portion has been assigned to some specific function and each portion
is called window, each of these portions are independent to each portion has a graphical symbol which gives the
general meaning, other of the co-operation.
In the past used interface consisted of some cryptic commands. It was very difficult to remember all the
commands. Each command has several options. Current trend is to display various commands on the screen and
allow the user to select a command using a cursor and simply checking on it. It was not possible to display all the
commands at a time therefore commands are grouped together in various levels by selecting the group user displays
the commands.
Max /
Restore
Left
Scroll
Title
bar Min Close
Up
Scroll
Scroll
down
Right
Scroll
Right
Scroll
bar
V.
Slider
Menu
bar
20
Components of GUI
Menu bar and pull down menu.
Scroll bar
Contents
Controls
Dialogue box.
Feedback pointers.
a) Menu bar : It gradually appears on the top of window and under this window some of the menu bar options are
file, edit, view, text, pick, options and help. When one menu is selected then it consists of number of sub-menus
called pull down menus. This pull down menu has rectangular box in which specific task is defined, which is
executed by clicking or by keyboard operation.
b) Scroll bar : It is used for looking the information, which is currently invisible. The scroll bars consists of
horizontal and vertical scroll areas with slider box and arrow in box at each end. The slider box gives the hint.
c) Title bar : The horizontal top on is the name of the program.
d) Control : Variety of controls are used in GUI to select the byte of information.
e) Minimize button : This is used to minimize the size of the program.
f) Maximize / restore button : Windows can be viewed as full screen by clicking the square button. This button is
also used for restore, which is indicated by double small squares, by clicking on double squares the window gets
in previous mode.
g) Close button : By clicking on close button windows application can be closed.
h) Dragging the window: The position of the window can be changed by dragging it. To drag the window, select
window by mouse and keep the button on mouse pressed and drag to necessary position and leave it to new
position and release the mouse.
i) Resizing : Making change in size of window is called resizing window.
SECURITY AND THREATS OF OPERATING SYSTEM
Introduction : The term security is defined that secure systems will control, through use of specific security,
features, access of information. Only the authorized individuals or processes operating on their be-half will have to
read, write, create or delete. There are three security elements which are defined as follows.
1) Confidentiality : This insures that information is not accessed in the authorized manner.
2) Integrity : This ensures that information is not amended or deleted in by any
3) Availability : ensures that information is available to authorized user at the right time .
Generally security is considered with the ability of the operating system to enforce control over the storage and
transportation of data in and between the objects that the operating system supports.
Security Threats :
When PC was designed it was intended to security to individual use. This the reason single operating system
(DOS) is not very strong in the security areas. It was not having the protection of data files of one user from
possibility of penetration of misuse by another user as no two users were intended to use the same machine
simultaneously.
Now day a number of PC’s are being networked together for sharing of data and programs. There is need to
have better and strict control over the protection aspects
The major threats of security in any environment are as follows ;
21
1) Tapping ( Unauthorized use of service)
2) Disclosure ( Unauthorized disclosure of information )
3) Amendment ( Unauthorized alteration or deletion of information )
4) Fabrication : (Unauthorized fabrication of information )
5) Denial: ( Denial of services to authorized users)
Following figure shows the types of security threats-
Tapping / Disclosure Amendment
Fabrication Denial
The tapping and disclosure systems are called passive threats and amendment, fabrication and denial are active
threats. In tapping without the knowing of A and B third party access the information but in disclosure A willingly or
knowingly disclosures the information to the third party.
Attacks on security:
The security system can be attacked and penetrated in many ways.-
1) Authentication : It means the verification of access to the system sources. The way of threatening by
authentication is by –
i. Guessing or stealing the password and then it is used.
ii. Interender may use vender supplied password and then it is used.
iii. Find the password by trial and error method by giving names, surnames, initials or common identities.
iv. I f logs on and goes for tea or some where then interunder may use the terminal to access and may
modify the contents.
v. Interunder can write a dummy login program to fool the user.
2) Browsing : Some system can have a control to access files, which are very permissive. An interunder can
browse the system files to get the information, which the confidential record may be record or modified.
3) Invalid parameters : The serious security violations can takes place due to passing a invalid parameters or due
to the failure to update them properly.
4) Trap doors : For easy installations and modify the contents, softwares engineers wants some secret points even
after production. Engineers knows how to use these shortcuts called trap doors. The interunder may use these
trap doors to access the secret information.
5) Line tapping : A special terminal can be used in this case to tap into the communications lines. The security is
threatened by tapping, amending or fabrication, once the interunder gets hold of line. The interunder needs
different hardwares and techniques depending upon the attack is passive or active.
6) Electric data capture : A penetrator may use active or passive wire-taps or mechanism to pick up the screen
radiation’s or recognize that displayed on the screen.
A
B
A
B A
A
B
A
B A
22
7) Lost line : In networking environments, a line can get lost. In that case system log out a user and allows an
access only after re-establishing the identity of the user. The process related before loosing line may be
accessible.
8) Improper access control : In some systems, the system itself does not allow the planning of meticulous access
control mechanism. The system administrator may not plan the access controls properly. This may lead to some
users for too many privileges.
9) Waste recovery : The interunder may use different techniques to recover the detected or part of them by
containing different passwords.
10) Rogue software : Lot many software programs are available. Computer virus is most notorious to then all. This
the deliberately written program or a part of it to create mischief.
The various rogue softwares are given below –
1) Tragan house : This a program, which appears to be harmless, but has a piece of code, which is harmful.
2) Chameleon
3) Ordinary software bomb
4) Timed software bomb
5) Logical software bomb
6) Worm
7) Virus
8) Rabbit.
Computer Worms :
It is full program by itself which is written in such a way that it spreads to other computers over the network,
while doing this it consumes the network resources to very large extent. It may bring the entire network to a grinding
halt. The computer worm does not harm any other program or data. It spreads these by consuming large resources
such as transmission capacity, storage and deny the services the user.
Safeguards against worms :
1) Prevention of creation : This can be achieved by having strong security and protection policies and mechanisms.
2) Prevention of spreading. : This can be done by introducing various checkpoints in communication system.
Computer virus :
Computer virus is program of infecting other program written with clear intention. It is not a complete
program. Computer virus originated in Xerox PARC research centre. The research scientists at the centre wanted to
carry out large computations which can be independently carried out, they designed smaller programs which could
by themselves spread to other computers. It can corrupt code and data. Virus works in number of ways, normally the
developer of virus is bright person who knows the operating system very well. When the virus program is executed
with the host program the virus executes i.e. spreads to other programs on the machine and affects them.
classification Viruses according to types.
1) Boot sector virus – Affects when machine booted
2) Memory resident virus – It loads upon execution of an infected file.
3) File specific virus – It affects only the specific types of files.
4) Command processor virus – General purpose infector can infect exe file.
23
5) General purpose virus – Loads viral code in memory.
Infection methods of virus
1) Append : The viral code appends itself to unidirectionl program
2) Replace : The viral code replaces the original ecexutable program completely or partially
3) Insert : The viral code insert the the unwanted program
4) Delete : Viral code deletes some code from executable code
5) Redirect : normal control is changes
Virus Detection :
It normally detects or checks integrity of the binary files. The program maintains the checksum on each file
or for better accuracy on sub-sectors of each file in addition. Every time and better control before each execution the
detection program again checks the stored data. A mismatch indicates some tampering inside the memory.
Virus removal :
A generalized virus removal program is very difficult to imagine due to the multiplicity of viruses and
creativity with which they can be controlled. However, there are some viruses whose bit pattern in the code can be
predicted. If the removal program scans the disk files for the pattern, of known viruses and on detection it removes
them.
Virus prevention :
The best way to deal with virus is to prevent it as there is no good cure available after infects. One of the safe
method of prevention of virus is to buy official legal copies of software from stores and should not pick up the free
and illegal software.
Exercise :
1. --------- is not an operating system. (M-2004)
a) UNIX b)LINUX c) MS-DOS d) C++
2. Operating system is ------------. (M-2003)
a) Hardware b) Software c) Input device d) Output Device
3) What is meant by GUI ? What are the essential components of GUI? Explain any three . (M-2004)
4) Explain he file system related to Information Management with file operations only. (M-2004)
5) What are the components of LINUX operating system? Explain any three features of LINUX? (M-2004)
6) Explain the concept of virtual memory. Explain any three terms used in virtual memory. (M-2004)
7) What is difference between worm and virus? Explain how these can be prevented? (M-2003)
8) What are the different functions performed by memory management in O.S. ? Draw a memory map of single
user computer. Explain types of partitioning in brief. (M-2004)
9) Explain the use of VIDEO RAM. Explain data bytes and attribute bytes. (M-2003)
10) Why is a user program not allowed to carryout direct read/write operations from /to a disk sector? (M-2003)
11) With reference to process management explain the terms. (M-2003)
1) External priority 2) Purchase priority
3) Internal priority 4) Time slice.
12) Explain the three main functions performed by a memory management module of an operating system. State any
four memory management systems. (M-2003)
13) Explain the following programs in MS-WINDOWS. (M-2003)
i) Program Manager ii) File Manager ii) Control Panel
14) Explain the functions of Scroll bar and menu bar components of GUI. (Mod-2002)
15) What is VDU? Explain 1)Dumb terminal 2) Intelligent terminal. (Mod-2002)
24
16) Which are the tree major areas in which the operating system divides its services? Give its examples.
(Mod-2002)
17) Explain context switching at process level in multiprogramming system with suitable example. (Model –2002)
18) What is computer virus? State the various types of viruses and the basis on which they are classified.
(Model-2002)
25
CHAPTER – II
DATA STRUCTURE INTRODUCTION TO DATA STRUCTURE
Data are nothing but simply a set of values. The data item is a single unit of value. The data is divided into sub-
items called group items. The data sub-items which can’t be further divided are called elementary items. Eg. : Name
of place, student, etc. The data may be represented in numeric or non-numeric values.
An entity is some thing that has certain attribute or properties which may be assigned values. The values
themselves may be either numeric or non-numeric.
Example: Attribute Name Age Sex Phone No
Value A.S. Rao 29 Male (0234) 22279 The term
“information” is used for data with given attribute or in other words meaningful or processed data.
Field : Information regarding the attribute of entity is called data field. Field is a single unit of information.
Record : It is a collection of field values of given entity.
File : File is a collection of record of entities. A file can have fixed length records or variable length records. In
fixed length record data space remains same and in variable it goes on changing for different lengths.
Data may be organized in two different ways. The logical or mathematical model of particular organization is
called data structure.
Data structure and its operation
The logical or mathematical organization of data is called Data structure. The operations that performed
under Data structure are as follows:
Traversing : - The traversing means acessment of each record only one to process the data. That means entire
data is accessed only once for processing the data.
Example : Reading the roll numbers only once, reading any data only once.
Searching: - Finding location of record in the given main value of all record that satisfies the particular
condition.
Example: Finding the largest / smallest number from given data
Inserting : - Insertion means adding new record to the structure. Once the data is entered and new entry is made
in between.
Example: Inserting the names of new born babies in the population list.
Deleting : - It means removal of record from the structure.
Example : Removing the names of retired staff
Sorting : -Arranging the records in logical order.
Eg – Names of students according to alphabets.
Merging : - Merging combines two records into one record file.
Example : Combining the students names from the two list to make one list.
Algorithm :
Algorithm is a step by step well defined list of instructions for solution of some problem.
To write algorithm we need to specify different data operation. The algorithm consist of no. of steps which has
got specific meaning. The first step tells the purpose of algorithm written. The first step also includes list of variables
of input data. The second step gives the list of steps. The steps in the algorithm are executed one after other and
control is transferred to particular step by Go statement.
26
Eg: Go to step n-1, the control transfers to n-1 step. The algorithm is terminated by exit or stop statement .The
assignment of data to variable is done by result statement.
Example: An array DATA of numerical values is in memory. We want to find the location LOC and the value MAX
of the largest element of DATA.
The n step simple algorithm is shown below
Algorithm : A
Step 1 :----------
Step 2 :----------
Step n-1: --------
Step n :-----------
The above program has n steps and to transfer control go to step no. is used.
DATA CONTROL STRUCTURE
In control structure data flow in 3 different logics.
1] Sequential flow
2] Selection flow
3] Repetitive flow
1] Sequential flow : The data is executed in step by step as sequence of one after the other.
Eg Step 1
Step 2
Step 3
Step 4
---"---
Step n
Conditional data flow ( Selection flow) Selection logic employs number of conditions which lead to a selection of one out of several alternative
modules. One or other condition is selected according to the condition, there are three condition in which the
conditional data flows.
1) Single alternative structure
This will take the form
If condition, then
[ module x]
End of if structure
2) Double alternative structure
This has if - else form
If condition then :
[ Module x ]
ELSE :
[ Module Y ]
[ End of if structure ]
3) Multiple alternative
This has if -else if form
If condition (1) then ;
[ module x ]
ELSE if condition (2) ; then
[ module y ]
Conditi
on?
Module x
Yes
No
Condition
?
Module x
Yes
No
Module x
27
Else if condition (n); then ;
[ module An ]
[ module z ]
[ End of if structure ]
The logic of this structure allows only one of the module to be executed. Specifically either the module
which allows the first condition which holds is executed or the module which follows the final Else
statement is executed. Example : Solution of the quadratic equation
ax2 + bx + c = 0 Where a 0, and given by quadratic formula
-b b2 – 4ac
2a
The quantity D = b2 – 4ac is called discriminant of the equation. If D is negative, then there are no real
solutions. If D = 0, then there is only one (double) real solution.,
x = -b / 2a. If D is positive, the formula gives two distinct real solutions. The following algorithm find the real
solutions of the quadratic equation.
Algorithm :
Step 1. Read : A, B, C.
Step 2. Set D : = B2 – 4ac.
Step 3. If D > 0 , then:
a) Set X1 := ( -B + D ) / 2A and X2 := ( -B - D ) / 2A.
b) Write : X1, X2.
Else if D = 0, then:
a) Set X := -B / 2A.
b) Write : “ UNIQUE SOLUTION”,X.
Else:
Write : “ NO REAL SOLUTIONs”.
[End of if structure]
Step 4. Exit.
Repitative flow
Some modulus or steps are executed repeatedly until certain conditions are satisfied. It has the form
Repeat for J=K to L by T
[ module ]
End of if loop
Is K>S
Module
No
Yes
J K
J = J + T
The repeat for loop uses an
index variable, such as K to
control the loop, the loop will
usually have a form.
X =
28
Repeat while loop
Repeat while structure.
Here the program remains in loop while condition is false. LINEAR ARRAYS
Array is a list of finite homogenous finite number of data elements. Array defines or reserves consecutive
memory locations. The elements of an array are stored in successive memory locations. The no. of elements in an
array denotes the length or size of an array. The length or no. of elements in an array can be obtained by
Length = UB-LB+1
Here UB - upper bound LB - Lower bound
LB=0
If LB=1 then length = UB-LB
The elements of an array A are represented by
A0, A1, A2, A3,…….An
Or A[0], A[1], A[2], A[3],…….A[n]
Eg. Marks of 6 computer students
Marks
0 35 Here marks[0] = 35
1 89 marks[1] = 89
2 91 marks[2] = 91
3 92 marks[3] = 92
4 94 marks[4] = 94
5 81 marks[5] = 81
Here UB = 5 LB=0
Length = 5-0+1=6
Example
Algorithm using repeat while loop rather than a Go to statement.
( Largest element in an array) Given nonempty array DATA with N numerical values, this algorithm finds
the location LOC and the value MAX of the largest element of DATA.
1. [Initialize.] Set K := 1, LOC := 1 and MAX : = DATA[1].
2. Repeat steps 3 and 4 while K <N + 1:
3. If MAX < DATA[K], then:
Set LOC := K and MAX := DATA[K].
[End of if structure.]
4. Set K : = K + 1.
[End of if structure.]
5. Write : LOC, MAX.
6. EXIT.
REPRESENTATION OF LINEAR ARRAY IN MEMORY
The arrays are always stored in consecutive memory location. The location required depends up on the data
elements and computer gives the way of first element of the array
Condition
Module
No
Yes
29
If LA is the linear array in the memory of the computer.
LOC(LA[K]) = address of the element LA{K] of the array LA.
As the elements of an linear array are stored in successive memory cells. Accordingly the computer does not need to
keep track of the address of every element of LA, but needs to keep track only of the address of the first element of
LA, denoted by
Base(LA)
And called the base address of LA. Using this address Base (LA), the computer calculates the address of any
element of LA by the following formula.
LOC ( LA [ K ] ) = Base (LA) + W (K-LB)
Where LA = linear array
W = no. of words per memory cell
LB = Lower bound
The array representation can be shown as
2000
2001
2002
.
.
.
memory
address Fig.1 Representation of memory array.
Deleting
Deleting means removing one or more elements from the given elements. Deleting of an atom at the end is
easy than the middle because when element in the middle is deleted free space is created and every element of an
array down to free space need to shift upward to fill the gap.
Deletion process
Original Array Deletion of Shruti name from array Fig. 2 Deleting process
ALGORITHM :
DELETE (LA,N, K, ITEM)
Here LA is linear array having N elements and ITEM element located at position Kth is to be deleted for that K N
1. SET ITEM: = LA [K]
2. REPEAT FOR J:=K TO N-1:
Move J+1st element upward.
Set LA [J] := LA [J+1].
End of loop
3. Reset N, N:=N-1
4. Exit
Sequential storage
of elements of an
array
Suresh
Jay
Shruti
Ram
Sham
Suresh
Jay
Ram
Sham
30
SORTING
Sorting means rearranging element of an array in specific order for increasing order i.e.
A[0]<A[1]<A[2]<………..<A[n],
Here A is array name
Suppose array X contains list of nos. in ascending order
4, 9, 2, 100, 50, 48, 3
After sorting X has a list of
2,3,4,9,48,50,100
In sorting comparison of first and second element is considered and the nos. are rearranged in desired order
then second third are taken for comparison and then according to desired form they are rearranged and next no. are
taken for comparison. This comparison continues till n-1 times where n- is no. of elements
Algorithm of bubble sorting.
BUBBLE (DATA, N)
Here DATA is an array of n elements
1. Repeat step 2 and 3 for k= 1 to N-1.
2. Set PTR:=1 Here PTR = Pointer [ initializes pass pointer ]
3. Repeat while PTR N-K;
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
Example of BUBBLE SORT
Suppose the following numbers are stored in an array A:
31, 50, 26, 84, 65, 22, 12, 56
We can now apply the bubble sort to an array by pass method.
Pass 1. We have the following comparisons:
a) Compare A1 and A2. Since 31 < 50, the list is not altered.
b) Compare A2 and A3. Since 50 > 26, interchange 50 and 26 as follows.
31, 26, 50, 84, 65, 22, 12, 56
c) Compare A3 and A4. Since 50 < 84 the list is not altered
d) Compare A4 and A5. Since 84 > 65 interchange 84 and 50 as follows.
31, 26, 50, 65, 84, 22, 12, 56
e) Compare A5 and A6. Since 84 > 22 interchange 84 and 22 as follows.
31, 26, 50, 65, 22, 84, 12, 56
f) Compare A6 and A7. Since 84 > 56 interchange 84 and 56 as follows.
31, 26, 50, 65, 22, 12, 56, 84.
At the end of the first pass, the largest number, 85, has moved to the last position. However, the rest of the
numbers are not sorted, even though some of them have changed their positions.
Pass 2. 26, 31, 50, 65, 22, 12, 56, 84.
26, 31, 50, 22, 65, 12, 56, 84.
26, 31, 50, 22, 12, 65, 56, 84.
26, 31, 50, 22, 22, 56, 65, 84.
At the end of 2nd pass, the second largest number, 66 has removed in way down to the next to the last
position.
Pass 3. 26, 31, 22 50, 12, 56, 65, 84.
26, 31, 22 12, 50, 56, 65, 84.
31
Pass 4. 26, 22, 31 12, 50, 56, 65, 84.
26, 22, 12 31, 50, 56, 65, 84.
Pass 5. 22, 26, 13 31, 50, 56, 65, 84.
22, 13, 26 31, 50, 56, 65, 84.
Pass 6. 13, 22 , 26 31, 50, 56, 65, 84.
Pass 6 actually has two comparisons, A1 with A2 and A2 with A3.
TRAVERSING A LINEAR ARRAY
Traversing array means accessment of an array for only once. The algorithm for traversing linear array is
given below
Algorithm – Traversing of linear array
LA is linear array with lower bound LB and upper bound UB.
1. Set K := LB, [ initialize counter = LB ].
2. Repeat steps 3 and 4 while K UB
3. Visit element of an array.
Apply process to LA [K]
4. Set K := K + 1. Increase the counter.
[ End of step 2 loop]
5. EXIT
Example :
An automobile company uses an array AUTO to record the number of automobiles sold each year from 1932
through 1984. Rather than beginning the index set with 1, it is more useful to begin the index set with 1932 so that
AUTO[K]= number of automobile sold in the year K
Then LB= 1932 is the lower bound and UB = 1984 in the AUTO.
UB - LB + 1 = 1984 - 1932 + 1 = 55
The AUTO contains 55 elements and its index set consists of all integers from 1932 through 1984.
a) Print each year and the number of automobiles sold in that year.
1. Repeat for K = 1932 to 1984:
Write: K AUTO[K].
[End of loop.]
2. Return.
INSERTING
Inserting deals with operation of adding extra element in between existing elements in an array. The
inserting can be done at the end of an array or in between. The insertion at the end of an array is easy because no
other existing elements are needed to shift down. Then insertion can be done depending upon the availability of the
free memory. When elements needs to insert in middle then we have to create space by shifting down the other
elements.
Insertion operation
Original Array Insertion of Ajay in an array
Fig. 3
Suresh
Jay
Shruti
Ram
Suresh
Ajay
Jay
Shruti
Ram
32
Algorithm : Inserting into a linear array.
INSERT (LA, N, K, COMPUTER)
Here LA = Linear Array.
N = No. of elements in an array.
K = Positive integer.
This program inserts the element COMPUTER into the Kth position in the linear array LA.
1. Set counter J := N,
2. Repeat steps 3 and 4 while J K
3. Set LA [J + 1] := LA [J].
Move the jth element downward.
4. Set J := J – 1, decrement the counter.
[ end of step 2 loop ]
5. Set LA [K] := COMPUTER.
Insertion of COMPUTER at Kth position.
6. Reset N, N := N + 1.
7. Exit.
Example :
Suppose Exam has been declared to be 6 element array but data have been recorded only for TEST[1],
TEST[2], TEST [3] and TEST[4]. If Z will be the value of next test, then one simply assigns
TEST[5]: = Z
SEARCHING
Searching refers to operation of finding the location LOC of the ITEM in DATA, or printing some message that
ITEM does not appear there. The search is said to be successful if ITEM does not appear in DATA and unsuccessful
otherwise.
There are two methods of searching.
1) Linear search : searching means finding the location of given element in the list. the search is said to be
successful when item is found else unsuccessful. In linear search the given element is compared with each element
in the list in a sequential manner.
Algorithm-For linear search.
LINEAR ( DATA , N , ITEM, LOC )
Here Data is of element of an array of an array with N element and if ITEM is found LOC=1for the ITEM for
successful search or set LOC=0 for unsuccessful.
1) Insert- ITEM at the end of DATA.
Set DATA [N+1]:= ITEM
2)Set LOC=1 , initialization of counter.
3) Search for ITEM
Repeat while DATA [LOC] ITEM
Set LOC := LOC +1
4) If LOC :=N+1 then set LOC :=0.
5) EXIT.
33
Example :
Consider the array NAME as shown in the figure below.
a) Suppose we want to know whether Suresh appears in the array and if so, where. Our algorithm temoprarily
places SURESH at the end of the array, as shown in fig A, by NAME [4] = SURESH. Then the algorithm
searches the array from top to the bottom. Since Suresh first appears in NAME [N + 1], Suresh is not the original
array.
NAME NAME
Original Array Insertion of Ajay in an array
Fig. 4
BINARY SEARCH
If list is of increasing or decreasing order then for searching Binary search method is more efficient.
In Binary search algorithm. The given element is compared with middle item and comparison decides whether
given item lies at middle or upper half or lower half, else no item is found.
suppose data is arranged in increasing order.
DATA [BEG]. DATA [BEG+1] - - - - DATA[END]
Here BEG denotes beginning of data and END denotes end of the data segment.
This algorithm always compares the given item with middle element.
middle element is given by
DATA [MID] = INT [(BEG+END)/2]
If DATA MID = ITEM then search is successful and LOC =MID. Other wise the ITEM is compared with upper
and lower half.
1) If ITEM < DATA [MID], them ITEM appears in upper half that is DATA[BEG] ------DATA[MID] so END
=MID-1
2) If ITEM > DATA [MID], then ITEM appears in lower half .
DATA[MID+1] - - - -- DATA [END]
BEG=MID+1
And if ITEM is not in DATA we have END<BEG, the search is on successful.
Algorithm;- Binary search.
Binary (DATA, LB, UB, ITEM, LOC)
Here DATA is started in an array having Lower Bound LB and Upper Bound UB, ITEM is given
element to search in an array and if ITEM is found LOC=1 and if not found LOC=NULL.
1. Set BET := LB END := UB
and MID := INT[(BEG+END)/2].
2. Repeat steps 3&4 while BEG END.
and data [MID] ITEM.
3. If ITEM < DATA [MID,] then:
set END := MID-1.
ELSE:
Madhavi
Jay
Shruti
Ram
MAdhavi
Jay
Shruti
Ram
Suresh
34
Set BEG := MID+1.
[ End of if structure ]
4. Set MID := INT[(BEG+END)/2].
[ End of step 2 loop ]
5. If DATA [MID] := ITEM then.
set LOC := MID.
ELSE:
Set LOC := NULL
[ End of if structure ]
6. EXIT.
The number of comparisons here are approximately equal to log2n.
Example : Let DATA be the following sorted 13 - element array:
DATA : 11, 22, 30, 33, 40, 44, 55, 60, 66, 77, 80, 88, 99
We can apply the binary search to DATA for different values of ITEM.
a) Suppose ITEM = 40. The search for ITEM in the array DATA is shown below, where the values of
DATA[BEG] and DATA[END] in each stage of the algorithm are indicated by circles and the values of
DATA[MID] by the square. Specifically, BEG, END and MID will have the following successive values:
i) Initially BEG = 1 and END = 13. Hence,
MID = INT[(1 + 13)/2] = 7 and so DATA mid = 55
ii) Since 40<55, END has changed its value by END = MID - 1=6. Hence
MID = INT[(1 + 6)/2] = 3 and so DATA mid = 30
iii) Since 40>30, BEG has its values changed its value by BEG = MID + 1=6. H
MID = INT[(4 + 6)/2] = 5 and so DATA mid = 40
We have found ITEM in location LOC = MID= 5.
11, 22, 30, 33, 40, 44, 60, 66, 77, 80, 88, 99
11, 22, 33, 40, 44, 55 60 66, 77, 80, 88, 99
11, 22, 30, 33, 40, 44, 55, 60, 66, 77, 80, 88, 99
Binary Search for ITEM = 40
POINTER ARRAY:
A variable is called pointer if it points to element in the lost. Pointer contains the address of the element in the
list. The array of class and students are discussed. Suppose we have 4 class and each class has list of students.
Class IX contains the list of students from 1 to 3
Class X contains the list of students from 4 to14
Class XI contains the list of students from 15 to 24
Class XII contains the list of students from 24 to end
Class pointer indicates the starting list number of student of that particular class.
Records: Record is collection of non-homogeneous data of fields. The record may contain non-homogeneous
data i.e having different data types. The record can be described by different levels.
55
,
30
40
35
For example : A school keeps record of students. It contains data items : Name, class, birthday, father name, age,
mother name, age, subjects. The structure is given below.
1. Student
2. Name
2. Sex
2. Class
2. Birthday
3. Day
3. Month
3. Year
2. Father
3. Name
3. Age
2. Mother
3. Name
3. Age
2. Subjects
3. Marathi
3. English
3. Maths
3. Science
The number indicated on the left side is variable level.
4.18
Example
A class of students record may be organized as follows :
1 Student ( 25)
2 Name
3 Last
3 First
3) MI
2. Test (2)
2. Final
2. Grade
REPRESENTATION OF RECORDS IN THE MEMORY
The record in the memory is stored in linear array. The student in school requires linear array of name, sex,
day, month, year, father name, age, mother name, age, subjects, etc. One array is required for each element. All the
arrays should be parallel subscripted K elements.
Name [K], Sex [K] …………….. Subject [K].
This array in memory can be shown as follows –
LINKED LIST Linked list is a linear collection of data elements called nodes. Each node is divided into two parts. The first
part contains information of element and second is link field which contain the address of next node as shown
Name Sex Day M. Age Subject
Fig. 4 Parallel array
36
Information Pointer
Part of next node Fig. 5 Linked list
The left part denotes the information of file and right contains the address of the next node and last node have no
address in the right part. If list do not contain any node then it is called null list and start variable contain null
variable.
REPRESENTATION OF LINKED LIST IN THE MEMORY
One array of list contains the information and the other is linker array. Information is linked by the linker the
other information part. The name of linked list, start, contains beginning and ended with the null information.
1 2 3 4 5 6 7 8 9 10 11
INFO
LINK
Fig. 6 Linked list representation in the memory
Example Figure below is linked list in memory where each node of the list contains a single character. We can obtain
the actual list of characters or in other words the string as follows.
START = 9, so INFO[9] = N is the first character.
LINK[9] = 3, so INFO[3] = O is the second character.
LINK[3] = 6, so INFO[6] = (blank) is the third character.
LINK[6] = 11, so INFO[11] = E is the fourth character.
LINK[11] = 7, so INFO[7] = X is the fifth character.
LINK[7] = 10, so INFO[10] = I is the sixth character.
LINK[10] = 4, so INFO[4] = O is the seventh character.
LINK[4] = 0, so the NULL value, so the list has end.
Trees :
Tree is a non-linear data structure used to represent data containing a hierarchical relationship between
elements. A binary tree is a special kind of tree which is easy to maintain on the computer. Tree consists of number
of nodes.
Binary tree : A binary tree T can be defined with finite set of elements called nodes such that it can be null set or
contain nodes R.
If T contains root R, then T1 and T2 are the left and right sub-trees of R. If T1 and T2 are non-empty then T1 is
left successor of R and T2 is right successor of R.
A
B C
D E H I
F G J K
L
Fig. 7 Binary Tree
A B C
7 10 1
Start
X
37
The tree T contain 12 nodes (A to L ). Root of T is A at the top of the figure. B is the left successor and C is
the right successor of node A. The left subtree contains nodes B, D, E, F and G while right sub-tree contains nodes C,
H, I, J, K and L each node has 0, 1 or 2 successors. The nodes with no successor is called terminal node and if the
two trees are said to be similar if they have the same structure.
The algebraic expression (a+b) * ((c / d) – e) is given by the tree structure,
*
+
a b / e
c d A tree T is said to complete if all its levels, except the last has the maximum number of possible nodes. A
binary tree is said to be a 2-tree or an extended binary tree and each node N has 0 or null elements.
Representation of Binary Tree in the Memory
The Tree T can be represented in memory by a sequential or link representation. The important requirement
is that one should have direct access to its roots R. The linked list uses parallel arrays. Information left and right and
a pointer variable root of each node N of T will correspond to a location K such that
* INFO [K] contains data of node N.
* LEFT [K] contains the location of left node N.
* Right [K] contains the location of right node N.
Root
Root
In sequential method, linear array is used. The sequential steps are executed in such a manner that
A
B C
D E Fig. 9 Sequential representation of binary tree
Exercise
1) What is data structure ?
A
X X
B X X
C
1 INFO LEFT RIGHT
2
3 A 3 5
4 B 0 0
5 C 0 0
15
A
B
C
0
0
D
E
38
2) What is group item and non group item? Explain with example.
3) What is entity? Give example of entity.
4) What is information?
5) What is file?
6) What is record? Give suitable example.
7) What are the different operations performed on the data structure?
8) What is algorithm ? State suitable example of algorithm.
9) Describe double alternative structure.
10) Describe repetitive flow structure.
11) What is array and how array is represented in memory ?
12) What is traversing ? Explain the algorithm with suitable example.
13) What is Deleting ? Explain the algorithm with suitable example.
14) What is searching ? Explain the algorithm with suitable example.
15) What is inserting ? Explain the algorithm with suitable example.
16) What is sorting ? Explain bubble sort algorithm
17) What is merging ?
18) How record is represented in a file?
19) What are linked lists? Explain the 6 linked list in a memory.
20) What is tree ? Explain binary tree.
21) How binary tree is represented in memory?
22) Represent the binary tree for the following.
[ ( a + b) * ( b + c) ] / [ ( D / c ) / b ]
13) Represent the binary tree for the following.
{[ ( d * b) / [q * ( b + c) ]} / [ ( D / c ) / b ]
14) Record contains ------ data.
a) linear b) homogeneous c) non-homogeneous d) non-linear
15) Finding the element from given data is called ---- .
a) Searching b) sorting c) merging d) deleting.
16) Tree is a --- data structure.
a) linear b) homogeneous c) non-homogeneous d) non-linear
17) Accessing each element only once is called --------.
a) Searching b) traversing c) merging d) deleting.
18) The element of an array are -------.
a) contineous b) non-linear c) linear d) scattered.
19) Pointer variable contains -----
a) Float number b) address c) string c) none
Example 2.6
Algorithm using repeat while loop rather than a Go to statement.
( Largest element in an array) Given nonempty array DATA with N numerical values, this algorithm finds
the location LOC and the value MAX of the largest element of DATA.
7. [Initialize.] Set K := 1, LOC := 1 and MAX : = DATA[1].
8. Repeat steps 3 and 4 while K <N + 1:
9. If MAX < DATA[K], then:
Set LOC := K and MAX := DATA[K].
[End of if structure.]
10. Set K : = K + 1.
[End of if structure.]
11. Write : LOC, MAX.
12. EXIT.
39
CHAPTER – III
C++
C++ review
C++ is an object oriented programming language. C++ was developed by Bjarne Stroustroup at Bell
laboratory in USA. It is a superset of C
TOKEN:
We know that smallest individual units in the program are called as tokens. Using these tokens
spaces and syntax of the c++ language is written except some modification and addition. c++ tokens are similar to C
language. The following are the tokens used in C++.
* Keywords
* Identifiers
* Constants
* Strings
* Operators
KEYWORDS:-
The keywords give specific c++ language features. They are explicitly reserved identifiers and cannot be used
as names for the program elements.
There are 48 c++ keywords, which have specific meanings with them the following table gives the list of
keywords.
asm double new switch
auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typedef
class friend return union
const goto short unsigned
continue if signed virtual
default inline size of void
delete int static volatile
do long struct while
IDENTIFIERS:- Identifiers refer to name of variable, functions, array, classes, etc created by the programmer. Identifiers are
fundamental requirements of any language. Each language has its own rules and identifiers. Some of the rules are
listed below.
*Only alphabetical characters , digits and underscores are permitted.
*Name cannot start with number.
*Uppercase and lowercase are distinguished.
*Declared keywords cannot be used as a variable name.
BASIC DATA TYPES
The basic or fundamental types are of three types ; Built-in , user defined and derived types. The Built-in
data type consist of int, char float, double & void. User defined types are structure, union, class & enumeration. The
derived types are Array, function & pointer. The basic data types are listed in the table shown below.
C++ Data types
Int class function
char union pointer
Built-in type User defined Derived types
40
void structure array
float enumeration reference
double
The table of size and range of basic C++ data type .
TYPE BYTE RANGE
Char 1 -128 to 127
Unsigned char 1 0 to 255
Signed char 1 -128 to 127
int 2 -32768 to 32767
Unsigned int 2 0 to 65535
Signed int 2 -31768 to 32767
short int 2 -31768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -31768 to 32767
long int 4 -2147483648 to 2147483648
signed long int 4 -2147483648 to 2147483648
unsigned long int 4 0 to 4294967295
float 4 3.4E -38 to 3.4E38
double 8 1.7E -308 to 1.7E +308
long double 10 3.4E -4932 to 1.1E+4932
Constants :-
The constants has fixed value. It does not change its value. The value declared as constant cannot be
modified by program. There are two ways of creating constants in c++.
1) By using qualifier constants
2) defining set of integer constants
Example of constants-
Const. Int size=2186;
This declares size integer constants having value 2186. The another way to represent the constant is enum
{A,B,C};
The above statement defines A,B and C as integer constants with value 0,1and 2 respectively.
Constants may be written as
Enum{A=10,B=50,c=500};
Like C ,C++ supports several kinds of literal constants , which include integers, characters, floating point-
numbers and strings . These literal constants do not have a memory location.
E.g.:
2186 // Decimal integer
21.86 // Floating point integer
16 // octal integer
0x3 // Hexadecimal integer
“ ABC” // string constant
‘A’ // Character constant
S ‘ Kumar’ // wide character constant
Variables & its declaration :-
41
A variable is symbol that represents a storage location in memory & the information stored in memory is
called the value of variable. One common way for a variable to obtained a value is by an assignments. The syntax
can be given by,
Variable = expression.
Here the expression is evaluated first & then resulting value is assigned to the variable. Every variable in c++ must
be declared before it is used. It can be declared anywhere in program before it is being used . By declaring variable
program becomes easier & easily understood.
E.g.- float A;
float i;
Sum = sum + A;
avg = sum/i;
All the variables cannot be seen at glance.
Dynamic initialization of variable :-
This permits the initialization of variable at runtime. This is called dynamic initialization. It can be
initialized simultaneously at a place where the variable is used for the first time.
Example : float volume = side a* side b* side c;
float avg = sum/i;
This dynamic initialization is extensively used in object oriented programming. C++ allows the declaration
of variable anywhere in scope. This means that variables can be declared right at place of its use, which makes
program easier and reduces errors.
Example : int main ()
{
float y ;
float sum = 0; // declaration
for ( int i = 1; i < 10; i++ ) // declaration
{
cin >> y;
sum = sum + y;
}
float average ;
average = sum / i;
cout << average ;
User Defined Data Types
User defined data type consists of structure, union, class and enumeration, some more features have been
added to make them suitable for object oriented programming. C++ also permits to define another user defined data
type known as class, which can be used like other basic data types to declare variables.
Enumerated data type is another user-defined type, which provides a way for attaching names to numbers,
thereby increasing comprehensibility of code. The enum (keyword) automatically enumerates a list of words by
assigning the values 0, 1, 2 and so on. This facility provides alternative means of creating symbolic constants. The
syntax of an enum statement is similar to that of the struct statement.
Example : enum shape
{
circle
rectangle
triangle
};
int main ()
{
cout <<” Enter shape code :”;
42
int code ;
cin >> code ;
while (code >= circle && code <= triangle)
{
switch ( code )
}
Case circle:
----------
---------
--------
break;
---------
--------
break;
case triangle:
-----
------
break;
}
cout<<"Enter shape circle:";
cin>>code;
}
cout<<"thank you\n";
return 0;
}
In C++ enum is defined within a class or structure is local to that class only.
Derived data types:-
Derived data type consists of Arrays, Functions, Pointers & References.
Array: In C++ array can be written as
char string [4]="bc";
The size should be one larger than the number of character in string.
Function : Functions always plays important role in program
Development. There are different types of functions like main, Return, Reference, Inline, Default, overload,
argument, etc.
Pointers:
Pointers are exclusively used in C++ for memory management & achieving polymorphism. Some of the examples
of pointers & pointer to constant are,
Char *const ptr1 ="pass"; //constant pointer.
We can't modify address that ptr 1 is initialized to
int const *ptr2 = & m; // pointer to constant.
Here ptr2 is declared as pointer to a constant. It can point to any variable of correct type, but the contents of what
it points to can't be changed.
We can declare both the pointers & variable as constant in the following way;
Const char *const SP="ABC";
The above statement declare SP as a constant pointer to the string which has declared a constant. But in this case
neither the address assigned to the pointer SP nor the constants, it points to can be changed.
SYMBOLIC CONSTANTS
C++ can create symbolic constants in two ways:
By using qualifier constant,
By defining a set of integer constants using enum.
43
In C++ any value declared as const can not be modified by the program in any way.
Example : const int size = 20;
Char place [ size ];
The named constants are just like variables except that their values cannot be changed. C++ always requires
a const to be initialized. To give a const value an external linkage so that it can be referenced from another file and
we define it by extern.
extern const total = 100;
The constant integer may also be defined by enumeration.
enum { A, B, C }
which defines as A, B , C as integer constants with values 0, 1, and 2 respectively.
const A = 0;
const B = 1;
const C = 2;
We can also assign constant values as
Enum { A = 2, B = 25, C = 100};
The type compatibility
In case of compatibility C++ is very strict. C++ defines int, short int and long int as three different types.
They must cast when their values are assigned to one another. similarly, unsigned char, char and signed char are
considered as different types, although each has a size of one byte. In C++ the type of values must be same for
complete compatibility, these are necessary in order to support function overloading.
size of (‘A’)
equals
size of ( char )
Reference Variable
Reference variable provides alternative name for previously defined variable. A reference variable is
created as follows-
Data-type & reference- name = variable- name
Example :- float total = 200;
float sum = total ;
Here the total is float type variable, which is already declared. Sum is alternative name declared to represent the total.
Both the variables refers to the same data object in the memory.
cout << total ;
and
cout << sum ;
Both prints the value 200,
Now total = total + 50 ;
will change both total and sum to 250.
A reference variable must be initialized at the time of declaration. This helps to establish the correspondence between
reference and data object, which it names.
C++ has additional meaning to symbol &, here & is not an address operator. The notation float & means
reference to float.
int x [10];
int& x = n [10];
char & a = ‘\n’;
44
The variable x is an alternative to array element n [10].
OPERATORS IN C++
Operator Meaning
<< Insertion operator
>> Extraction Operator
:: Scope resolution operator
::* Pointer-to-member decelerator
>* Pointer-to-member operator
.* Pointer-to-member operator
>** Pointer-to-member operator
*, /, % Multiplication, division, modules operators
+, - Addition, subtraction operator
<, <=, >, >= Less than, less than or equal to, greater than,
greater than or equal to
==, != Equality, inequality
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
&& Logical AND
|| Logical OR
?: Conditional
=, *=, /=, %=, +=, -=, Assignment operators
<<=, >>=, &=, ^=, |= Assignment operators.
, Comma operator
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator
Extraction Operator (>>)
The extraction (>>) operator is used to get the data from. This extracts data from input devices and assign it
to variables.
Example : cin >> result 1 ;
Insertion Operator (<<)
It gives value to the operator. It inserts the contents of variable to the object.
Example cout << word;
Scope resolution Operator (::) Scope resolution operator is used to declaration of variable in inner block and to hide the same variable in outer
block. It contains block within block.
:: variable-name Block 1 block 2
45
Memory Management operators
To allocate the memory two unary operators are used such as new and delete. The memory operation can
have the form as –
Pointer – variable = new data type.
The new operator allocates sufficient data type and returns the address of the object. The pointer - variable holds the
address of memory space allocated
E.g.. :- A : new int;
Here A is pointer of type int.
We can initialize the memory using new operator.
Pointer - variable = new data , type (value);
E.g.., int * A = new int (25);
When data object is not necessary then it must be destroyed to release memory space by delete operator.
delete pointer - variable
e.g. - delete A; delete S;
Manipulators
Manipulators are operators that are used to format the data display. The most commonly used manipulators
are end l and set w.
The end l manipulator, is used in an output statement causes a linefeed to be inserted. It has same effect and
using the newline character "\n"
E.g.., -----------------
----------------
Count << "A" << A << endl
Count << "B " << B << endl
Count << "C " C<< endl;
-------------------
-------------------
This would cause 3 line output, one for each variable, If how we assume the variables an 2186, 15and 3715
respectively, the O/P will occur
A =
B =
C =
The set w specify the a common field width and forces them to print right justified
A = 2 1 8 6 B = 1 5
C = 1 7 5
Count << set w(6) << sum <<endl;
The set w(6) manipulator specifies a field width 6 for printing value of variable sum
Example:
Program of endl and setw
2 1 8 6
1 7 5
1 5
2 1 8 6
46
# include <iostream.h>
# include <iomanip> " for setw
Using namespace std ;
Int amin ( )
{
int Basic = 1000, Allowance = 105, Total = 1105;
Count << set w (10) <<"Basic" <<setw (10) <<Basic<<endl
<< set w (10) <<"Allowance" <<setw(10) <<Allowance<<endl
<< set w (10) <<"total" <<total (10) <<Total<<endl
return 0 ;
}
Expression and their types
Expression is combination of operators, constants and variables arranged as per the rules of language
1) Constant Expression
This expressions have constant values
E.g.., - 10, 30+15-21/2 X
2) Integral Expression
Integral expression are those which produce integer results after implanting all the automatic and
explicit type conversions.
E.g.. - A
A*B+2 here A and B are integer
A+ int(5) variables
3) Float expression
These have floating point result
x + y
A * B
206 + float(10) here x and y
107.52
4) Pointer expressions
The variables produce address values
& A
Ptr
Ptr-1
"(AB)"
5) Relational Expressions
It depend on whether the expression yields true or false result.
A <= Y
BC = = OE
A+B < 100
6) Logical Expressions
Two or more expressions are logically combined together
E.g.. a>b && x = = 5
X = = 5 // y = = 10
7) Bitwise expressions
These expressions are used to manipulate data at bit level. Basically shifting of data is done.
A >> 5 Shift one bit to right
B<< 5 Shift one bit to left
Control structures
A large number of functions are used in C ++, that passes messages and process the data contained in the
objects. A function set up to perform a particular task, but when the task is complex, at that time many different
algorithms can be designed to achieve the goal. The designed programs are simple as well as complex. Number of
problems occur in the format so the format should be such that it should be easy to trace the flow of execution of
statements. To achieve the accurate and mainentanable code is to use one of the following three control structures.
47
1) Sequence structure ( straight forward)
2) Selection structure ( branching )
3) Loop structure ( repetition )
The following example shows the basic control structures-
Entry
Exit Selection structure
Sequential structure Exit
Loop Structure
Exit
The structure has one entry point and one exit point.
Action 1
Action 2
Action 3
Condition
Action 1 Action 2
Action 3
Condition
Action 1
Action 2
Control Structure
selection sequence loop
if-else do-
while
while for if
switch
48
If statement
if statement can be represented by two ways
1) simple if statement.
2) if --else statement,
The simple if has the form
if (expression is true)
{
action 1 :
}
action 2 :
action 3:
Fig. 3 Simple if statement
Second form ( if -- else )
if ( expression is true )
{ action 1 ; }
Else
{ action 2;
}
action 3;
Switch statement
The switch statement has multiple branches based on the various conditions, the control is transferred to one
of the many possible conditions. The switch statement takes the following form.
switch ( expression )
{
case 1:
{
condition 1;
}
case 2:
{
condition 2;
}
case 3:
{
condition 3;
}
case x:
{
condition x;
} }
The do-while statement
do- while is an exit controlled loop based on the condition the control is transferred to particular location in the
program.
do
{
action 1;
}
while (condition );
action 2;
The while statement
Condition
Action 2
Action 1
Action 2
49
This is loop structure but entry controlled one.
While (condition is true )
{
action x;
}
action y;
The for statement It is entry controlled loop statement in C++. It is used when an action is to be repeated for
predetermined number of times.
for ( initial value : test : increment )
{
action 1;
}
action 2;
Arrays in C++
Array is a collection or group of identical data objects, which are stored in consecutive memory locations
under common variable name. Array must be declared before it is being used in the program. The declaration of an
array is as follows -
Storage-class data-type array name [ expression ];
The storage class may be either external, static or automatic. The data type is elements of an array. The array name
may be any void variable name. The expression is used to declare size of memory locations required.
Example : int marks [50];
Automatic char page [9];
int values [5] = { 1, 2, 3, 4, 5 };
Two array programs
An array is composite object, which is composed of several elements with independent variables. In contrast
an ordinary variable of primitive type is called scalar object.
Example :- Using direct access on array
int main ( )
{
double a [3];
a[2] = 22.22;
a[0] = 11.11;
a[2] = 33.48
cout <<"a[0] = " <a [0] << endl;
cout <<"a[1] = " <a [1] << endl;
cout <<"a[2] = " <a [2] << endl;
}
/* A program by using 2 dimensional array. */
#include<conio.h>
#include<iostream.h>
main()
{
int a[3][3];
int x;
int y;
clrscr();
for (x=0; x<= 2; x++)
{
50
for(y=0;y<=2; y ++)
}
cin>>a[x][y];
}
MULTIDIMENSIONAL ARRAYS The arrays which we have used were one-dimensional i.e. sequential. But an array of arrays is called a
multidimensional array. The number of dimensional will indicate the brackets used. A two dimensional array will
require two pair of square brackets. The general format of multidimensional array is
The simplest way to declare a multidimensional array is like
Double a [30] [10] [5];
This the three dimensional array with 30, 10, and 5
E.g.. = static double records [100] [50];
Char line [50] [30];
Storage-class data-type array- name [exp1] [exp2] ------ [ exp n] ;
51
Program :
Main ()
{
int a [4] [5];
read (a);
print (a);
}
void read (int a[20] [5]
{
cout <<" enter 20 integers, 5 per row : \n";
for ( int i=0; i<4; i++)
{
cout <<" Row" << i <<":";
for (int j = 0; j<5; j ++)
cin >. A [i] [j];
}
}
void print (const int a [ ] [5] )
{
for ( int i = 0; i < 4; i++)
{
for (int j = 0; j<5; j ++)
cout << " " << a[i] [ j];
cout << endl;
}
}
/* A program by using 3 dimentional array.*/
#include<iostream.h>
#include<conio.h>
main()
{
int a[2][2][2];
int x,y,z;
clrscr();
for(x=0;x<=1;x++)
{
for(y=0;y<=1;y++)
{
for(z=0;z<=1;z++)
{
cin>>a[x][y][z];
}}}
for(x=0;x<=1;x++)
{
for(y=0;y<=1;y++)
{ for (z=0;z<=1;z++)
{
cout<<a[x][y][z];
} } }
getch(); }
Linear search Algorithm
Computers are probably used more for the storage and retrieval of information than for any other purpose.
Data is always stored in sequential structure such as an array. The simplest way to find an object in an array is start a
beginning and inspect each element, one after the other until the object is found. This method is called linear search
algorithm.
int index ( int, int [ ], int );
int, a int ()
{
52
int a[ ] = { 22, 44, 66, 88, 44, 66, 55};
cout << “ index (44, a, 7) =” <<index (44, a, 7) << endl;
cout << “ index (50, a, 7) =” <<index (44, a, 7) << endl;
}
int index ( int x, int a[], int n)
}
for (int i=0; i <n; i++)
if (a[c] ==x) return i;
return; / not found
}
Pointer Arithmetic
Pointer
Ptr++ Ptr-Ptr size of (Data-Type). Pointer value is
incremented after execution of statement .
++Ptr original pointer value is incremented before execution
of state-
Ptr-- Ptr= ptr_Size of(Data Type) Pointer value is
decremented after statement
execution.
- - Ptr Original Pointer value is decremented before
execution of statement.
*+ + Ptr Increment - the pointer & then retrieve the contents
of location pointed by Ptr.
*Ptr+ + Increment the content of location pointed by pointer
Pointers and functions
There are two ways in which pointer function is called-
1) Call-by value 2) call by reference
When some portion of program involves a function control will be transferred from min function to the
calling function and the value of the actual argument is copied to function.
When the function is called and from program the altered values are not transferred back this is called call by
value.
E.g..-
Main ()
{
Void func (int A, int B);
Function (A,B); // call by value
-----------------
}
void func ( int x, int y)
{
-----
------
}
In call by reference, when program calls function the actual address is copied on to formal argument. Both
formal and actual arguments are of references of same memory locations. Therefore change in value of formal will
change the value of actual argument.
E.g.:
Main ()
{ void func ( int*A, int*B);
------
------
function ( &A, &B); // call by reference
---------------
}
void funct (int*a, int*b)
{ -------
53
}
Pointers
A Pointer is a variable, which stores the memory address of another variable.
Advantage of pointer.
It allows to return structured variable form function .
It allows to pass variables, arrays, and string to function as argument.
Supporting allocation and deallocating memory segment .
Establish link between data and element.
There are two types of pointer variables. 1.pointer operator 2.address operator
Pointer operator is always indicated with combination of * variable.
e.g. int*ptr;
Address pointer is indicated with combination of & .
e.g. p=&ptr ;
Here *Stands for ‘at address ‘and
&stands for ‘address of ’.
E.g. int A, B;
int ptr2*ptr3;
ptr1=&A;
The memory address of variable A is assigned to the pointer variable ptrz.
. B =ptr z;
B will be assigned value at address ptr z .
Both ptrz & ptrz holds the same address .
PROGRAM.
// Pointer variable.
# include <iostream.h>
int main ( )
{
int n=50;
cout<<”n=<<,’’&n=”<<end l;
int*pn=&n; //pn hold the address of n
cout <<” pn =//<<pn<<end l;
cout<<// &pn =//<<&pn << end l’
}
The variable n is initialized at 50. The variable pn is called d “pointer “ because the value points to the location of
another value. The value of the pointer is an address. That address depends on the state of individual computer.
Program 2
# include <iostream.h>
main ()
{ int A ;
int *ptr;
A=15
ptr = &A;
cout<< “ value of A =” << A<< endl;
cout<< “ content of ptr =” << “*ptr<< endl;
out<< “ address of ptr =” << “ptr<< endl;
}
Pointers Array:
54
There is close relation between data type and array considering
int marks [20];
int * ptr;
The address of first element of array is marks [0]. ptr is also address of variable.
so we can write ptr= & marks [0].
Program:
Pointers and arrays
# include ,<iostream. h>
main ( )
{static int x [5] = {0,1,2,3,4}
int i, n, temp;
n=5;
count << “ content of array “ << end l;
for ( i=0, i<= n-1; i++)
{temp = *[ (a) +(i) ];
cout << “ value = “<< temp << end l ;
{
}
References:
C++ allows the use of reference, which is simply another name of variable that is being initialized
int S =109;
int &Y =S;
Y is an alternative name for S
If we not add 5 to Y,
Y= Y+5
we have the effect that added 5 in S.
Reference is alternative name or synonym for other variable. It can be declared by syntax.
type & ref- name = var-name;
e.g. int & rn=n; // r is another name of n
rn is declared to be a reference to the variable n,
Program:
int main ( )
{
int n=5
int & rn=n // r is alternative name of n
C out << “n=” << , rn = “ rn << end l;
C out << “n=” <<n<< “rn = “<< rn<< end l;
rn*=2;
C out “n=” << n<<” , rn =” << rn << end l;
}
Strings
Class string support many function that could be used to obtain the characteristics of string such an the no of
element currently stored in given string the capacity indicates
The total element that can be stored in given string. Strings are one-dimensional arrays of the type char.
String is terminated by null character, String constants are written in double quotes.
" KIRLOSKAR" is a string of 7 characters and last is null character.
Program to read word from kirloskar and display
# include <iostream.h>
# define max 10
55
main ()
{
char word [ max ];
cout << " Enter word of text \n";
Cin.get ( line, max, '\n');
Cout << line;
}
Principle of Object Oriented Programming
The high level languages like COBOL, C, FORTAN are procedure oriented. The procedure-oriented
approach uses a sequence of thing to do. So number of functions are to be written to do the task.
Principles of object- oriented programming
The major motivating feature in the invention of object-oriented programming is to remove some of the
drawbacks in the procedure oriented approach. OOP treats data as a critical element in the program development and
does not allow it to flow freely around the system. It lies data more closely to function that operates upon it & protect
it from accidental modification from other outside functions.
OOP allows decomposition of problem into a no. of entities called objects & then built data & function around
these objects. The organization of data & function of OOP is shown in fig.
Object A Object B
Object C
Organizations of data and functions in OOP Features of object oriented programming-
1) Programs are divided into objects.
2) More stress is given on data rather than procedure.
3) Data structures are designed such that they characterize the objects.
4) Functions operate on data of an object are tied together in data structure.
5) Data is hidden and cannot be accessed by external functions.
6) New data and functions are easily added.
7) Follows bottom up approach in program design.
OOP is most recent concept among programming.
Definition of object oriented programming
OOP is an approach that provides a way of modularizing by waiting partitioned memory area for both data
& functions that can be used as templates for creating copies of such modules on demand .
Basic concepts of OOP:-
1) Objects :- Objects are runtime entities is OOP system. This may represent person, account, name, and table of
data or any other that program handles . They represent user-defined data such as vectors , time and lists . Program
objects should be chosen such that they match closely with real world objects . When the program is executed , the
objects interact by sending messages to one another.
Example-
Data
Functions
Data
Functions
Data
Functions
Object : Student
Data
Name
Date of Birth
Marks
Functions
Total
Avg.
Total
A
e
56
Two ways of representing of an object.
2) Classes :- The entire set of data and code of an object can be made a user defined data type with the help of class. The
objects contain data and code that manipulates data. Once the class has been defined we can create any no. of objects
which belong to same class. The class is collection of similar types.
E.g.- Apples, Bananas, Oranges are members of class fruit classes are user defined data types and behaves like built
in types of programming language.
3) Data Abstraction and encapsulation :
The wrapping up of data & functions in a single unit is called encapsulation and the insulation of data from
direct access by the program is called data hiding.
Abstraction means the act of representing essential features without background.
4) Inheritance:
Inheritance is the process by which objects of one class acquire the properties of another class. Inheritance
supports the hierarchical classification.
E.g.- Boys & Girls grouped under human class.
5) Polymorphism:
It means ability to take more than one form.
E.g. consider the example of multiplication ;the number the of additions with generate a sum.
6)Dynamic Binding :
Binding refers to the linking of procedure call to code to be executed in response to call .
7) Message passing :
process of OOP involves the following basic concepts.
1)Creating class that defines objects and their behavior
2)Creating class from class definition
3)Establishing communication among objects
Objects communicating with one another by sending & receiving information.
Advantages of OOP
1)Elimination of redundant code
2)classes
3)standard working modulus for communication
4)data hiding
5) Helps to build secure program
6)Software complexity can be easily handled
7)Message passing technique is employed
Display
57
OO Languages:-
OOP is not the eight of any particular language such as C and Pascal.
Object base programming is style of programming that supports encapsulation and object identity.
Major features are
1) Data encapsulation
2) Data hiding
3) Automatic initialization
4) Operators overloading
Applications of OOP:-
The following are the area in which OOP is used.
1) simulation and modeling
2) Real line systems
3) OO data-bases
4) Hypertext & expertext
5) AI and expert systems
6) Neural Networks
7) CAD/CAM/CIM systems
8) Office automation.
CLASSES AND OBJECTS
Class binds the data and it’s associated function together. It allows data and functions to hide from external
use. While defining a class we create new abstract data type that can be treated like any other built in data type.
The class has two parts
class declaration
class function definition
The class declaration describes the type scope of its members.
The general form of class declaration :
class class-name
{
private :
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
Here the class declaration is almost similar to a struct declaration . The keyword class specifies that follows
an abstract data of type class name. The body of class is always enclosed in braces and terminated by semicolon. The
body contains declaration of variable and function and these are collectively called class members. Class members
are generally grouped in private and public followed by colon.
The members declared by private can access with in the class and public will access from outside the class
also. By default member of class is private .
The variables declared inside the class are known as data members and functions are called member
functions.
58
Examples of class declaration
class declaration
{
int runs; //variable declaration
float avg; //private by default
public:
void getdata (int x, float A); // functions declaration
void put data (void);
};
Here cricket is name of class which contains two data members and two data functions, by default data member is
private and function are public.
CREATING OBJECTS
Declaration of cricket does not defined any object of cricket but only specifies what they will contain, once
class has been declared we can create variables of that type using class name.
cricket x; memory for x is created
Here x is called variable of cricket and we call this variable as object. Therefore x is called object of type cricket.
cricket x, y, z;
objects also can be created when class is defined by placing their names immediately after the closing brace.
class cricket
{
_____
_____
}
x, y, z;
This would create the objects x, y, and z of type cricket.
ACCESSING CLASS MEMBER
Private data of a class can be accessed only through the member functions of that class. The general format
of accessing member function.
object-namefunction-name(actual-argument);
Example :
x.getdata(10,5.2);
This assigns value 100 to number and a 5.2 to cost of object
Similarly it put the value by x.put data( );
DEFINING MEMBER FUNCTION
* outside class definition
* inside class definition
function body is identical in both cases.
1)OUTSIDE CLASS DEFINITION :
The member function which is not declared inside class has to declared outside of the class.
return-type class-name::function-name
{
function body
}
void sangli::getdata (int x, float y)
{
umber = x;
average = y;
}
void sangli::putdata(void)
{
59
cout<<”numbers”<<number<<”\n”;
cout<<”average”<< average <<”\n”;
}
INSIDE CLASS DEFINITION
member function is declared within class
class shruti
{
int number;
float average;
public:
void gatedata(int a, float b);//declaration
void putdata (void);//definition
{
cout<<number<<”\n”;
cout<<average<<”\n”;
}
};
TO MAKE OUTSIDE FUNCTION INLINE
inline void shruti:: getdata (int a, float b)//is declared
ARRAY WITHIN CLASS
The array can be used as member variable in class. The valid definition is
const int size=25;
class shruti
{
int a[size]; ‘a’ is integer type array.
public:
void setval (void);
void display(void);
};
Example :
Teachers[7]; //array of teachers
Students[30]; //array of students
STATIC DATA MEMBERS
A data members of a class is static , which has similar properties to that of C.
Static member has following characteristics
1) It is initialized to zero when first objects is created.
2) Only copy of that member is created for entire class and shared by all the objects of that class.
3) It is visible only within class.
The static variables are generally used to maintain values common to entire class.
Example: class shruti
{
static int number
--
--
}
STATIC MEMBER FUNCTION
Like static member, variable static member functions have the same type .The members function is declared
static by the following properties.
A static function can have access to only static members declared in same class
member function is called using class name as
class-name::function-name;
e.g.class marks
{
static void show count (void)
{
_----------
}
}
60
test::show count ( );
FRIENDLY FUNCTIONS
Private members can not be accessed outside the class. The non members function can not be a member of
private data of class. But when two classes share a particular function in that condition friend function is used. In the
shared mode c++ allows common function friendly to both classes.
Example :
class shruti
{
___
___
public
___
___
friend void shruti (void); //declaration
};
The function declaration should be proceeded by the keyword friend. The function declared that are declared
with keyword friend are called friend functions .Function can be declared in many number or classes.
OBJECTS AS FUNCTION ARGUMENT
Like other data function may be used as function argument. This can be achieved in two ways
1) passing entire object to function
2) by passing address of object to function.
The first method is also called pass by value. Single copy of the object is passed to the function and any
change made to the object inside the function do not affect the object used to call the function. The second method is
called pass by reference.
Only address is transferred to function and function works
directly on the actual object used in the call.
Change made inside function are refereed in actual object.
The pass by reference method is more efficient because only address is passed rather than whole object.
RETURNING OBJECTS
A function can not be only receive objects as argument but also return then.
CONSTANT MEMBER FUNCTION
If the member function does not change any data in the class the function is declared as constant.
e.g. void mul (int, int) const;
POINTERS TO MEMBERS
It is possible to the address of the member class to the pointer .This can be achieved by operator & to the
fully qualified class member name. A class member pointer can declared using the operator ::* with class name.
Example :
Class shruti
{
private:
int S ;
public :
void show ();
};
We can define a pointer to member S as follows
Int shruti ::* ip = &shruti ::* S;
Here ip pointer created acts like class member
shruti ::* pointer to class shruti
61
&shruti ::* is address of S member class shruti.
Local classes
The classes defined and used inside the function or block are called local classes.
Void test (int a) // function
{
----------
----------
class shruti // local class
{
---------- // class definition
----------
};
--------
----------
student.S1(a) // create object
----------
----------
}
Local class can use global variable.
62
CONSTRUCTOR AND DESTRUCTORS
Constructor is a special member function whose work is to initialize objects of its class. Its name is same
to that of class name. The constructor is invoked whenever a object of its class is created.
It constructs the values of data members of the class.
Declaration of constructor
//Class with constructor
class integer
{
int a, b;
public:
integer(void); // Constructor declaration
----------------
-------------------
};
integer ::integer(void) // Constructor declared
{
A=0;B=0;
}
The constructor that accepts no parameters is called the default constructor.
Characteristics of constructor
They must be declared with public section.
They are initialized automatically when objects are created .
They do not have return type .
They can’t be inherited though a derived class.
They have refer to their addresses.
An object with constructor can’t be used..
Parameterized constructor C++ permits us to pass arguments to constructor function when the object are created. The constructor that
takes the arguments are called parameterized constructors.
Constructor integer( ) many be modified to the arguments.
Class integer
{
int A,B
public:
integer(int x, int y);
-------------
------------
};
integer :: integer(int x, int y)
( a = x; b = y;
}
Multiple constructors in a class Till now we have discussed 2 types of constructors
i.e. integer( ); //no arrangements
integer (int ,int); //2 arrangements
In first case constructor itself provides data values and no values are passed by calling program .In second case
function call passes the approximate value from Main( ) . Both constructors may be used in same class .
C++ allows to use more than one constructor in the same class.
Class shruti
{
63
int A,B;
public:
shruti ( )
{ a=0; b=0} //constructor 1
Shruti( int x.int y)
{ a=x; b = y;) //constructor 2
int shruti ( shruti &I )
(a=I.a; b=i.b;} //constructor 3
};
The above program declares three constructors for a shruti object .
The first constructor receives no object ,second receives 2 arguments and third receives one integer object as an
argument .
When more than one constructor is defined in a class .It is said to be overloaded.
Constructors with default arguments .
Default constructor is declared as follows .
Complex ( float real, float imag=0);
Here the default value of argument imag is zero.
Complex a(4,0);
assigns value 4.0 to real and 0.0 to imag , but if the statement.
Complex A(10.0 , 4.5);
Assigns 10.0 to real and 4.5 to imag.
Dynamic initialization of objects.
Dynamic initialization provides initial values of an object during time. It provides various initialization
formats using overloaded constructors.
COPY CONSTRUCTORS
Copy constructor is used when compiler has to create temporary object to a class object. This constructor is
used in the following format.
Class name ::class name (class-name&ptr)
Example : a::a (a&ptr)
Ptr is pointer to class a
PROGRAM
KHS( ) //constructor
{
x0=0;x1=1;
x=x0+x1;
}
khs ::khs ( khs&ptr) //copy constructor
{
x0=ptr.x0;
x1 =ptr.x1;
x=ptr.x;
}
DESTRUCTOR
Destructor is used to destroy the objects that have been created by constructor. Like constructor destructor
is a member function , whose name is same as that of class name .but preceded by a tidle ,consider dsestructor of
class shruti.
Example :
~ shruti ( ){ }
64
A destructor never takes any argument nor does return any value destructor releases memory space. The new is
used to allocate memory space and delete with free memory space.
Matrix :: ~ matrix( )
{
for {int I=0;~matrix( )
{
for(int I=0;I<d1;c++)
delete p[I]
delete p;
}
Destructor program
#include<iostream.h>
int count=0;
class khs
{
public:
khs( )
{
count ++
cout<<”\n no of objects created “<<count;
}
~khs( )
{
cout<<”\n no of objects destroyed “<<count;
count - - ;
} };
int main( )
cout<<”\n \n enter in main\n’;
khs x1,x2,x3.x4;
{
cout<<”\n \n enter block1”;
khs x5;
}
{
cout<<”\n \n enter block 2\n”;
khs x6;
}
cout<<”\n\n re-enter main\n”;
return 0;
}
OPERATOR OVERLOADING
Introduction:
One of the important features of C++ is operator overloading. The operator overloading enhances the power
of extensibility of C++. C++ permits us to add two variable of user defined types with the same syntax that is applied
to the basic types. The C++ has the ability to provide the operator with special meaning for data types. The
mechanism of giving such special meanings to an operator is known as operator overloading.
The flexibility is provided by the operator overloading. The following operators can not be overloaded
class member access operator ( . , .*).
Scope resolution operator (::)
Size operator ( size of ).
Conditional operator.
The syntax of semantic operator is not changed.
Defining operator overloading
The overloading means to give the extra task to the operator. We have to specify what it means in relation to
the class which the operator is applied. This can be done with special function called operator function.
65
General format
return type class-name :: operator
{
function body // task defined
}
The operator function can be either member function or friend functions.
Overloading involves the following steps.
1) Create a class that defines data type.
2) Declare the operator function operator op() in the public part of class.
3) Define the operator function to implement the required operations.
The overloaded operators can be shown by
op x or x op
for unary operators
x op y
for friend functions both forms are declared.
x op op (y)
Program :
# include <iostream.h>
class space
{
int a;
int b;
int c;
}
public :
void getdata ( int x, int y, int z);
void display (void);
void operator – (); // overload unary minus
};
void space :: get data ( int x, int y, int z )
{
a = x ;
b = y;
c = z;
}
void space :: display (void)
{
cout << a<< “----“ ;
cout << b<< “----“ ;
cout << ca<< “----“ ;
}
void space :: operator –() // defining operator –()
{
a = -a ;
b = -b;
c = -c;
}
main ()
{
space s;
s.get data ( 20, -15, 40);
cout << “ s : ” ;
s.display ();
-s; // activate operator –()
66
cout << “s:”;
s.display ();
}
RULES FOR OVERLOADING
Only existing operator can be overloaded.
Overloaded operator must have at least one operand that is of user defined type.
Overloaded operators follow the syntax rules of original operators.
Basic meaning of the operator can not be changed.
Certain operators can not be overloaded
Size of, ., .*, :: and ?:
certain operators can not overloaded by friend function like
=, (), [ ], etc.
Binary operators +, -, * and / must return a value.
TYPE CONVERIONS
Constants and variables of different types are mixed in an expression then automatic type conversion takes
place.
Example :
int A
float B= 3.142
A = B;
Conversion of B to an integer before its value is assigned to m and factorial part is truncated. The conversion is
automatic as long as data type is built in type. When the data type is user defined type the operations of addition and
assignment are carried out smoothly and when objects are of different class gives errors. For user defined type
compiler does not support automatic type conversions.
There are three basic conversions-
1) Basic to class conversion
This is easy to accomplish. The constructors may be used to initialized the objects.
String :; string (char*a)
{
length = strlen(a);
p = new char [ length + 1];
strcpy (p.a);
}
The constructor builds a string type object from a char* type variable a. The variables length and p are data members
of the class string.
Let’s consider the example of converting an int type to a class type.
Class distance
{
int kms;
int mts;
public:
distance (int); // constructor
{
kms = D/1000;
mts = 10%1000;
}
67
}
2) Class to Basic type conversion
The constructor does not allow to construct class to basic conversion, so overloading casting operator is
used to convert class to basic type conversions.
General format of casting operator is
Operator type name ()
{
------
------- ( function )
}
Example : The operator double () converts the class objects to type double, the operator int () converts
class type to type int.
Consider the conversion
Vector :: operator double ()
{
double sum = 0
for ( int i=0; i<size; i++ )
sum = sum + v[i]* u [ i ];
return sqrt (sum);
}
This converts vector to scalar magnitude.
Casting operator function should satisfy the following conditions
It should be a class member
It should not specify return member.
It does not have arguments.
3) One class to another class type
Obj A = obj B
Obj A is an object of class A and obj B is an object of class B. The class B type data is converted to the class
A type data and the converted value is assigned to the obj A.
INHERITANCE
Classes created can be reversed in several ways. Creation of new class by using the properties of old &the
deriving a new form an old class is called "inheritance" or "derivation".
The old class is referred to on base class &new one is called the derived class or subclass.
When class is derived with only one base class is called single inheritance.
Single inheritance
One derived class from served base classes is called multiple inheritance.
Multiple inheritance-
Where more than one classes are derived from single base class is called hierarchical inheritance.
A
A
B
B
A
A
D
A
B C
68
Hierarchical inheritance-
The mechanics of derived class from derived class is called multilevel inheritance.
Multilevel inheritance-
The combination of both multiple & hierarchical inheritance forms hybrid inheritance.
Hybrid inheritance
Defining Derived Classes:-
Derived class can be defined by specifying 'its' relationship with the base class in addition to its own details.
General form:
Class derived-class-name : visibility- mode base class name
{ -------
--------
--------
};
the colon indicates the derived class name.
Example
Class Shruti : private KHS // private derivation
{
member of Shruti
};
class Shruti : public KHS // public derivation
{
member of Shruti
};
class Shruti : // public derivation by default
{
member of ABC
};
Hence class is private inheritance by derived class at that time public members of the base class becomes private
members of the derived class.
Making Private Members Inheritance:- The third visibility modifier called protected which serve for limited purpose inheritance. A member declared
on protected is accessible by the member function within its class.
Class computer
{
private:
--------
--------
protected:
-------
--------
public
-------
B C D
A B D C
A
D
A A
69
---------
}
when a protected member is inherited in public made it become protected in the derived class to, & thus accessible
by the members functions of the derived class. A protectable member inherited in the private mode derivation
becomes private in derived class.
Friend functions &the member functions of a friend class can be direct access to both the private &protected data.
Multilevel Inheritance:-
Here class A serves as base class & B as derived from class B & C is derived from class B, while d is
derived from class C. The class B,C are called intermediate base classes & the path ABCD is called inheritance path.
The multilevel inheritance format is as bellow:
Class W {------};base class
Class x: public w{----}; //x derived class
Class y: public x{----}; //y derived class
Class z: public y{----}; //z derived class
Base class [ class w ] grand grand fathers
Intermediate base class [ class x ] grand fathers
[class y ] fathers
derived class [class z ] child
Hierarchical Inheritance:-
Base class in hierarchical inheritance include all the features that are common to subclass. A sub class can be
constructed by inhering the properties of the base class.
Hybrid Inheritance:- This is a multilevel multiple inheritance.
Class computer
{protected
float score;
public
void get-score(float);
void put-(score);
};
The result can be declared on follows class computers: public test, public computer
{
-------
-------
};
Her test itself is a derived class from student.
INDIA
UT STATES
UP MAHARASHTRA MP
Student
Test
Result
Computer
70
Class test: public computer
{
----
----};
VIRTUAL FUNCTION:-
When all the 3 kinds of inheritance namely, multiple, multilevel, hierarchical are used in this condition
virtual function is used.
Here the child inheres a traits of grandfather via 2 separate path. The child can duplicate sets of members
inherited from grandparent.
The duplication of inherited members due to these multiple paths can be avoided by making the common base class
on virtual class.
Class A
{
----------- //grandparent
------------
};
class B1: virtual public A //parent 1
{----
-----
};
class B2:public virtual A //parent2
{------
-------};
class ?C: public B1; public B2 //child
{-----
-----
};
when class is virtual then only one copy of that class is inherited.
Abstract Classes:-
The class is used to create objects. It is designed to at as base class which is inherited by other classes.
Constructed in Derived Class:-
The constructor of derived class receives the entire list of values as its argument & passes them on the constructor in
the order in which they are declared in derived class.
NESTING OF CLASSES:-
All objects of class will be contained in objects . this kind of relationship is called nesting ".
Example.
Class Shruti {------};
Class KHS{};
Class KIRLOSKAR{};
{
Shruti a; // a is object of class Shruti.
KHS b; // b is the object of class KHS.
};
Polymorphism
Grandfather
child
Parent 1 Parent 2
71
Polymorphism is one of the crucial features of object oriented programming. It means one name &multiple
poems. If number of appropriate member functions would be selected while the program is running. This is called
run time polimerphism.
Polymorphism
Compile time run time
Polimorphism polymerphism
Function overloading operator overloading virtual functions
At run time class objects are under consideration then apprapriate function is involved. Since the function is linced
with particular class much lator the compilation this process is termed on data binding. This uses pointers &objects.
POINTERS TO OBJECTS
Pointer can point to an object created by a class.
Example : item x;
where item is class and x is object defined to type item.
Similarly we can define pointer it-ptr of type item as follows
item*it=ptr;
Object pointer are useful in creating objects at run time.
class Shruti
{
int code;
float price;
public:
void getdata(int a, int b)
{
code=a;
price=b
}
void show(void)
{
cout<<"code:"<<code<<"\n";
<<"price:"<<price<<"\n";
} };
Now lets declare item variable x and pointer ptr to x as follows.
item x;
item*ptr=&x;
The ptr is initialised with address of x.
this POINTER
The keyword "this" represents an object invokes member function . this is a pointer that points to the object for
which this functions was called.
eg:- this -> a = 125;
POINTERS TO DERIVED CLASS
Pointers are objects of derived classes pointers to objects of a base class are type compatable with pointers
to objects,if a derived class.
72
If A is the base class and B is the derived class from A,then pointer declared as a pointer to A can also be pointed
to B.
VIRTUAL FUNCTIONS
when we use the same function name in both the base and derived classes. The funcyion in base class is derived as
virtual. It can be used at runtime on the type of object pointed to by the base pointer rather the type pointer.
RULES FOR VIRTUAL FUNCTIONS:-
1] It must be member of some class
2] Should not be ststic member
3] They are accesed by object pointers
4] Virtual functions are friend of other classes.
5] Virtual constructor is not allowed.
6] The base pointer can point any type of derived object.
7] When base pointer points to derived class the incrementation and decrementation is only relative to its
base type.
8] Virtual funtions are defined in base class.
PURE VIRTUAL FUNCTIONS
In the normal way virtual funtions is declared in base class redeclared in derived class.The function
inside the base class is used for performing any task.
Example : virtual, void display( ) =0;
is a pure virtual functions. The class contains pure virtual functions is called abstract base class.
Working with files
In real life large data is to be handled and for that purpose storage disks are used. The data stored on the disk
using the concepts of the files. A file is nothing but collection of data stored on the disk.
The data will be moved in two ways.
1) Between console and program
2) Between program and disk file.
C++ uses the file streams as an interface between program and a disk files. The streams that supplies data to the
program is known as input stream and receives data from the program is known as output stream.
Input stream
Read data Data input
Write data output
Output stream.
Fig. Input output streams
The input operation involves creation of an input streams and linking with the program and the input file. Similarly
output operation involves establishing an output stream with links to programs and output file.
CLASSES FOR FILE STREAM OPERATIONS
Disk files Program
73
The file stream classes includes ifstream, of stream and fstream. These classes are derived from fstreambase
and from corresponding iostream.
fstreambase -- provides operations common to file stream.
ifstream -- provide input operation , contain open () default input mode
ofstream -- provides output operations contains open() with default mode.
fstream -- provide support for simultaneous input and output operations.
OPENING AND CLOSING A FILE
A file can be defined using the classes, ifstream, ofstream and fstream
that are in header file fstream .
A file can be opened in two ways :
(1)using constructor function class
(2)using open( ) function of class
The first method as useful when we use only one file and second in multiple files.
OPENING FILES USING CONSTRUCTOR
When objects are created by using constructor. Here the file name is used to initialize the file stream objects.
(1)ofstream is used to creat output stream and ifstream to creat with input stream.
(2) Initialising the file object with derived file name.
The connection with file is closed automatically when stream object express.
OPENING FILE USING OPEN( )
The function open( ) can be used to open multiple files that uses same stream object .If we want to process a
set of files. In that case, we can creat a single stream object and use it to open each file in turn.
file_stream _class stream _object :
stream_object.(" file name)
DETECTING END-OF FILE
To prevent the reading of data from file detection of end _of file is necessary .
while(fin)
fin returns a value 0 if any error in file operation including the end of file condition .The while loop terminates when
fin returns a value of zero on reaching the end of file condition.
if(fin1.eof( ) !=( ){exit(1);}
eof ( ) is member function of 10s class.
eof means end of file .
OPEN FUNCTION
ifstream and ofstream constructor and function open( ) used to creat new file as well as open file existing files.
stream _object.open("filename",mode);
74
PARAMETERS MEANING
ios::app append to end of file
ios::ater go to end of file on opening
ios::Binary Binary file
ios::in open file for reading only
ios::nocreat open fails if file does not exists
ios::noreplace open file if file already exists
ios::out open file for only writing
ios::menu delet the contents of file if it exists
FILE POINTER & THEIR MANIPULATORS
Every file has two pointers known as file pointer ,one is input pointer
or it is also called get pointer and other is called output pointer or put pointer .These pointers are used to move files
while reading and writing. The get pointer is used to read data from given location and put pointer is used to write
data to given location .The pointer is set at the beginning
Input pointer
Output pointer
Functions for manipulation of file pointers
* seek () moves input pointer to specified location.
* seekp () moves put pointer to specified location.
* tell g () gives the current position f get pointer.
* tell () gives the pointer byte function
example : infile.seekg ( 20 ).
This moves the pointer to byte number 20
Put () and get () functions
Put() function write single character to associated stream and get () function reads single character from
associated stream.
read () and write () function
Write () and read (0functions handle data in binary form. The values stored in the disk file are in same
format as they are stored in the internal memory. The binary format is more accurate for storing the numbers.
Reading and writing a class
The binary input and output functions read () and write () are designed to do exactly the particular job. These
functions handle the entire structure of an object as single unit. Write function copies a class object from memory
byte by byte with no conversion.
Updating a file
Updating is a routine task of maintenance of any data file. Updating includes the following tasks –
Displaying the contents of the file.
A B C ------
A B C D E F
75
Modifying the existing item.
Adding a new item.
Deleting an existing item.
Error handling during the file operation
While opening and closing file errors occurs.
A file which we are attempting to open for reading does not exist.
The file name used for new file may already exists.
We may attempt an invalid operation.
There may not be any free space in disk for data storing.
If invalid file name is used.
Error handling functions
eof () Returns true if –end-of – file is encountered while reading
otherwise return on false
fail () Return true when input or output operation has failed.
bad () Return true if valid operation is attempted,
if error and not possible to correct then false.
good () Return true if no error has occurred.
If false no further operation can be carried out.
// A PROGRAM TO WRITE IN THE FILE IN out MODE.
#include<conio.h>
#include<iostream.h>
#include<fstream.h>
main()
{ char n[23];
fstream a("file2.txt",ios::out);
clrscr();
cin>>n;
a<<n;
getch(); }
// A PROGRAM TO READ FILE BY eof().
#include<iostream.h> #include<fstream.h>
#include<conio.h>
main()
{
char n[5];
ifstream lmn("file2.txt");
clrscr();
while(lmn.eof()==0)
{
lmn.getline(n,5);
cout<<endl<<n;
}
getch();
}
Exercise :
1. To read the data from the file, the file should be operated in ---- mode.
a) Input b) Output c) Append d) None
2. Write any six main advantages of OOP. (M-2003)
76
3. What is operator overloading? State the three steps involved in process of overloading. (M-2003)
4. Explain the difference between static and dynamic binding with suitable example. (M-2003)
5. Explain any six characteristic of constructor function. (M-2003)
6. What is class? Give the general form of class declaration.(M-2003)
7. What is inheritance in C++? What are the different forms of inheritance? Give example of each. (M-2003)
8. Write a C++ Program to sort of 10 floats in descending order using bubble sort method. (M-2003)
9. Implement a class convert to convert degree Centigrade values to Fahrenheit degree. (M-2003)
10. Write a function in C++ hat is passed in an array of n pointers to floats and return to the maximum of the n
floats. (M-2003)
11. Implement a point class for two dimensional points (x,y). Include a function norm() to return the points distance
from origin (0,0) and a print () function to print the result. (M-2003)
12. Write a C++ Program to display a series of 15 terms of the Fibonacci series. (M-2004)
13. Write a C++ program to replace every space in inputed string (less than 80 characters) with a hyphen (i.e. -)
(M-2004)
14. Write a C++ program to find Factorial of a natural number inputed during program execution. (M-2004)
15. What is operator overloading ? Explain with suitable example. Why it is necessary to overload an operator. (M-
2004)
16. What are pointers in C++? Explain the use of pointer variables for function definitions using call by value and
call by reference.(M-2004)
17. Explain how the memory address of a variable can be accessed in C++. (M-2004)
18. Explain the following OOP concepts with suitable example of each.
a) Inheritance b) Polymorphism c) Data Abstraction.
19. Explain the use of scope resolution operatior and memory management operators in C++ with examples. (M-
2004)
20. What are classes in C++ for file stream operation? How do you open and close files in C++ ? Explain any four
file modes. (M-2004)
77
Chapter - IV
HTML Introduction to HTML
The long form of HTML is Hypertext Mark-up Language. The Hypertext is ordinary text that has assigned
extra features such as links, formatting, multimedia, images etc. to other documents. The mark-up is the process of
taking ordinary text and adding extra symbols such as editor’s proof reading symbols are type of markup. Each
symbol used in the HTML tells the browser how to display the text. HTML is a computer language which is related
to programming languages like BASIC, C, Pascal. It has its own rules and syntax. HTML is a special type of
computer languages. They are concerned with only part of documents according to their functions. They indicate
which part of document is title, which is subheading, which is author name and so on. HTML is not a programming
language, but it is a markup language.
Why HTML
The internet is international network of computers connected for exchange of information with each other.
The world wide web (www) is a vast inter connected library of information, art and commerce. The web consists of
several pages. Once the web page is build it can be published on the internet. So that all the people can access it.
There are huge variety of web pages. For example : Personal home page, business home pages, directories, search
engines, etc. HTML document can not only be put on the computer screen but also on printer, fax machine, TV sets,
games, digital watches, etc.
Advantages of HTML
* HTML is used to create a HTML document.
* No special software is required.
* It can be written on the notepad and can be run on the windows.
* You can work on the HTML away from your computer.
* The document can be created on any hardware platform.
* It is easy to understand.
* Easy to find the errors.
* Learning HTML is easier than any other programming languages.
* You can work independently without any rely on other program.
* HTML is free to use, It will not cost to for using.
* It is the simplest method for designing the web page.
78
Disadvantages of HTML
* It can’t display even date.
* Even simple calculations can’t be done in HTML.
* In true sense it is not a programming language.
* Web page developed in HTML can not have its own interface.
* Web page developed in HTML can not behave like application.
* Need to strip server each time.
* Interactive web pages can not be built by HTML.
Study of tags in HTML
A tag is a unit of mark-up having the set of symbols defined in HTML with some special meaning. The tags
always starts with less than sign (<) followed by the key word and ends with the greater than sign (>). These
symbols are called angle brackets.
Example of the tags : < TABLE>
< HTML>
<>BODY>
The tag contains some meaning and it’s meaning is straightforward to indicate the particular application on the page.
For example <B> it switches to the bold. There are two types of tags.
1) start tag 2) End tag
The start tags has starting effect or beginning effect and end tag has end effect of the keyword. The end tag
always indicated with slash in front and after that greater than sign.
Example : The text “Kirloskar” is displayed in bold then the start tag and end tag is written as follows.
< B> Kirloskar </B>
Here <B> is starting bold tag and </B> is end of the bold tag.
The word Kirloskar is displayed in bold letters.
The tags can be places inside the other tags.
Suppose if the <B> is used for bold and <I> for italic tag then one can combine then as
<B> <I> Kirloskar </I> </B:
The word Kirloskar will appear in italic bold. The inner tags <I> must be completed before the end of the outer tags
<B>. One can include number of tags in nested within other.
Tag attribute:
The tag attribute is a effect of the tag’s behavior. A attribute is a keyword separated by the a space within
the angle brackets is called tag attribute.
For example: <HR with shade> this means for an shaded horizontal rule.
Some attributes requires a value preceded by equal sign such as <HR WIDTH = “100”> This means that
horizontal rule is of 100 units wide. In the browser the tags are not displayed but their effect is displayed. The tags or
attributes which are unknown are ignored.
The Web page and Web Page requirement :
Each web page consists of few tags which defines the page as a whole.
Example: <HTML>
<HEAD>
<TITLE> XII class Computer Science </TITLE>
<HEAD>
<BODY>Theory paper is very easy
</BODY>
<HTML>
79
The browser on Internet will display Theory paper is very easy on the screen.
The above code consists of different tags such as <HTML>, <HEAD>, <TITLE>, </HTML>, </HEAD>, and
</TITLE>. The above HTML code can also be typed by using text editor.
The detail study of the various tags :
< HTML > tag : This tag declares the text that follows, defines the web page that can be viewed in a web browser.
The closing of the HTML code is given by the tag </HTML> which ends the page. The document is started by tag
<HTML> and closed with </HTML> tag.
<HEAD> tag : This defines the header area of the page and not displayed in page of the browser. The opening of
the header section is done by < HEAD> tag and closing of the header section is denoted by </HEAD> tag.
<TITLE> tag : This tag is used within the <HEAD> tag. The text between the <TITLE> and </TITLE> will be
displayed in the title bar of the browser. The title is used frequently to find the program to name the web page and it
should be descriptive. The extra spaces are not allowed between the title tags.
Fig. Basic structure of HTML document
< BODY > tag : The actual contents displayed on the web page will appear in the body section. This section starts
with <BODY> and ends with </BODY> tag. We can change the font size and even set the different colours in the
body section. The several other functions can be done in the body tag.
<P> tag : The <P> tag is used to create the paragraph of the text. To create the paragraph the text is enclosed within
the <P> and </P> tag. Here the every time you enter then the already made paragraphs are ignored. You have to
define the specific paragraph by defining a code in HTML using <P> tag.
Example
<P>The communication is sharing of thoughts with one another. Communication can be defined as basic process of
exchanging information. </P> . <P> The information may oral or in written or printed form. In practice
communication involves the conversion of message. </P>
This will appear as two separate paragraphs in browsers page. The length of each line determined by the browsers
window. The browser may inserts extra spaces between the paragraph. To get the text onto the next line browser will
use <BR> tag.
For example : S. A. Patil <BR> 189, Nishant Colony <BR>
Narsinghwadi <BR> Tal – Palus <BR> Dist - Sangli-416308.
<BR> India. Ph. (02346) 222333
The above example shows that the address is broken into many separate lines
S. A. Patil
<HTML>
</HTML>
<HEAD>
</HEAD>
<BODY>
</BODY>
<TITLE>
Title of document
</TITLE>
Actual document
80
189, Nishant Colony
Narsihnghwadi
Tal – Palus
Dist - Sangli-416308.
India. Ph. (02346) 222333
The line break takes back to the left margin. The paragraph has three different attributes they are as – <P align =
left> This is left alignment of the paragraph of the text.
<P align = right> The text is aligned to right margin.
<P align = center> The text is aligned center.
<HR> tag : Here HR refers to the horizontal rule which divides the document into two sections. <HR> tag is used
to divide the documents. The purpose of this tag is decorative type only.
Example : To design a web page for school containing name of school appearing on the top then table contents
showing the linkage to the other pages, which appears in the next section and important notes at the bottom.
81
Name of School
Table of contents and link to
other page
Important notes
Fig. 1 shows the section of the page.
The <HR> tag takes several attributes
Example : The thickness of the line on the browsers window can be changed by
<HR SIZE = “7” WIDTH = “70”>
This has the ability to display a line of 7 pixels thick which spans 70% of the browsers window.
Heading Hierarchy: ( width heading)
Web page design has 6 different sizes of headings, they are <H1> to <H6>. The use of the heading can be
random. Generally first level heading is used at highest level and sixth is lowest level. When the structure of the page
is designed then normally first level heading appears on the page. So <H1> is used at that instant of time. <H2 tag is
used to reduce the heading size and even H3, H4, H5 and H6 can be used according to desired size.
Example : <H1> Sangli is district place </H1>
The text Sangli is district place appears at level 1 font. For fine quality printing <H5> and <H6>
tags are used.
Heading Size 1
Heading Size 2 Heading Size 3 Heading Size 4
Heading Size 5
Heading Size 6
The heading can appear with the following attributes –
ALIGN = “RIGHT”
ALIGN = “LEFT”
ALIGN = “CENTER”
ALIGN = “JUSTIFY”
Example : <H2 ALIGN = “CENTER”>
<H2 ALIGN = “RIGHT”>
All the above attributes are used to control the horizontal alignment of the heading. Heading attribute need
not be closed they themselves are closed in opening tag only. Justify alignment makes text appears with smooth
margins on both left and right side.
TEXT FORMATING:
To give the additional weightage to the text of word and phrases the bold, italic, underline is done. So for
formatting the text <B>, <I>, <U>, <PRE>, <ADDRESS> tags are used. The details of these tags are –
<I> tag : This tag is used to create italic appearance of the text on page. This <I>tag is opening tag and </I> is
82
closing tag.
Example : <I> H. S. C. Board </I> H.S.C. Board will appear in italic form
<B> tag : This tag is used to get the text in bold face. It has <B> opening tag and </B> closing tag.
Example : <B> Lion is king of animals </B>
Here Lion is king of animals text appears in bold face.
<U> tag : This tag is used to get the underline to the text. <U> tag is opening tag and </U> is closing tag of the
underline effect.
Example : <U> Computer Science </U>
Generally underling of the text is avoided because browsers indicates hypertext links in web by indicating the
underlining of particular text.
< PRE > tag : This tag is used to display the text in monospace or positioning the text of the character. <PRE> is pre
format the text. The text appearing between <PRE> and </PRE> is displayed in monospace.
Example : <PRE> Shivaji University Kolhapur </PRE>
The display format is
Shivaji University Kolhapur
<ADDRES> tag : This displays web pages information such as page Uniform Resource Locator (URL), author,
name, date, last update, information and so on in italic in your browser. The address is a search engine for the
address information.
URL is address for a web page and unique for each page.
Example : http :// www.hotmail.com
Here http is hypertext transfer protocol. The addressing can also be used as follows.
<Address> email : [email protected] </Address>
<EM> tag : This is emphasis tag. The text between <EM> and </EM> will be displayed in italic.
Example : <EM> Principal is the head of the institution </EM>
The above sentence will appear in the italic form.
<STRONG> tag : This tag is used to get the text larger which lies in between <STRONG> and </STRONG>. This
is used to give more stress on the bold word of the text.
<LI> tag : This is a list tag used for listing n sequencing the text. There are three types of listing tags-
1) Unordered lists - bulleted
2) Ordered lists -. are number in some faction
3) Definition lists – This consists the term following the definition.
The ordered and unordered lists have start and end effects tags. Each term in ordered list begins with <LI> tag. In
unordered list each term begins with some bullet like square, closed circle, open circle, disc, etc. The unordered list
has <UL> and </UL> tags.
Example : <TITLE> Subject list of XII class </TITLE>
<BODY>
<UL> <LI> PHY
<LI> CHEM
83
<LI> Com. Sci.
<LI> English
</UL>
This will display as
PHY
CHEM
Com. Sci.
English
Here we have used both <LI> and <UL> tags together in list.
<UL> and <LI> tags have same set of attributes
TYPE = “Square” represents solid block
TYPE = “disc” represents solid bullet circle
TYPE = “Circle” represents solid block
The default appearance for a list is with disc.
Example : To represent the subject with different types
<UL TYPE = “”Circle”>
<LI> PHY
<LI> CHEM
<LI TYPE = “DISC”> Computer Science
</UL>
The displayed format will be
PHY
CHEM
Computer Science
The list can be nested into another to create a sub-list
Example:
<UL>
<LI> EXAM
</UL>
<LI type =”circle”> Comp. Sci.
<LI type =”circle”> PHY
<LI type =”square”> Practical of Physics
< LI type =”square”> Practical of C.S.
</UL>
</UL>
Display format will be
EXAM
Comp. Sci.
PHY
Practical of physics
Practical of C.S.
Ordered Lists
The ordered list is always proceeded by a arabic numbers, upper case or lower case characters, for ordered
list <OL> and </OL> tags are used.
Example :
<OL>
<LI> Mumbai
<LI> Pune
<LI> Sangli
<LI> Aurangabad
</OL>
The final appearance of the list is
84
1. Mumbai
2. Pune
3. Sangli
4. Aurangabad
The ordered list can have the following attributes
TYPE = “1” Arabic number
TYPE = “a” Lower alphanumeric
TYPE = “A” Upper case alphanumeric
TYPE = “i” Lower case Roman
TYPE = “I” Upper case Roman
START = “X” Beginning of the list from the starting.
Example : <OL START = “3”> This starts the ordered list beginning with number 3. This can also be done in <LI
VALUE = " ” > tag.
Example : <LI VALUE = “5”> KHS
This displays 5. KHS
There is provision of listing the paragraph and links of list images also.
Definition lists :
The <DL> and </DL> tags are used to create definition lists. There are no numbering and bullets. <DT> tag
is used to defining term and <DD> tag for defining themselves.
Example : <DL>
<DT> Term Z
<DD> Definition of term Z
<DT> Term Y
<DD> Definition of term Y
</DL>
This will display as
Term Z
Definition of term Z
Term Y
Definition of term Y
<A> tag : This tag is used to create links. Links points to the different file on the web. Text or image enclosed in
<A> and </A> tag is a link which is clickable in graphical browser.
Example : <A HREF = “http: // www.kirloskars.com”>
Home page of kirloskars </A>
<SUB> tag : This tag is used to get subscript. The text enclosed in <SUB> and </SUB> is displayed in subscript
form.
Example : Al<SUB>2 </SUB>O <SUB> 3 </SUB>
This displays data with Al2O3.
<SUP> tag : <SUP> tag is used for getting superscript. The text enclosed within <SUP> and </SUP> is displayed in
super script form.
Example : A<SUP>2 </SUP> + B<SUP>2</SUP>
This will display A2 + B2
<FONT> tag :
This tag is used to get different fonts and sizes as well as different font colors enclosed in the text. This tag
has three attributes – size, face and color. The color attribute is specified with an RGB value or by specifying color
85
name.
The size can be specified within range from 1 to 7. So by putting + or – sign before the number, will change the font
size.
Example : <FONT SIZE = “+6”>
This makes the font size 6 steps larger than the current size.
Different font sizes are as follows
<BIG>
<BIG> is big tag. The text enclosed <BIG> and </BIG> is displayed in larger font which has the same
meaning as < FONT SIZE = "+1”>
For example:
<BIG> India is seventh largest country in the world </BIG>
If size is already largest then tag is ignored.
<SMALL>
This is small tag. The text enclosed in <SMALL> and </SMALL> is displayed in smaller font. If the size is
already smallest then tag is ignored. <SMALL> tag has the same meaning as < FONT SIZE = "-
1”>
For example:
<SMALL> India is seventh largest country in the world </SMALL>
If size is already smallest then tag is ignored.
<STRIKE>
This is strike tag. The text enclosed in <STRIKE> and </STRIKE> draws the line through middle of the text.
Example : < STRIKE> This is hopeless situation </STRIKE>
This will display : This is hopeless situation
<MARQUEE>
This is marquee tag. The text enclosed in < MARQUEE> and </MARQUEE> is rolled over the horizontal
line on the web page.
Example : <MARQUEE> Kirloskar Jr. College </MARQUEE>
COLOR Schemes
There are six body attributes to which we can give the different colors.
They are : BGCOLOR, BACKGROUND, TEXT, LINK, VLINK and ALINK.
Colors in the HTML can be specified by a color name or by color code RGB which stands for RED, GREEN
and BLUE
India won the match ( size 1)
India won the match ( size 2)
India won the match ( size 3)
India won the match ( size 4)
India won the match ( size 5)
India won the match ( size 6)
India won the match ( size 7)
86
There are 16 color names in HTML : BLACK, SILVER, GRAY, WHITE, MAROON, RED, PURPLE,
PUCHSIA, GREEN, LINE, OLIVE, YELLOW, NAVY BLUE, TEAL and AQUA.
RGB color code is always represented in 6 numbers. First two numbers in hexadecimal specifies the amount
of red, next two specify the amount of green and last two numbers specify the amount of blue. By mixing different
amounts of three primary colors it is possible to generate any color.
For blue color RGB code is # 00 00 FF
For green RGB code is # 00 FF 00
For red color RGB code is # FF 00 00
For white color RGB code is # FF FF FF
For black color RGB code is # 00 00 00
Background color of document can be changed as
<BODY BACKGROUND =”LIME” TEXT=”WHITE”>
OR <BODY BACKGROUND =”#00 FF 00” TEXT=”# FF FF FF”>
We can use any image file as a background for a page.
<BODY BACKGROUND =”clouds.jpg”>
The BACKGROUND attribute overrides BGCOLOR attribute.
To make text bluish- green
<BODY TEXT=”TEAL”>
<BODY TEXT=”#00 8080”>
Default text color is black.
The link attributes specifies the color used for hypertext links.
For example : <BODY LINK = “ Green” >
The visited links can be set by VLINK
<BODY VLINK = “RED”>
<BODY VLINK = “#FF0000”>
The color of active links can be set by ALINK
<BODY ALINK = “GREEN”>
<BODY ALINK = “#00 FF 00”>
With <FONT> tag we can use COLOR attribute to set color of block of text.
<FONT COLOR = “ colorname”> or <FONT COLOR= “#RGB code”>
Example : <FONT COLOR = “ RED”> or <FONT COLOR= “#FF0000”>
Images
<IMG> Tag:
This is mage tag. Its purpose is to include graphic images in the body of the web page. The images are some
time referred to a inline Images because the images are inserted within the line of the body text. To make an image
appear as a separate paragraph, enclose it within paragraph element as
<P>
<IMG SRC= “srtpat\image.jpg”>
</P>
The two popular formats of the images on the browser are .JPG and .GIF.
IMAGE element attribute:
87
There are two image attributes that are always used with any <IMG> Tag: The SRC and ALT attributes. In
SRC we need to give appropriate path of image file for searching.
And for any browser that is not displaying images, the alternative text containing inside the ALT attribute is
displayed.
Example : < IMG SRC = “ clouds.jpg” ALT = “ clouds”>
If you use this tag the browser can display the word “clouds” instead of clouds
There are 5 reasons why a browser would use the alternate text instead of image itself.
1.The browser is text and can’t display images. In such case without ALT attribute, browser will display the word
“[INLINE]” on the screen instead of image. If alternate text is present, browser displays alternate text in place of
image.
2. The browser is programmer is allowed to read alternate text instead of displaying an image. The ALT attribute can
explain your image to blind surfaces.
3. The person using the browser has chosen not to display images. Since images are often large files that are slow to
display, many people surf with their browser set to not Auto Load Images or view pictures. Instead, browsers show
an empty frame as a place holder for the image, and the alternate text is displayed inside the frame.
4. Some browsers displays on images alternate test while image is being loaded.
5. Some browsers display the alternate text as a tool tip when ever you point your mouse cursor at the image for a
few seconds.
88
Placing Images with Alignments Attributes.
Image can be aligned with ALIGN attribute
1) Inline images occur in the middle of the line of text. If the image is large one, then the line becomes very
tall and a lot of white space will appear.
2) Floating images causes text to wrap around the image. Images can either be left aligned or right aligned.
ALIGN in line images
To align an image in a line , choose one of the following attribute
ALIGN = “TOP”
ALIGN = “MIDDLE”
ALIGN = “BOTTOM”
The default behaviour is ALIGN = “BOTTOM”, Which means that the bottom of an image will align with
the bottom of the line of the text. By choosing ALIGN = “TOP” you request that the browser display the top of your
image so that it aligns with the top of the line of text. This will push down the next line of the text. Similarly ALIGN
= “MIDDLE”
Creating Floating Images
To float image to the left or right side and cause paragraphs to wrap around the image, we can choose one of
the following two attribute values for the ALIGN attribute.
ALIGN = “LEFT”
ALIGN = “RIGHT”
Choosing LEFT and RIGHT as the value for ALIGN causes the images to be placed directly against the left
or right margin. Text after the <IMG> tag will flow around the image.
If your page has images on both the LEFT and right sides, use <BR CLEAR = “ALL”> to force the next line
of the text to appear below the lowest image.
WIDTH and HEIGHT attribute of image :
The above mentioned attributes denotes the size of the images.
Example
<IMG SRC = “image2.jpg” HEIGHT = “200” WIDTH = “150”
ALT= “Image of institution” >
This displays the image with 200 pixels height and 150 pixels width. By changing the height width ration
image can be stretched.
If the image is to be bordered then BORDER = “1” must be given. This displays very thin border around the image.
The border number can be changed in order to get the image border large in size
Example : BORDER = “4”
This displays the Larger border around the image. The thickness of the border changes according to the
increase in number.
IMAGE as LINK
The images can be used as hyper links
Example :
<A HREF = “http:// www. srk.org>
< IMG SRC = “image.jpg” ALT “ natural scene” > </A>
89
Here image JPG is used for link.
Image format :
JPEG ( Joint Photographic Group ) It has compact format designed for photograph. It has more than 16 million
colors in images.
PNG ( Portable Network Graphic). It is superior to GIF. They are smaller and have more colors. The images can be
created by using photoshop softwares.
GIF ( Graphic Interchange format) . It is most widely used on web design. It is good for line drawing, icons,
computer generator images, and cortoons. It has 256 colors.
TABLE
The data must be organized into table structure in HTML. The data in tables has rows and columns which
has the advantage that reading the data is very easy. To create table <TABLE> tag is used and to end the table
</TABLE> tag is used at the end. The table can have the following formatting attributes.
Alignment of entire table [ALIGN]
Width of the table [WIDTH]
Cell borders and border widths [BORDER]
Spacing between the cells [CELL SPACING]
Padding with cell [CELL PADDING]
1) WIDTH : <WIDTH> tag specifies width of the table.
<TABLE WIDTH = “50%”>
<TABLE WIDTH = “20”> This has fixed pixel value.
2) BORDER : The <BORDER> tag is used to get or change the size of the border.
<TABLE BORDER = “3>
If no border is required then <TABLE BORDER = “0”> is used.
ALIGN : Alignment of the table can be done with this tag.
<TABLE ALIGN = “RIGHT”>
<TABLE ALIGN = “LEFT”>
<TABLE ALIGN = “CENTER”>
CELL SPACING : This creates more space between each cell in table.
<TABLE CELL SPACING = “40”> This sets the cell spacing of 40 pixels.
To increase the space between cell border and the cell data cell padding is used.
<TABLE CELL PADDING = “ 1”>
Many attributes can be used together in table.
< CAPTION > tag :
<CAPTION> tag is used to create caption on top of or below the table. It requires <CAPTION> start tags
and </CAPTION> as end tag. This can be used with align attribute.
<CAPTION ALIGN = “ MIDDLE”> </CAPTION>
The caption is located outside the table.
<TR>, <TH> and <TD> tags
<TR> tag : <TR> tag is table row opening tag and </TR> is closing tag. It created horizontal row of cells and
contains table heading and table data. Each use of table row element begins a new table row.
This <TR> tag uses several attributes : ALIGN, VALIGN, BGCOLOR. A row must contain at least one table data
90
element or table heading.
<TD> tag : <TD> tag is used to get the table data in individual cell. The number of cells in a row determines the
number of columns. </TD> is table data closing tag.
<TH> tag : <TH> tag is used for opening of table heading and </TH> is used for closing the heading. The above
<TH>, <TR> and <TD> tags can have align attribute.
ALIGN = “RIGHT”
ALIGN = “LEFT”
ALIGN = “CENTER”
The default align is left.
The vertical align is specified by
VALIGN = “TOP”
VALIGN = “BOTTOM”
VALINE = “BASELINE”
VALIGN = “CENTER”
The default align is MIDDLE.
The table can have colors with BGCOLOR
<TR BGCOLOR = “RED or FF0000”>
<TH BGCOLOR = “RED or FF0000”>
<TD BGCOLOR = “RED or FF0000”>
The width of the cell can be specified by
<TD WIDTH = “100”>
<TH WIDTH = “25”>
COLSPAN and ROWSPAN
To merge cell contents with another cell COLSPAN is used.
<TD COLSPAN = “3”>
<TH COLSPAN = “4”> This spans 4 columns.
The ROWSPAN specifies how many a rows a cell should be taken.
<TH ROW SPAN = “4”>
<TD ROW SPAN = “4”>
SCRIPTING OF LANGUAGE
SCRIPT : Script is embedded application. Scripts are simple programs embedded in HTML pages as ASCII
text. When the page is down loaded the script is downloaded with it and it is executed by the browser on the client
computer.
The web is client / server environment. The server stores the information, client processes it but by using
VB script one can add small programs to pages that can be executed by the server.
<SCRIPT> tag:
The Vbscript can be placed in <SCRIPT> start tag and </SCRIPT> end tag. One can have the attribute of
language = “VB script”
<SCRIPT LANGUAGE = “VB script”>
code
</SCRIPT>
When browser gets <SCRIPT> tag it calls the interpreter to compile and execute the code.
91
Write a simple HTML program for VB script demo program.
HTML code
<HTML>
<HEAD><TITLE> VB script Program” </TITLE></HEAD>
<BODY> <SCRIPT Language = “VB script”>
document bgcolor = “BLUE”
MSG box “well come to VB script”
</SCRIPT> </HEAD>
<BODY>
<H2> VB script program </H2>
</BODY>
</HTML>
The various properties of the documents can be observed through the document object.
Program 1
Write HTML program to display Time using VB script.
HTML code
<HTML>
<HEAD><TITLE> Local Place Time </TITLE></HEAD>
<Body>
<H4> The Local Place Time is ---- </H4>
The Local time is now
<SCRIPT Language =”VBscript”>
Document Write Time () & “on” & -
</SCRIPT >
</BODY>
</HTML>
Program 2
Write HTML code with VB script for a web page which denote day if time is between 6 AM to 6 PM else denote
Night.
HTML code
<HTML>
<HEAD>
<TITLE> Denote Day or Night </TITLE> </HEAD>
<BODY>
<SCRIPT Language = “VB script”>
function denoting day or night ()
if time () > 06:00:00 AM # and Time ()-
< # 06:00:00 PM # Then –
denote = “day”-
Else
Denote = “night”
End if
End function
Document write denote ()
</SCRIPT>
</BODY>
</HTML>
Program 3
Create a web page to display personal information such as name address, phone number, date of birth,
Education qualification etc.
HTML Code
<HTML>
<HEAD>
<TITLE> Personal Information </TITLE>
</HEAD>
<BODY>
<H3 ALIGH = “CENTER”> Personal Information </H3>
92
<HR>
Name <B> S. R. Kale</B> <BR>
Address <BR> 18o, Kirloskar Colony <BR>
Kirloskarwadi, <BR> Tal - Palus <BR>Sangli pin 416415. <BR>
<I> TEL. (02346) 222339 </I>
Birth Date : 27 : 12 : 1972
Qualification : M.Sc. Ph. D. <HR>
<CENTER> Visit to <A HREF “htpp:// www. Rediffmail .com>
</BODY>
</HTML>
Program 4
Create a web page of industry containing information , Name, address, production of item.
HTML code
<HTML>
<HEAD>
<TITLE> Industry information </TITLE>
</HEAD>
<BODY>
<H4 ALIGN = “CENTER” > KIRLOSKAR BROTHERS LIMITED </H4>
<H5 ALIGN = “CENTER”> Address : A/P – Kirloskarwadi <BR>
Tal : Palus <BR> Dist : Sangli <BR> Pin : 416308 <BR>
</H5>
<H1> ALIGH = “CENTER”> Production items : PUMPS and Engines. </H1>
</BODY> </HTML>
Program 5
Write HTML Code to create a web page for gathering invitation by making use of various colors.
HTML code
<HTML>
<HEAD>
<TITLE> Gathering Invitation </TITLE>
</HEAD>
<BODY BGCOLOR =”PINK” TEXT = “ BLUE” LINK = “GREEN”
ALINK = “MAROON” VLINK = “YELLOW” >
<H2> The Gathering Day Invitation </H2>
<FONT SIZE = “+10” FACE = “New Times Roman”>
<I> <B> You are invited for gathering </B> </I>
</FONT>
<P> <B> FONT COLOR = “RED”>
Please come for gathering </B>
To see my dance. You can also call you friends and for passes use the link below.
</P>
< FONT COLOR = “BLACK” SIZE “5”>
<A HREF = “ Mail to : srkumbhar@rediffmail .com”>
<HR>
</BODY>
</HTML>
Program 6
Write HTML code for creation of web page of your college with image of laboratory.
HTML code
<HTML>
<HEAD>
<TITLE> Kirloskar Jr. College </TITLE>
</HEAD>
<BODY>
<H2> Well come to Kirloskar Jr. College KHS is established in 1937and only English medium school in Sangli
District At that time </H2>
<I> <B> 100% result since last 5 years </B> </I>
For more details write at <BR>
KHS and Jr. College Kirloskarwadi <BR> Tal : Palus <BR>
Dist : Sangli
<IMG SRC = “images \ school building . jpg”>
93
<HR>
Visit
<A HREF = “http // www. Kirloskars.com”>
</BODY></HTML>
Program 7
Write a program for a web page displaying following table
Food grains in India
Year RICE WHEAT PULSES
1950 150 550 1500
1980 175 800 2215
1990 125 100 1000
HTML code
<HTML>
<HEAD>
<TITLE> FOOD PRODUCTS </TITLE> </HEAD>
<BODY>
<CAPTION> Food grain production in India </CAPTION>
<TABLE>
<TR>
<TH> Year </TH>
<TH> RICE </TH>
<TH> WHEAT</TH>
<TH> PULSES </TH>
</TR>
<TR>
<TD> 1980 </TD>
<TD> 175 </TD>
<TD> 800 </TD>
<TD> 2215 </TD>
</TR>
<TR>
<TD> 1990 </TD>
<TD> 125 </TD>
<TD> 100 </TD>
<TD> 1000 </TD>
</TR>
</BODY>
</TABLE>
</HTML>
Program 8
Write a program displaying six cell table
HTML code
<HTML>
<HEAD>
<TITLE> Celled table </TITLE>
</HEAD>
<BODY>
<TABLE BORDER = “4” CELL SPACING = “8”>
<TR>
<TH> PHYSICS </TD>
<TH> CHEMISTRY </TD>
<TH> COM. SCI. </TD>
</TR>
<TR>
<TD> 99 </TD>
<TD> 96 </TD>
<TD> 196 </TD>
</TR>
</TABLE> </BODY> </HTML>
94
Program 9
Write a program to display the following table
Students
XI XII
49 62
HTML code
<HTML>
<HEAD>
<TITLE> STRENGTH OF STUDENTS </TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
<TH ROWSPAN = “2” > STUDENTS </TD>
</TR>
<TR>
<TD> <B>XI <B></TD>
<TD><B> XII </B> </TD>
</TR>
<TR>
<TD> <B>49 </B> </TD>
<TD> <B>62 </B></TD>
</TR>
</TABLE>
</BODY>
</HTML>
Exercise :
1) What is long form of HTML?
2) What are the advantages of HTML?
3) What are the disadvantages of HTML?
4) What is tag? What is attribute?
5) Which tags are essential for web page design.
6) Why HTML is necessary?
7) Explain the following tags with example.
a) HTML b) HEAD c) TITLE d) BODY e) P f) BR
8) What are the different attributes of <P> tag and <BR> tag ?
9) What is the use of <HR. tag ?
10) Hat are different levels of heading?
11) What is the function of <B> <I> <U> tags ?
12) What is the function of list tag ?
13) What are the various attributes of list tag? Explain with suitable example.
14) Explain the use of link tag.
15) Explain the function of following tags.
1) <SUP> 2) < SUB > 3) <STRIKE>
16) What is the function of <BIG> and <SMALL> tag ? Explain with suitable example.
17) Explain the use of FONT tag with various attributes.
18) Write a HTML code to display the college / company profile.
19) Write a HTML code along with VB script for web page which displays a new six digit number every time when
the page is visited.
20) Write a HTML code for gathering invitation in your college.
21) Write a HTML code for birth day invitation stating various colours and attributes.
22) Write a HTML code to represent your mark list on the web page.
23) HREF is -------.
95
a) Hyper Text Reference b) Hyper Text Mark-up Language
c) Hyper reference d) None
24) ------- is RGB code for red color.
a) # F00FF0 b) # FF00F0 c) # 0000FF d) # FF0000
25) ------- is not a HTML tag.
a) < MARQUEE > b) < B > c) < TM > d ) < TM >
26) PNG stands for -----
a) Portable Network Graphic b) Pure Network Graphic
c) Pictorial Network Graphic d) Protected Network Graphic
27) ------ is not a attribute of image tag.
a) Align =”Left” b) Align =”Justify” c) Width d) Height
28) To merge columns ---- attribute is used.
a) ROWSPAN b) COLSPAN c) MERGE COLUMN d) MERGE ROW
29) ------- Tag is used to get italic tag.
a) <B> b) <I> c) <PRE> d) <STRIKE>
35) Write output following HTML Code
<html>
<body>
<h1> LIST OF BOOKS </h1> <hr>
<ul type="circle">
<li> How to solve by computer
<li> HTML in Easy Steps
<li> c++ Programming
</ul>
<ol type="A">
<li>Microprocessor Programming
<li> Networking Essentials
<li> Microcontrollers
</ol>
</body>
</HTML>
37) Give the output of the following HTML code.
<html><head><title>information</title></head>
<body >
<caption><align="center"> <b><i> <u>information of chemical salt </u></i></b>
</caption>
<table border="4">
<tr><th>types of salt</th>
<th>name of salt</th></tr>
<tr><td>salt of weak acid weak base</td>
<td>H<SUB>2</SUB>SO<SUB>4</SUB></td></tr>
<tr><td>salt of strong acid strong base</td>
<td>NH<SUB>4</SUB>Cl</td></tr>
<tr><td>salt of weak acid strong base</td>
<td> <font color="red"> HCl</td></tr>
<tr><td>salt of strong acid weak base</td>
<td>NaOH</td></tr>
</body> </html>
38)Write the output of the following code.
<HTML> <HEAD> <TITLE> Medal tally table</TITLE> </HEAD>
<BODY>
<CAPTION> <H1> OLYMPIC MEDAL TALLEY </H1> </CAPTION>
<TABLE BORDER =”2”>
<TR>
96
<TH> COUNTRY </TH>
<TH> GOLD </TH>
<TH> SILVER </TH>
<TH> BRONZE </TH>
<TH> TOTAL </TH>
</TR>
<TR>
<TD> <B>USA </B></TD>
<TD> 91 </TD> <TD> 50 </TD>
<TD> 25 </TD> <TD> 166 </TD>
</TR>
<TR>
<TD><B> GERMANY</B> </TD>
<TD> 33 </TD> <TD> 14 </TD> <TD> 10 </TD>
<TD> 57 </TD>
</TR>
<TR>
<TD><B> INDIA </B></TD>
<TD> 01 </TD> <TD> 2 </TD>
<TD> 4 </TD> <TD> 7 </TD>
</TR>
</TABLE> </BODY> </HTML>
30) VB Script can be executed in ------ web browser. ( M-2004)
a) Netscape Navigator b) Internet Explorer c) Both d) None
31) Explain the following HTML tags.(M-2004)
a) <PRE) b) <SUP> c) <MARQUEE>
32) Write the HTML code for the following table. (M-2004)
Year
1999 2000 2001
Sales Units 300 750 1,200
Income Rs.3,000 Rs. 7,500 Rs. 12,000
Write HTML code using VB Script for designing of Web Page which greets “Good Morning” If time is from 12:00
AM upto 12:00PM, else greets “Good Afternoon”. (M-2004).
Top Related