0% found this document useful (0 votes)
21 views89 pages

Syjc-Cs-1 Notes

The document provides an overview of operating systems, detailing their role as an interface between users and hardware, and outlining their major components such as the storage manager, process manager, and file system. It discusses various types of operating systems, including single program, multiprogramming, time-sharing, real-time, and multiprocessing OS, along with their functions and services. Additionally, it covers memory management techniques like contiguous and non-contiguous storage allocation, and introduces the concept of graphical user interfaces (GUIs) for user interaction.

Uploaded by

Jash Mehta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views89 pages

Syjc-Cs-1 Notes

The document provides an overview of operating systems, detailing their role as an interface between users and hardware, and outlining their major components such as the storage manager, process manager, and file system. It discusses various types of operating systems, including single program, multiprogramming, time-sharing, real-time, and multiprocessing OS, along with their functions and services. Additionally, it covers memory management techniques like contiguous and non-contiguous storage allocation, and introduces the concept of graphical user interfaces (GUIs) for user interaction.

Uploaded by

Jash Mehta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

NIRMALA MEMORIAL FOUNDATION JUNIOR

COLLEGE OF COMMERCE & SCIENCE

COMPUTER SCIENCE (SOFTWARE- D93)

SYJC

CS-1 NOTES

2022-23
CHP-1. OPERATING SYSTEM

The requirements are changing day-by-day. Thus, hardware is becoming more and more
powerful and is able to perform complex functions. Hardware is nothing but finely designed machinery.
An operating system is a program, which acts as an interface between a user and the hardware
(i.e. all computer resources).
E.g.: it is just like our secretary. As the boss gives orders to his secretary and she does all the work for his
boss. The secretary herself decides: How to do? What to do? When to do? etc. same way, we pass our
orders/request to OS thus to make the computer system convenient to use and secondary goal is use
computer hardware in an efficient manner.

Q. What is an operating system?


Ans. An operating system is a control program. A control program is responsible for the execution of the
programs in an efficient and proper way so as to prevent errors and improper use of the computer;
especially concerned with the operation and control of the I/O devices. It controls and
coordinates the use of the hardware among the various application programs for the various users.
An o. s. is an important component of a computer system, which controls all other component of the
computer system. Major components of a computer system are:
1) The hardware
2) The operating system
3) The application program routine (complier, linkers, database, management systems)
4) The human ware (users).

Device Driver:-
Each I/O device has its own characteristics requiring careful programming. A special program
routinewas written for each I/O device. This special routine was called ‘device driver’.
Note: A device driver is a program, which controls and monitors the working of a particular I/O
device.
E.g. our keyboard will have a separate device driver and mouse will have a separate device driver.

The compliers for COBOL, FORTAN and other languages appeared but made the computer
operationscomplex. The program execution consisted of many steps: loading the complier tape,
running the complier, unloading the complier, unloading the complier tape, etc If an error
occurred, the entire
process has to be repeated.
Note: The time spent in loading, unloading, mounting etc. is called setup time.

Q. What are the different Components of OS?


Ans. An operating system is a program, which acts as an interface between a user and the hardware.
The major components of OS are as follows:
(i) The Storage Manager:-
It controls the utilization of the main storage by different user programs. It protects the program
area in main storage from illegal access i.e. it checks the authority of the user to access the data. It
translates the data from HLL to MLL. It terminates a user program if sufficient storage is not
available for the program. The storage manager keeps the track of the deallocation storage and
provides its reuse by other programs.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 1


(ii) The Process Manager:-
The process manager (or processor manager) is responsible for effective utilization of the processor. It
keeps the track of each program’s (a) process state and (b) priority associated. Then by making use of
one of the job scheduling technique, it allocates the CPU to the highest priority program. It interacts
with other OS components in order to carry out the various operations.

(iii) File System:-


It provides information management support to OS as well as to a program. It manages allocation of
space for a file on a secondary storage device, when a program demands for it. It also takes care of
file protection against illegal access. It is also responsible for grouping of files under directories and
manages them.

(iv) Input Output Control System:-


Actual input and output for the file data is performed through this very component, IOCS.
Logical IOCS Provides the access method and data organization for the data stored in files.
Physical IOCS is responsible for carrying out devices level I/O operations to implement data transfer.
It also optimizes devices performance by scheduling jobs waiting for the device.

Some other components of OS are:


The console manager is responsible for changing the operating mode from supervisor (monitor) mode
to user mode or vice versa.
Log on-Log off Manager checks user’s authorization like a password or account number.

Q. What are the types of OS?


Ans. There are different types of OS available, which requires different types of hardware to run upon.
The OS are of mainly following types:
(i) Single Program OS:-As the name suggests, this OS is single user operating system, so only one
user program can be supported and executed at a time. Example:- DOS
(ii) Multiprogramming OS:-This is a multi-user OS. It supports multi-programming i.e. more than
one user can be supported by it, therefore, more than one user program are loaded and active in the
main storage at the same time.

(iii) Timesharing OS:- This OS uses the time-sharing technique. Each active user program is given
a fair share of CPU time ( δ ), if the time elapses or an I/O operation is requested, CPU shifts over to
the next job waiting and the previous job is put to wait (if the time is over).
Note: The delay between job submission and job completion is called turnaround time.
A turnaround time does not improve the system utilization as multiprogramming does.
(iv) Real time OS:-
In real time OS, the jobs have fixed deadlines and the jobs have to be completed within their
deadlines. The system performance is measured by its ability to complete the jobs within their
specified deadlines. If a job cannot be completed within its deadline, this situation is called deadline
overrun.
(v) Multiprocessing OS:- The multiprocessing OS is capable of handling more than one processor,
as the jobs have to be executed on more than one processor. The multiprocessing OS should be
capable of load sharing in case of identical processors so that the system’s efficiency improves.
Nirmala Memorial Foundation Junior College of Commerce and Science Page 2
FUNCTIONS OF OS
The environment required for the execution of the program is provided by the operating system. The
environment provided is responsible for effective and efficient execution of the program which
depends upon the service provided by the OS.
 Types of Services
(i) Program execution
(ii) Handling I/O operations
(iii) Manipulation of file system
(iv) Error detection and Handling
(v) Resource allocation
(vi) Accounting
(vii) Information and Resource Protection

Major OS functions are as follows:-


1) Processor Management
2) Storage (Memory) Management
3) Information Management

1. Processor Management : Multiprogramming improves the overall efficiency of the computer


system by more CPU utilization. While CPU is executing a job, it has to wait for the job; if the job
requires certain I/O operation, the CPU waits for the I/O operation to get over and that wait time is
CPU’s idle time. So another job takes and over utilizes CPU’s idle time.
The benefits of multiprogramming are as follows:
i) Increased CPU utilization
ii) Higher total job throughput
Note: Throughput is the amount of work accomplished in a given time interval.
It is calculated as:

Thenumber of jobs completed


Throughput =
total timetakentocompletethe jobs
2 jobs
Throughput = = 1 job/minute
2 min
Note: When two or more tasks are simultaneously in progress (e.g. CPU working as well as the I/O
operation) it is referred to as multitasking.

2. Storage Management : Memory is a large array of word or bytes, each with its own address. The
CPU reads from and writes to specific memory address.

CPU Memory I/O System

Memory plays a central role in Computer System

Nirmala Memorial Foundation Junior College of Commerce and Science Page 3


A program must be assigned some memory area and loaded into memory in order to be executed.
As the program executes, it access program instructions and data from memory by generating
addresses of the allocated memory. When the program terminates, its memory space is declared
free, and the next program is given the same memory area. There can be many user program loaded
in the memory along with the system programs and OS. How the memory is managed? is given
below.

1. Contiguous Storage Allocation : Each program to be executed is allocated a contiguous


storage memory. At every job step initiation, the OS has to ensure that sufficient contiguous area
is available to accommodate it.
There are three techniques used for multiprogrammed storage management in contiguous
storage allocation system.

(i) Fixed Partition Allocation:-


 In this technique, the main storage is spilt into different storage areas called Partitions.
 The number and sizes of partitions are fixed, thus degree of multiprogramming is also fixed.
 The number and sizes of partitions can be changed only when no programs are executing in
the affected partitions.
 Example: When 3 programs are executing together. If P1 has the size 40k, P2 has 35K and
P3 has 60K; then the size must be>=60K and number of partitions should be atleast 3.

P1

P2

P3

 As the entire partition is allocated to one job, two parts 20K, 25K of the two partitions is
wasted, as the program needs only 40K and 35K. This wastage of space is called internal
fragmentation.
 Drawback: One is internal fragmentation. Second is, external fragmentation, during a
program execution, after the program has been assigned a partition a if its complied
version (pgm after compilation) is too large to fit in the partition.

(ii) Variable partitioned Allocation:-


 In this technique, the partition sizes and boundaries are not fixed.
 Each job is allocated a partition size according to its requirements.
 When a job finishes, the system keeps track of the released storage.
 For a new job, a partition is created to suit its requirements.
 This technique overcomes internal fragmentation, though external fragmentation would still

Nirmala Memorial Foundation Junior College of Commerce and Science Page 4


persist because of the holds that are too small to be used for job initiations.

(iii) Roll in/Roll out:-


 The above techniques allow the activation of a new program only after current program
terminates.
 When a High Priority Program (HPP) arrives for the execution and it requires 120K. Two
programs P1 and P2 are running with 100K (60K+40K) of memory occupied.
 So, the current running programs are sent to backing store and the freed memory is given to
HPP.
 After HPP finishes, memory is released and P1 and P2 are bought back to resume their
execution.
 This scheme is called rolling out/ rolling in or swapping.
 P1 = 60K, P2 = 40K, HPP = 120K

P1 and P2 making rooms for HPP

HPP releasing memory and P1 and P2 reloaded.

2. Non contiguous storage allocation


(i) Paging
1. Partitions suffer from external fragmentation because of available memory is not contiguous.
2. Paging permits a program’s memory to be non-contiguous allowing a program to be allocated
physical memory wherever it is available.
3. Physical memory is broken into fixed- size blocks called Page Frames. Logical memory is also
broken into blocks of the same size called Pages.
4. When a program is to be executed its pages are loaded into any available frames and the page map
tables defined to translate from user pages to memory frames.
5. The page size is defined by hardware. It is typically power of 2. The paging model of memory is
shown as follows:
Nirmala Memorial Foundation Junior College of Commerce and Science Page 5
6. Every address generated by CPU is divided in two parts:- a page number (p) and a page offset/
displacement (d). The page number is used as an index into a PMT.

(ii) Segmentation
1. Segmentation are logical divisions of programs and hence are normally of variable sizes.
2. Segmentation is a memory management scheme which support user’s view of memory.
3. Each segment has number and length.
4. Each program in executable form can be considered to be consisting of different segments such as
code, data and stack. Each of these can be further divided into new segments.
5. A program normally contains main program, some subprograms and few predefined and precompiled
functions. Each of these belongs to different segments.
6. An application programmer does not necessarily have to declare different segments in the program. If
various segments in his programs does not define explicitly, then the compiler does it by its own.
Following are the jobs of compiler:
(a) Recognize different segments in program.
(b) Number those segments.
(c) Define segment table.
(d) Produce an executable image by assigning two dimensional addresses.
7. Consider the examples an shown in figure Four segments numbered 0 to 3. The SMT (Segment Map
Table) has separate entry for each segment giving the size and base of segment.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 6


3. Information Management
A computer system works on ‘information’. It stores information, processes information, provides
information etc. Thus managing this information is very important and necessary tasks performed by
OS. To support this functions, OS’s have one component called ‘Information management’. This
information management component is structured as follows:

File System
Logical IOCS
Physical IOCS
Computer Hardware
Hierarchy of Information Management Modules.

1. Physical IOCS (Input-Output Control System) is responsible for device management for ensuring
device independence ( through drivers).
2. Logical IOCS is responsible for efficient organization and access of data on I/O devices. It
provides basic capabilities for file definition, choice of data organization and access method.
3. File System is responsible for protection and controlled sharing of files.

Q. What is Terminal I/O?


Ans. A terminal or Visual Display Unit (VDU) is an extremely common I/O medium. It would be hard to
find any programmer or user who has not seen and used a terminal. Example: Monitor.

TERMINAL HARDWARE: Terminal hardware can be divided into two parts: the keyboard, which
is an input medium and the video screen, which is an output medium.
The terminal can be dumb terminal or intelligent terminal.
 The dumb terminal has a microprocessor in it on which we can run rudimentary software.
 It has very limited memory.
 The dumb terminal is responsible for the basic input and output of characters.
 Even then, it is called ‘dumb’ because it does no processing on the input characters.
Example : normal monitor.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 7


 As against this, the intelligent terminal can also carry out some processing (e.g. validation) on
the input.
 This requires a more powerful hardware and software for it. Example: ATM machines.

THE GRAPHICAL USER INTERFACE (GUI) SYSTEM

Q. What is GUI ?Explain its features.


Ans. We see many pictorial signboards of parking instructions or a hospital in the vicinity. Software
developers borrowed this idea and decided to make the OS flexible, fast and user-friendly.
 The pictorial representations are called pictures rather than representations.
 The OS interact with the help of pictures rather than commands.
 Graphical User Interface (GUI) environment gives a flexible working environment to the user
for interacting with the hardware.
 The working of the software and hardware is completely transparent to the user in GUI
 It is fast and easy to use because entire system is picture based.
 It interacts through icons. Icons are pictorial representations of a program.
 The four characteristics of icons are:
 Visual : the appearance of the icon.
 Textual : the name below the icon.
 Operational: the program that is executed when the icon is activated.
 Positional: the location of the icon on the screen.
 It is multi- tasking. The multi-tasking facility of the GUI allows more than one program to be
loaded in the memory.
 For Example: MS- Windows is a GUI environment.
 The GUI environment allows easy communication of data between programs.
 The step-by-step procedure to complete a job is called wizard. In this, the user does not have
to remember a set of steps or commands to complete a job.

Q. What are the basic components of the GUI System?


Ans. The working of GUI environment is different from the character based operating system
environment. Some components of the GUI environment are described below:
1. Desktop:- The area on the screen, which displays various components of a GUI.
2. Windows:- Every group under a GUI OS has a number of icons. These are enclosed in a frame
called a window. Windows separate one group from the other. An icon can also represent a
program group. If more than one program is active or opened by a user, the number of windows
on the desktop will be equal to the number of programs running. Many programs open their
windows in their own window. This is called a child window.
3. Menu Bar:- There is a menu bar on the top of the display, which shows the various menu
options. The menu and menu bar are displayed on the top of the desktop.
4. Menu:- The most common way for the user to interact in the GUI environment is to use menu
options. Every GUI environment has at least one menu containing options or commands. Menus
hold a list of commands that are usually related in some way. Example: the window menu of

Nirmala Memorial Foundation Junior College of Commerce and Science Page 8


Window Explorer contains two groups of related commands indicated by a solid line drawn
between them.
5. Menu Options:- Menu options are displayed as a list when the user selects the menu. These
options are commands or utilities that the system provides. To execute a command, it has to be
selected from the menu.
The GUI environment has an additional input device called mouse. When any pictorial
representation is pointed at, one of the following three actions can follow:
 Click once, press the mouse button & release it. This click will only select the program item.
It will not activate it.
 Double click, press & release the mouse button twice, with a fairly short time between the
two clicks. This selects and activates the program item.
 Drag, press the mouse button and while continuing to hold it down you move the mouse.
The keyboard can also be used to activate the programs and select options.
6. Toggle:- Some commands are preceded by a check mark as ‘Save settings on exit’
7. Dialog Box:- They are the standard way to tell the program exactly how you want it to act. They
are used to choose options for the commands.
8. List Box:- If an item has many choices, it becomes difficult to show all these options on the
display. The list box contains more than one option, which can be traversed by the scroll bar.
9. Text Box:- If a choice is not provided amongst the pre-defined choices in list boxes, option
buttons, etc. then the choice has to be entered. The place to insert the option is called text box .
10. Radio button:- When only one item from the group ( generally a dialog box) is to be selected,
then these options are in the form of radio buttons. The radio buttons, which is selected by
default, is enclosed in a dotted circle.
11. Control Menu:- Every Window opened in an environment has a control menu, which has menu
options to maximize, minimize or size a window. It also has option to close the window.

 Some GUI Operating Systems


 Windows-NT
 Open Server UNIX operating system
 OS/2
 Novel operating system (NOS) version 4.1

 Some GUI Packages


 MS-Office
 Oracle Power Objects
 Power Builders
 FoxPro Under Windows (ver.2.6)

Nirmala Memorial Foundation Junior College of Commerce and Science Page 9


Security and Protection
Security is concerned with the ability of the OS to enforce control over the transportation of data in
and between the objects that the OS supports. In multi- user environment, security and protection
are very important because user programs should not interfere with one another.
During the execution, a user program access different objects like files, directories and printers.
Because many of these objects are shared, a proper security mechanism is very important. The lack
of security mechanisms can lead to disaster.

Q. What are the different Security Threats?


Ans. Sharing and protection are requirement of any modern computing. More sharing gives rise to more
possibility of security threats, thus requiring higher protection.
The major threats to security in any computing environment are as follows:
(i) Unauthorized use of service (Tapping)
(ii) Unauthorized disclosure of information (Disclosure)
(iii) Unauthorized alteration or deletion of information (Amendment)
(iv) Unauthorized fabrication of information (Fabrication)
(v) Denial of service to authorized users (Denial)

Q. Define “security” with respect to an operating system. Explain the different elements of
security?
Ans.
i) Security is concerned with the ability of the operating system to enforce control over the storage and
transportation of data in and between the objects that the OS supports.
ii) In multiuser operating systems, the concepts of security and protection are very important. User
programs should not interfere with one another or with the operating system.
iii) In general, secure systems are those, which control, through the use of specific security features,
access to information that only properly authorized individuals or processes operating on their behalf
will have access to read, write, create or delete.
iv) There are three main elements of security are:
Confidentiality: It ensures that information is not accessed in an unauthorized manner. It is
generally related to the ‘read’ operations.
Integrity: It ensures that the information is not amended or deleted by an unauthorized manner. It is
generally related to ‘write’ operations.
Availability: It ensures that information is available to the authorized users at right time.

Q. What are the different Computer Worms? How it is affected?


Ans. 1. A computer worm is a full program by itself.
2. It is written in such a way that it spreads to other computers over a network.
3. By doing this, it consumes the network resources to a very large extent.
4. It can bring, potentially, the entire network to a grinding halt.
Origin:-
1. The research scientists at the centre wanted to carry out large programs.
2. They design small programs (worms), which could buy themselves spread to other computers.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 10


3. This worm could execute on a machine if idle capacity was available on that machine; otherwise it
would continue to hunt for other machines ‘in search of idleness’, this was the original purpose.
Mode of operation:-
1. A computer worm does not harm any other program or data.
2. It just spreads, consuming large resources such as transmission capacity or disk storage.
3. It usually operates on a network.
4. Each node on a network maintains a list of all other nodes one the network.
5. It also contains a ‘mailing list’, which contains the name & address of the reachable machines on
the network.
6. The worm gets an access into this list & using this, sends a copy of it to all those addresses.
7. If a worm is more intelligent and less harmful, after reaching there it checks at a new node
whether it is copy already exists, if it does, it does not create another one.
8. If it is dumb, it copies itself to all die nodes on the mailing list regardless.
9. As a result of this large continues transfer over the network, a major portion of network resources
such as line capacity, disk capacity, network buffers, process tables are used up so that the network
speed can reduce substantially.

Safeguard against worms:-


There are two major safeguards against worms
1. Prevention its creation: This can be achieved by having very strong security &protection polices &
mechanisms.
2. Prevent its spreading: Introducing various checkpoints in the communication systems can prevent
it. You can disallow the transfer of executable files over a network.

Q. What is the Computer Virus? What are the different types of Computer virus?
Ans.
1. A computer virus is written with a clear intention of infecting other programs.
2. It differs from a worm, which is a complete program by itself.
3. On the other hand, the computer virus normally cannot and does not, operate independently.
4. Virus normally causes direct harm to the system.
5. It can corrupt the code as well as data whereas a worm only consumes system resources.
Types of virus:-
There are several types of viruses. They are:
1. Boot Sector Infectors -- Virus can get infected into the system memory if the machine is booted
with an infected floppy or hard disk.
2. Memory Resident Infectors – It load upon execution of an infected file. Subsequently whenever a
non-infected file is executed the virus infects it.
3. File Specific Infectors – Infection occurs when an infected file is executed. The virus then loads its
vital code into the memory.
4. Command Processor Infectors – A few viruses place their memory-resident code into allocated
to COMMAND.COM. They can cause system crash.
5. General Purpose Infectors -- It can infect exe file.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 11


Q. What are the different Infection Methods of computer virus?
Ans. There are five well-known methods by which a virus can infect other programs:
1. Append: - In this method, the virus code appends itself to the unaffected program.
2. Replace: - In this case, the viral code replaces the original executable program completely or
partially.
3. Insert: - In this case, the viral code is inserted in the body of an executable code to carry out some
funny or undesirable actions.
4. Delete: - In this case the viral code deletes some code from the executable program.
5. Redirect:- In this, the normal flow of a program is changed to execute some other code, which
could exist as an appended portion of an otherwise program. This mode is quite common.

Q. What is the Mode of Operation of computer virus?


Ans. A virus works in a number of ways. Normally, a developer of a virus has to be a very bright person
who knows the OS very well in order to break it. This person produces an interesting or useful program
such as good name or utility. However, this program has some viral code embedded in it.
Typically, it is developed under MS-DOS, as viruses are very popular on the PCs. This program is
published on the public bulletin board system or it is distributed to people free of charge.
Tempted by its contents and the price, the user acquires it and then starts using if after copying it onto
his machine. At this stage, the virus can be said to be in a “nascent” state.
Virus Detection: The virus detection program checks for the integrity of the binary files. The program
maintains a checksum, on each file or for better accuracy, on subsections of each file, in addition. At
regular frequency, and for better control before each execution, the detection program again calculates
this checksum and matches it with the one originally calculated and stored. A mismatch indicated some
tampering with the executable file.
Virus Removal: The virus removal program scans the disk files from the patterns of the known disk.
On detection, it removes them. However, if that virus has already damaged some other data, it would be
impossible to recover the old data.
Virus Prevention: One of the safest ways to prevent virus is to buy official, legal copies of software
from reliable stores or sources. One should be extremely careful about picking up free, unreliable or
illegal software. Frequent backups and running of monitoring programs also help in detection and thus
prevention of different viruses.

MS-WINDOWS, WINDOWS NT & LINUX


Q. What is MS-WINDOWS?
Ans.
1. MS- Windows supports all the GUI (Graphical User Interface) features but due to handicap of
MS- DOS it works very slowly.
2. Under MS-DOS or Windows only one application at a time can be executed on the processor.
3. MS-Windows allow many applications to start.
4. However, only one application can be executed that has the focus. All others are idle.
5. When the focus changes, the old application are stopped and the new one is restarted.
6. It takes much shorter time to switch from one application to another application.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 12


7. MS- Windows does cooperative multitasking unlike pre-emptive multitasking in a more powerful
OS.
8. This needs a lot of memory.
Drawbacks:-
1. Many applications are not written as per the requirements of MS-Windows.
2. To be able to write well with MS-Windows, MS-DOS calls should not be used by the application.

Q. What is the WINDOWS NT?


Ans. 1. Windows NT is a full- fledged operating system.
2. It does not need MS-DOS underneath.
3. It is also portable OS like UNIX.
4. Windows NT is a multi-user, multitasking and multithreading.
Multi-user:
1. Multiple applications can run at a time and be executed.
2. A MS-Window’s user is visible to multi-user as he can get his output fast.
Multi-tasking:
1. Windows NT’s multitasking is pre-emptive like UNIX.
2. The OS, giving a time slice to each task, schedules tasks and when its time is over, the next one is
started.
3. So, applications cannot tie up the CPU for a long time.
Multithreading:
1. This will differentiate Windows NT from MS-Windows.
2. A task can be subdivided into smaller units called threads.
3. Each thread has an independent flow of control within a task.
4. Different threads can be scheduled and executed independently.

Q. What are the different features of Windows NT?


Ans. 1. Virtual memory management:-
 When an OS is capable of multitasking and it supports multi-users, a virtual memory
management is very useful.
 It is very costly to provide physical memory in the computer, which spans the full address
spaces of all the processes executing at a given time.
 There is also a need for protecting applications from accessing areas outside their own, thus
causing security violations.
 So, Windows NT provides a full-featured virtual memory subsystem.
2. Symmetric Processing:-
 It will allow various tasks to be scheduled on any CPU in a multiprocessor system.
 To be able to process queries from many users for large database and files, the throughput of
a single processor will be a bottleneck.
 Through, symmetric processing hardware technology will improve.
3. Threads:-
Same as multi- threading
4. Pre-emptive multitasking:-
Same as multitasking

Nirmala Memorial Foundation Junior College of Commerce and Science Page 13


5. Built-in networking:-
 Workstations are used more & more to solve problems in a workgroup. There is a heavy
demand for interconnecting workstations on a network.
 Windows NT has these services built in; while in MS-DOS we have to install
NetWare for its networking needs.

LINUX
Q. What is Linux? Explain its components?
Ans. 1. Linux looks and feels like any other UNIX system, however, it is much younger than most UNIX
system.
2. Its development began in 1991, when a Finnish student, Linus Torvalds, wrote and christened a
small but self-contained kernel for the 80386 processor, the true 32-bit processor in Intel’s range of
PC-compatible CPUs.
3. Linux development revolved largely around the central operating system kernel- the core
privileged executive that manages all system resources and the interacts directly with the hardware.
4. The basic Linux system is a standard environment for applications and for user programming but
it does not enforce any standard means of managing the available functionality as a whole.
5. A Linux distribution includes all the standard components of the Linux system, plus a
administrative tools of simplify the initial installation and upgrading of Linux.
6. A modern distribution also includes tools for managing of file system, creation and management
of user accounts, networking administration & so on.

Components of Linux system


1. Kernel:
 It is responsible for maintaining all the important abstractions of the OS including such things
as a virtual memory and processes.
 It forms the core (Central part) of the Linux operating system.
 It provides all the functionally necessary to run the processes.
 It also provides system series to give protected access to hardware resources.
 The kernel implements all the features that are required to qualify as an OS.
 The kernel does not directly maintain the OS interface visible to running applications.
 Rather, applications make calls to the system libraries, which in turn call the operating system
services as necessary.
2. System libraries:
 It defines basic set of functions through which applications can interact with the kernel, and
which implement much of the OS functionality that does not need the full privileged of the
kernel code.
 The system libraries provide may types many types of functionality.
 They allow applications to make kernel system service requests.
 Making a system call involves transferring control from unprivileged user mode to privileged
kernel mode.
 The libraries take care of collecting together the system calls and arguments and, if necessary,
arranging those arguments in the special form.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 14


 For example, C language’s buffered file-handling functions are all implemented in the system
libraries. It also provides routines that so not corresponds to system calls such as sorting
algorithms, mathematical functions etc.
 All the functions that are necessary to support the running of UNIX applications are
implemented in the system libraries.
3. System Utilities:
 The system utilities are programs that perform individual, specialized management tasks.
 It includes programs such as those to configure network devices or to load kernel modules. It
also handles running server programs such as user login requests, incoming network
connections, and the printer requests.
 The UNIX user environment contains a large number of standard utilities to do simple
everyday tasks, such as listing directories, moving around and deleting files, or displaying the
contents of the file.

Q. Explain memory map of single user operating system.


Ans.
Free memory
Process
Command interpreter
Kernel

1. The Operating system like MS-DOS is single user O.S


2. The memory map of such operating systems consists of program to be executed i.e process,
free memory available, command interpreter and kernel.
3. The command interpreter of the single user operating system is invoked when the computer is
started.
4. The O.S load program to be executed in main memory and assigns as much memory as
possible to it. It then sets instruction pointer and executes the program.
5. If the program is terminated, then it is removed from memory.
6. The kernel of such O.S provides basic operating systems services, while the command interpreter
the commands.

Q. With reference to process management explain the terms:


1. External priority 2. Purchased priority
3. Internal priority 4. Time slice
Ans.:
1. External priority :
(a) An external priority is specified by the user externally generally at the time of initiating the
process.
(b) In many cases, the operating system allows user to change its priority externally even during
its execution.
(c) If the user does not specify any external priority at all, the operating system assumes a certain
priority, called the default priority. But when an urgent job needs to be done, the system manager
permits the process to be created with a higher priority.
2. Purchased priority:
(a) This priority is used in some data centre situations where each user pays for the time used.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 15


(b) Higher priority processes are charged at a higher rate to prevent each user from firing his job
at the highest priority. This is known as scheme of purchased priority.
(c) Operating system keeps track of the time used by each process and the priority at which it was
used.
3. Internal priority:
(a) The concept of internal priority is used by scheduling algorithms. They base their calculations
on the current state of the process e.g. each user, while firing a process, can be forced to specify
the expected time that the process is likely to take for completion.
(b) The operating system can then set internal priority, which is highest for the shortest job (SJF
i.e. shortest job first algorithm), so that at only a little extra cost to large job, many short jobs will
complete.
(c) This has two advantages: (a) if short jobs are finished faster, the number of processes
competing for C.P.U. will be decreased. (b) The number of satisfied users will increase.
(d) However if a stream of short jobs keeps coming on, an important large job may suffer from
indefinite postponement. To avoid this, set higher external priority to important large jobs.
4. Time slice:
(a) Each process is normally given certain time to run irrespective of its important. This is known
as Time slice.
(b) Time slice given to each process so that a process does not use the CPU indefinitely.

Q. Which are the three main areas in which the operating system divides its services? Give
examples
Ans.: The O.S. divides its services in the following three main areas:
1. Information Management (IM)
2. Process Management (PM)
3. Memory Management (MM)

1. Information Management (IM) :


Information Management provides facilities to store, retrieve, modify the information on various
devices. The services provided under IM are:
(a) Create files or directories.
(b) Open files or explore directories.
(c) Delete, copy or close files.
(d) Change working directory.
2. Process Management (PM):
The services provided under process management are directed to keep track of all running
Programs, called processes. In multiuser operating systems, number of users located at
Different programs at a time. In such case operating system keeps track of all processes. It
schedules them and dispatches them one after another.
3. Memory Management (MM) :
The services in memory management keep track the of all memory location. They determine
memory allocation policy and use various techniques and algorithms to achieve this.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 16


Q. What are the features of Windows NT? Or
Explain any four features of Windows NT operating system.
Ans. : The features of Windows NT are as listed below:
(a) Windows NT is multitasking, multiuser and multithreading operating system.
(b) A user will get faster response even though multiple applications are running.
(c) Windows NT supports virtual memory management system to allow multiprogramming.
(d) Symmetric multiprocessing in windows NT allows it to schedule various tasks on any C.P.U. in
a multiprocessor system.
(e) Windows NT is a 32- bit operating system.
(f) Windows NT uses New Technology File System(NTFS), which implements fault tolerance,
security and has support for very large files.

Q. What are the components of Linux system?


Ans.: The Linux is composed of three main bodies:
(a) Kernel: Kernel maintains all important abstractions of the operating system, such as processes
and virtual memory.
(b) System libraries: System libraries define a standard set of functions through which applications
can interest with the Kernel, and which implements much of the O.S. functionality.
(c) System Utilities: These are programs that perform individual, specialized management tasks.
Some system utilities may be invoked just once to initialize and configure some aspects of system.

Q. Explain the use of Video RAM. Explain data bytes and attribute bytes.
Ans.
i) The video RAM is basically the memory that the terminal hardware itself has.
ii) Anytime all characters stored in the video RAM are displayed on the screen by the video
controller using display electronics.
iii) All particular information (attributes) are stored in video RAM.
iv) Video RAM consists of 2000 data bytes (0 to 1999) preceded by 2000 corresponding attribute
bytes (0 to 1999) as shown in the figure.

Attribute byte 0 Data Byte Attribute byte Data Byte


0 1 1

Attribute Data Byte


byte 1999 1999

v) A typical alphanumeric screen can display 25 lines each consisting of 80 characters i.e.
25*80=2000 characters.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 17


vi) Data Byte : All 2000 characters are stores in video RAM. To display any specific character
on the screen at a specific position all ASCII or EBCDIC code for that character is to move in
video RAM.
vii) Attribute Byte : There is one attribute byte for each data byte. This byte tells the video
controller how the character is to be displayed. It specifies whether the corresponding data
character which is stored next to it in the video RAM is to be displayed bold, underlined,
blinking or in reverse etc.

Q. Explain the following terms in case of magnetic disk:


i) Tracks and Sectors ii) Seek Time
iii) Transmission time iv) Latency time/ Rotational delay
Ans.
i) Tracks and Sectors: Magnetic disk is made up of concentric circles called tracks. The number of
tracks varies depending on the disk type. A track is further divided into smaller areas called sectors.
A sector is a smallest unit of information which can be read from or written to the disk. Sector varies
from 32 bytes to 4096 bytes and track contains 4 to 32 sectors per track and from 75 to 500 tracks
per disk surface.
ii) Seek time: The time required for read/write heads to move to the correct track is called as seek
time.
iii) Transmission time: The time required for activate read/write head for appropriate surface and
read data is called as transmission time.
iv) Latency time/ Rotational delay: The time required for requested sector on track to rotate below
the head is called as latency time or rotational delay.

Q. Explain Running, Ready and Blocked process in process management. Discuss various process
states with examples. What is the difference between blocked and ready state
Ans. In order to manage switching between processes, the operating system defines three basic process
states, which are given below.
Running state: There is only one process, which is executed by C.P.U.at any given moment. This
process is called as running state.
In multiprocessor systems, with multiple C.P.Us, there are many running processes at a given
moment. The operating system keeps track of all of them.
Ready state: The process, which is not waiting for an external event such as an I/O operation, but
which is not running is said to be in ready state.
Actually, a process in ready state could have been running. But the fact that, there is only one CPU,
which is executing some other process, while this process, is waiting for CPU’s attention towards it.
Blocked state: When a process is waiting for an external event such as an I/O operation, the process
is said to be in blocked state.
The major difference between blocked and ready process is that a blocked process cannot be directly
scheduled even if CPU is free, whereas a ready process can be scheduled if the CPU is free.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 18


Q. Explain context switching at a process level in multiprogramming system with example.
Ans.
i) Multiprogramming is the concept of increasing utilization of CPU by always having something for
CPU to execute.
ii) In multiprogramming, CPU can execute two or more processes simultaneously. When process1
waits for an external event such as I/O operation, CPU executes process2 and vice versa.
iii) When CPU switches from one process to another the time required for switching is called as
context switching.

Run Run Idle Run Run


Process 1 Process 1 Process 1 Process 1
time

Context Switching
iv) Let A and B be the two processes ready for execution and requires CPU time for execution. Let
CPU time be given to process A, which is having some instruction depending on process B or on
some external event such as I/O operation. Then, it is the job of operating system to halt the
execution of process A and give CPU time for process B.
The lose in time in turning the attention of CPU from process A to process B is known as context
switching.

Q. Explain the following terms in case of process scheduling:


a) Turnaround time b) Waiting time
c) Terminal response time d) Event response time
Ans. Turnaround time: Turnaround time is the elapsed time between the time a program or a job is
submitted and the time when it is completed.
Waiting time: Waiting time is the time a job spends waiting in the queue of the newly admitted
processes for the operating system to allocate resources to it before commencing its execution.
Terminal response time: In the time-sharing system, Terminal response time is the time to respond
with an answer or result to a question and it depends on degree of multiprogramming, the efficiency
of hardware with OS and policy of OS to allocate resources.
Event response time: In the real-time system, event response time is the time to respond with an
event.

Q. State the various steps involved in the allocation of a partition in case of fixed partition
memory management.
Ans. When a process is to be allocated the following partition steps takes place:
i) The long term process scheduler of the PM decides which process to be brought in to the memory.
ii) It then finds out the size of the program to be loaded by consulting the IM portion of the OS. The
complier keeps the size of the program in the header of the executable file.
iii) Then makes a request to the partition allocation routine of the MM to allocate a free partition,
with the appropriate size.
The partition description table (PDT) is useful for this procedure.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 19


iv) With the help of the IM module it now loads the binary program in the allocated partition.
v) It then makes an entry of the partition ID in the PCB (process control block) before the PCB is
linked to the chain of ready processes by using the PM module of the operating system.
vi) The routine in the MM now redefines partition description table and marks the status of that
partition as allocated. (ALLC)
vii) The PM eventually schedules this process.
A PDT is shown below:
0K
P0 Partition
100K Partition ID Starting address Size Status
P1 Process A 0 0 100K FREE
400K 1 100K 300K ALLC
P2
Process B
2 400K 200K ALLC
600K
3 600K 300K FREE
P3 4 900K 100K ALLC

900K :
P4 Process C
1000K
Fixed partition

Q. Explain in brief the following programs of Ms-Windows :


(i) Program Manager (ii) File Manager (iii) Control Panel Ans.
MS-Windows environment provides following programs which play very important roles.
1) Program Manager :
(a) The Program Manager starts executing along with MS-Windows.
(b) This provides user interface to start and stop applications.
(c) It is used to organize various applications into different groups.
(d) It is also indicates how each group contents are controlled and displayed on the screen.
(e) It is also used to end the MS-Windows session.
2) File Manager :
(a) This helps organize user files and directories.
(b) This is used to traverse through the file system and change drives, to search, copy move,
create or delete files and directories.
(c) Applications can be started directly from the File Manager.
3) Control Panel :
(a) It can be used to choose or change the color schemes in the applications, select and display
the background of the screen, select border width and other border characteristics, cursor size
and shape etc.
(b) Fonts also managed by control panel.
(c) It is also used to configure printers and other ports on the PC.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 20


CHP-2. DATA STRUCTURES

Basic Terminology
 Data are simply value or set of values.
 A data item refers to a single unit of values.
 Data items that are divided into sub items are called “group items”; those that are not divided
are called “elementary items”. E.g.: name can be divided into sub items – first name,
middle name & last name but the P.F.F. number is treated as a single item.
 Collections of data are organized into a hierarchy of fields, records and files.
 An entity is something that has certain attributes or properties, which may be assigned values.
Example:
Attributes: Name Age Sex PFN
Values: Ruchi 21 F 1423
 Entities with similar attributes (e.g. all the employees in an organization) form an entity set.
 The term “information” is sometimes used for data with given attributes, or, in other words,
meaningful or process data.
 The way that data is organized into the hierarchy of fields, records & files reflects the relation between
attributes, entities and entity sets.
 That is, a field is elementary unit of information representing an attribute of an entity, a record is the
collection of field values of a given entity & a file is the collection of records of the entities in a given
entity set.

Q. What is Data Structure? What are its different types?


Ans. Data may be organized in many different ways; the logical or mathematical model of a particular
organization of data is called a data structure.
There are many types of data structure. They are as follows:
1) Arrays:
The simplest type of structure is a linear (or one dimensional) array. By a linear array, we simply
mean a list of finite number n of similar data element under same name. If we choose the name
‘A’ for the array, then the elements of ‘A’ are denoted by:
subscript notation -.............................A1, A2, ,An
or by the parenthesis notation......A[1], A[2], ........ ,A[n]
or by the bracket notation...............A(1), A(2), ........ ,A(n)
The number k in A[k] is called a subscript and A[k] is called a subscripted variable.
2) Linked List:
A linked list, or one-way list, is a linear collection of data elements, called nodes where the linear
order is given by means of pointers. That is, each node is divided into two parts: the first part
contains the information of the element, and the second part, called the link field or next pointer
field, contains the address of the next node in the list.
3) Record Structure:
A file may be maintained by means of one or more arrays or records, where one indicates both
the group items and the elementary items. It can also be described best by means of a tree

Nirmala Memorial Foundation Junior College of Commerce and Science Page 21


structure. For example, an employee personnel record may contain the following data items:
P.P.F. no, name, address, age and salary.
The record structure is presented as follows:
Employee

Name PFF no. Address Age Salary

FN MN LN City State Pin

Hierarchical representation Fig. (a)


Or
01. Employee
02. Name
03.FN
03. MN
03. LN
02. PFF No
02. Address
03. City
03. State
03. Pin
02. Age
02. Salary
Level no. representation (Fig a)
A linear array is a list of finite number “n” of homogenous data elements (data elements of same
data) such that:
a) The elements of array are referred respectively by an index set consisting of “n” consecutive
number.
b) The elements of array are stored respectively in successive memory locations.

Q. Explain One Dimensional Array. How it is represented in memory?


Ans. The number ‘n’ of elements is called the length or size of the array. The length or the number of
data elements of the arrays can be obtained from the index set by the formula.
Length = UB - LB + 1

where, UB is the length index called upper bound.


LB is the smallest index called lower bound.
 The following is an example of one dimensional array:-
Let DATA be a 6-element array of integers such that DATA [1]=200, DATA[2] = 201,
DATA[3]= 202, DATA[4] = 203, DATA[5] = 204, DATA[6] = 205
Simply writing as, DATA: 200,201,202,203,204,205
The array DATA can be pictured as

Nirmala Memorial Foundation Junior College of Commerce and Science Page 22


DATA DATA
200 0 0 1 2 3 4 5

201 1 200 201 202 203 204 205

202 2

203 3

204 4

205 5

Representation of linear arrays in memory:


Let “LA” be a linear array in the memory of computer. We know that the memory of the computer is
simply a sequence of addressed locations as pictured below

1000 1001 1002 1003 1004 1005

Loc (LA[k]) = address of the element LA[k] of the array LA. As previously noted the elements of LA
are stored in successive memory cells. Accordingly, the computer does not need to keep the track of the
address of every element of LA, but needs of keep tracks only of the address of the first elements of LA,
denoted by.
Base (LA) i.e., starting address of array
Using this address Base (LA), the computer calculates the address of any elements of LA by the
following formula:
LOC(LA[k]) = Base(LA)+w(k-lower bound)
where w is the number of words per memory cells for the array LA.

 TRAVERSING LINEAR ARRAYS: [Imp]


The following algorithm traverses a linear array LA. The simplicity of the algorithm comes from the
fact that LA is a linear structure. Other linear structures, such as linked lists, can also be easily
traversed. On the other hand, the traversal of nonlinear structure, such as trees and graphs, is
considerably more complicated.
Algo : (Traversing a linear Array) here LA is a linear array with lower bound LB and upper bound
UB. This algorithm traverses LA applying an operation PROCESS to each elements of LA.
1. Set K: = LB // Initialize counter
2. Repeat Steps 3 and 4 while K<UB
3. Apply PROCESS to LA[k]. // Visit element
4. Set K: = K+ 1. // Increase counter
[End of Step 2 loop]
5. Exit.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 23


We also state an alternative form of the algorithm, which uses a repeat-for loop instead of the
repeat-while loop.

Algo using ‘for’ loop:- (Traversing a Linear Array) this algorithm traverses a linear array LA
with lower bound LB and upper bound UB.
1. Repeat for K = LB to UB:
Apply PROCESS to LA[k]
[End of loop]
2. Exit.

 INSERTING AND DELETING element: [Imp]

Let A be a collection of data elements in the memory of the computer. “Inserting” refers to the
operation of adding one more element to the collection A, and “deleting” refers to the operation of
removing one of the elements from A. This section discusses inserting and deleting when A is a
linear array.

Inserting an elements at the “end” of the linear array can be easily done provide the memory
space allocated for the array is large enough to accommodate the additional element. On the other
hand, suppose we need to insert an element in the middle of the array. Then, on the average, half of
the elements must be moved downward to new locations to accommodate the new element and keep
the order of the other elements.

Similarly, deleting an element at the “end” of an array presents no difficulties, but deleting an
element somewhere in the middle of the array would require that each subsequent element be moved
one location upward in order to “fill up” the array.

Algorithm: (Inserting into a Linear Array)

INSERT(LA, N,K,ITEM)

Here LA is a linear array with N elements and K is a positive integer such that K N.
This algorithm inserts an elements ITEM into the Kth position in LA.
1. Set J = N //Initialize countes
2. Repeat Steps 3 and 4 while J =K.
3. Set LA // Move Jth element downward
[J+1]: = LA[J]
4. Set: =J-1. // Decrease counter
[End of step 2 loop.]
5. Set LA [k]: = ITEM. // Insert element
6. Set N: = N+1 // Reset N
7. Exit.

The following algorithm deletes the Kth element from a linear array LA and assigns it to a variable
ITEM.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 24


Algorithm:(Deleting from Linear Array)
DELETE (LA,N,K,ITEM)
Here LA is a linear array with N elements and K is a positive integer such that K<N. This algorithm
deletes the Kth elements from LA.
1. Set ITEM: = LA[K].
2. Repeat for J = K to N-1:
Set LA [J]:=LA[J+1] Move J+1st element upward
[End of loop.]
3. Set N:=N-1 Reset the number N of elements in LA
4. Exit.

Q. Explain bubble sort algorithm with the help of example.


Ans. Let A be a list of n numbers. Sorting A refers to the operation of rearranging the elements of A so
they are in increasing order. That is,
A[1]<A[2]<A[3]< ............ <A[N].

Example: 5,4,7,9,2,3; the sorted elements are 2,3,4,5,7,9

Bubble sort:

Suppose the list of numbers A[1], A[2], ............. A[N] is in memory. The bubble sort algorithmic
works as follows:
Step1: Compare A[1] and A[2] and arrange them in the desired order, so that A[1]<A[2]. Then
compare A[2] and A[3] & arrange them so that A[2]<A[3]. Then compare A[3] and A[4] and arrange
them so that A[3]<A[4]. Continue until we compare A[N-1] with A[N] and arrange them A[N-
1]<A[N].
Note: During step 1, the largest element is “bubbled up” to the nth position or “sinks” to the nth
position.
Step2: Repeat step 1 with one less comparison, that is, now we stop after we compare and
possible rearrange A[N-2] and A[N-1].

Step3: Repeat step 1 with two fewer comparisons, that is, we stop after we compare and possible
rearrange A[N-3] and A[N-2].
........................................................................................................................................................
.........................................................................................................................................................
Step N-1: Compare A[1] with A[2] and arrange them so that A[1]<A[2].

The process of sequentially traversing through all or part of a list is frequently called a “pass”
so each of the above step is called a pass.

Example:
Suppose the following numbers are stored in an array A
32,51,27,85,66,23,13,57
Now, we will apply bubble sort to the array

Nirmala Memorial Foundation Junior College of Commerce and Science Page 25


Pass1:
(a) Compare A1 and A2. Since 32<51, the list is not altered.
(b) Compare A2 and A3. Since 51>27, interchange the nos.
32,27, 51,85,66,23,13,57
(c) Compare A3 and A4. Since 51<85, the list is not altered.
(d) Compare A4 and A5. Since 85>66, interchange the nos.
32,27, 51,66,85,23,13,57
(e) Compare A5 and A6. Since 85>23, interchange the nos.
32,27, 51,66,23,85,13,57
(f) Compare A6 and A7. Since 85>13, interchange th nos.
32,27, 51,66,23,13,85,57
(g) Compare A7 and A8. Since 85>57, interchange the nos.
32,27, 51,66,23,13,57,85
At the end of pass 1, the largest number 85, has moved to the last position. However the rest of the
numbers are not sorted, even though some of them has changed their positions.
Pass2: 27,33, 51,63,23,13,57,85

27,33, 51,23,66,13,57,85

27,33, 51,23,13,66,57,85

27,33,51,23,13,57,66,85

At the end of pass 2, the second largest number, 66, has moved to its way down next to the last
position.

Pass3: 27,33,23,51,13,57,66,85
27,33,23,13,51,57,66,85
Pass4: 27,23,33,13,51,57,66,85
27,23,13,33,51,57,66,85
Pass5: 23,27,13,33,51,57,66,85
23,13,27,33,51,57,66,85
Pass6: 13,23,27,33,51,57,66,85
Pass7: Finally, there is no comparison now, as we have sorted the elements of the array A.

Algorithm: (imp)

1. Repeat step 2 and 3 for K = 1 to N-1.


2. Set PTR:=1 //Initialize pass pointer PTR
3. Repeat while PTR N-K. //Execute pass

Nirmala Memorial Foundation Junior College of Commerce and Science Page 26


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.
There is an inner loop, which is controlled by the variable PTR and the loop is contained in an outer
loop, which is controlled by an index K.

Q. Explain binary Search algorithm with the help of example.


Ans. Algorithm:
Here DATA is a sorted array with lower bound LB and upper bound UB, and ITEM is a given
item of information. The variables BEG, END and MID, respectively, denotes the beginning, end
and middle locations of a segment of element of DATA. This algorithm finds the location LOC of
ITEM in DATA or sets LOC = NULL.

1. [Initialize segment variables.]


Set BEG=LB, END=UB and MID=INT(BEG+END/2)
2. Repeat step 3&4 [while BEG, END and DATA [MID], ITEM]
3. If ITEM<DATA [MID], then:
Set END=MID-1.
Else:
Set BEG=MID+1.
[End of If structure]
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.
Example:

L et DATA be the following sorted 13-element array:


DATA: 11,22,30,33,40,44,55,60,66,77,80,88,99
We apply the binary search to DATA for different values of ITEM.

Suppose we are searching ITEM=40


So, it will be like
Initially, BEG=1 and END=13. Hence
MID = INT(1+13)/2=7 & so DATA[MID]=55

Nirmala Memorial Foundation Junior College of Commerce and Science Page 27


Since 40<55, END has its value changed by
END=MID-1 =6. Hence,
MID=INT[(1+6)/2] =3 & so DATA [MID] = 30

Since 40>30, BEG has its value changed by BEG=MID+1 = 4 Hence


MID=INT [(4+6)/2] =5 & so DATA[MID] =40
We have found ITEM in location LOC=MID=5.

1) 11 22 30 33 40 44 55 60 66 77 80 88 99

2) 11 22 30 33 40 44 55 60 66 77 80 88 99

3) 11 22 30 33 40 44 55 60 66 77 80 88 99
[Successful ]

Binary Search for ITEM = 40.

Q) Write an algorithm for linear search technique with suitable example.


Ans. Algorithm : Linear Search
LINEAR (DATA, N, ITEMS, LOC)
Here DATA is a linear array with N elements and ITEM is given element. This algorithm finds the
location LOC of ITEM in DATA or sets LOC = 0, if search is successful.
Step 1 : [Insert ITEM at the end of DATA]
Set DATA[N+1] : = ITEM
Step 2 : [Initialize counter]
Set LOC : = 1
Step 3 : [Search for item]
Repeat While DATA[LOC]  ITEM :
Set LOC = LOC + 1
[End of loop]
Step 4: If LOC = N + 1, then :
Set LOC : = 0
Step 5 : Exit
For example : Given DATA array with following 5 elements
11 22 33 44 55
Suppose ITEM = 33
Step 1 : Set DATA [6] = 33,  List becomes
11 22 33 44 55 33
Step 2 : LOC = 1
Step 3 : Since DATA [1] = 11  33 LOC = 2
Since DATA [2] = 22  33 LOC = 3
Here DATA [3]  33  33  ITEM
Step 4 : Hence ITEM = 33 found at position, LOC = 3.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 28


Q) Write difference between Linear search and Binary search.
Ans.
Linear Search Binary Search
1. Linear search performs on unsorted list 1.For binary search, the elements in array are
of elements as well as sorted list. stored in alphabetically or numerically in
sorted manner.
2. Compare the desired element with all 2. Compare the value of midpoint with desired
elements in an array until the match is value. If the value is greater than midpoint
found. value the first half is checked, otherwise
second half is checked until search is
successful or interval is empty.
3. Insertion of an element in an array can be 3. An insertion of a new element requires that
performed very efficiently when array is many elements be physically moved to
not ordered. preserved order.
4. For large size of array, time required for 4. For large size of array, comparatively time
this search is very large. required is less.
5. `Time complexity is as follows : 5. time complexity as follows :
worst case : N comparison worst case : log2 N comparison
Best case : 1 comparison Best case : 1 comparison

Nirmala Memorial Foundation Junior College of Commerce and Science Page 29


Arrays, Records and Pointers
INTRODUCTION:
Data structures are classified as either linear data structure or non-linear data structure.

 Linear data structure-


A data structure is said to be linear if its elements form a sequence, or in other words, a
linear list. There are two basic ways of representing such linear structure in memory.
1) The first way is to have the linear relationship between the elements of sequential memory
locations. These linear structures are called as arrays.
2) The second way is to have the linear relationship between the elements represented by means of
pointers or links. These linear structure are called linked lists.
 Non-linear data structure-
This structure is mainly used to represent data containing a hierarchical relationship between
elements, that is, records, family trees and table of contents such as trees and graphs.

Linear arrays:
Definition : An array can be defined as the collection of the sequential memory locations, which can
be referred to a single name along with a number, known as index, to access a particular field or data.
When the elements need to be referred by more than one index, it is known as Multidimensional
arrays.

There are data structures other than arrays, linked lists and trees. Some of these structures are
as follows:

a) Stack: A stack, also called a last-in-first-out (LIFO) system, is a linear list in which insertion and
deletion can take place only at one end, called the top. This structure is similar in its operation to
a stack of dishes or glasses placed at one above another and you can take out the dishes or glass
only from one end, that is , top.

b) Queue: A queue, also called a first-in-first –out (FIFO) system, is a linear list in which deletion
can take place only at one end of the list “front”, and insertions can take place only at the other
end of the list “rear”. For example, Queue in the bus stop, the first person in the queue gets in the
bus first and to join the queue the person has to come in the last.

c) Graph: Data sometimes contain a relationship between pairs of elements, which is not
hierarchical in nature. For Example, suppose an airline flies only between the cities connected by
lines. The data structure that reflects this type of relationship is called a graph.

Q. What are data structure operations ?


Ans. The data appearing in our data structures are processed by means of certain operations. The
following are the data structure operations, which are used:
1. Traversing: Accessing each record exactly only once so that certain items in the record may be
processed. (This accessing & processing is sometimes called “visiting” the record)

Nirmala Memorial Foundation Junior College of Commerce and Science Page 30


2. Searching: Finding the location of the record with the given key value, or finding the locations of
all the records.
3. Inserting: Adding a new record to the structure.
4. Deleting: Removing a record from the structure.
5. Sorting: Arranging the records in some logical order (e.g. alphabetically or numerically).
6. Merging: Combining the records in two different sorted files into single sorted file operations.

Q. What are the different control structures?


Ans. The control structures are as follows:
1. Sequence logic, or sequential flow
2. Selection logic, or conditional flow
3. Iteration logic, or repetitive flow
Explanation:
1. Sequential flow:
It means that the flow of the structure flows in sequence. The sequence can be presented by
means of numbered steps or by which the modules are written. Example:

Module A

Module B

Module C

Fig (a) Sequential flow


2. Selection logic: (Conditional Flow):
Selection logic employs a number of conditions, which lead to a selection of one out of
several alternative modules. The structures which implement this logic are called conditional
structures or IF structures. These conditional structures fall into three types. They are
(a) Single alternative: This structure has the form:
If condition, then:
[Module A]
[End of If structure]
The logic of this structure is pictured as:

Condition? Condition?

Module A Module A Module B

Single alternative Double alternative

Nirmala Memorial Foundation Junior College of Commerce and Science Page 31


(b) Double alternative: This structure has the form

IF condition, then:
[Module A]
Else:
[Module B]
[End of If structure]
The logic of this structure is pictured in Fig (b), above.
(c) Multiple alternative: This structure has the form
If condition (1), then:
[Module A]
Else if condition (2), then :
[Module B]
:
Else:
[Module C]
[End of If structure]
This logic of this structure allows only one of the modules to be executed.
3. Iteration Logic (Repetitive Flow):

This type of logic refers with a repeat statement involving loops. Each type begins with a Repeat
statement and is followed by a module, called the body of the loop

K=R

Is K>S?

Module (body of loop)

K=K+T

Q. What is the Complexity of Algorithms?

Ans.
 An algorithm is a well-defined list of steps for solving a particular task or problem.
 One major purpose of complexity is to develop efficient algorithm for the processing of or data.
 The time and space it uses are two major measures of the efficiency of an algorithm.
∴ The complexity of an algorithm is the function which gives the running time / space in terms of
the input size.
 The following two complexities are the important factor for complexity of an algorithm.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 32


 Space complexity
 Time complexity

Definition:

(i) Space complexity: The space complexity of an algorithm is the amount of memory it needs to run
or to complete an algorithm.
(ii) Time complexity: The time complexity of an algorithm is the amount of computer time it needs to
run or to complete an algorithm.

Q. What is a record? How it differs from a linear array?

Ans. A record is a collection of field or attributes i.e. relative data items.

Collection of data is frequently organized into hierarchy of field i.e. records. A file is nothing but
collection of records.

Difference between records and linear arrays :

(i) A record is a collection of fields, while an array is list of homogeneous data elements.

(ii) A record may contain non-homogeneous data i.e. data elements may be of different data types. An
array always contains homogeneous data.

(iii) In a record, natural ordering of elements is not possible. Array elements can be naturally ordered.

(iv) Elements of record are referenced by level number, while those of array can be referenced by an
index set consisting of n consecutive numbers.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 33


Linked List
ARRAY

 Data processing involves storing and processing data organized into lists.
 One-way store such data is by means of arrays.
 The linear relationship between the data elements of an array is reflected by the physical relationship of
the data in memory not by any information contained in the data elements themselves.
 This makes easy to compute the address of an element in an array.
 Disadvantages: It is relatively expensive to insert and delete elements in an array.
 Also, since an array usually occupies a block of memory, one cannot simply double or triple the size of
the array.

Link or Pointer

 Another way of storing a list in memory is to have each element in the list contain a field, called list
or pointer, which contains the address of the next element in the list.
 It does not occupy the adjacent space in memory, this will make it easier to insert and delete
elements in the list.

Q. What is Linked list? Explain.


Ans.
A linked list, or one-way list, is a linear collection of data elements, called nodes where the linear order
is given by means of pointers. That is, each node is divided into two parts: the first part contains the
information of the element, and the second part, called the link field or next pointer field, contains the
address of the next node in the list.
Basic example of linked list:
The diagram below of a linked list contains 6 nodes. Each node contains two parts. The left part
represents the information of the present node, which may contain an entire record of data items
(e.g. NAME, ADDRESS ..... ). The right part represents the next pointer field of the node, and
there is an arrow drawn from it to the next node in the list. The pointer of the last node contains
a special value, called the null pointer, which is any invalid address.
Start

Next pointer field of fourth record

Information of third record


Example:
A hospital ward contains 12 beds, of which 9 are occupied. Suppose we, arrange as listing of the
patients. This list can be given in the pointer field, Called NEXT. We use the variable START
to point to the first patient. Hence START contains 5.5 contain the information Vishal & points

Nirmala Memorial Foundation Junior College of Commerce and Science Page 34


to bed 3. Since 3 contain the patient Karan & Points to bed 11. Since 11 contain the patient
Sahil & points to bed 8 and so on.

Bed. no. Patient NEXT

1 Sita 7
Start
2

3 Karan 11
5
4 Juliet 0

5 Vishal 3

7 Ruchi 4

8 Mihir 1

9 Nita

10

11 Sahil 8

12 Nilesh

Q. How linked list is represented in memory?


Ans.
Let LIST be a linked list. LIST requires two linear arrays-called as INFO and LINK (INFO
contain the information of the present node and LINK contain the next pointer field of a node).
LIST also requires a variable name- such as NAME or START, which contain the location of
the beginning of the node and a NULL to indicate the end of the node.
The following example of linked list indicaes that the nodes of a list need not occupy
adjacent elements in the arrays INFO and LINK. However, each node has its own pointer
variable. From the given example, we can obtain the actual list of characters, or in other
words the string.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 35


INFO LINK

1
2
3 O 6
Start 4 T 0
5
6 11
9 10
7 X
8
9 N 3
10 I 4
11 E 7

START =9, so INFO[9] = N is the first character.


LINK [9]=3, so INFO [3] = 0 is the second character.
LINK [3] = 6, so INFO [6] = (blank) is the third character.
LINK [6] = 11, so INFO [1] = 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] = T is the seventh character.
LINK [4] = 0, the NULL value, so the list has ended.
In other words, NO EXIT is the character string.

Q. What are linked lists? Show a liked list with suitable example having six nodes with a
properly labelled diagram.
OR
With suitable example, show labelled diagram for link between two nodes having theinformation
part and next pointer field.
Ans. i) A linked list is a linear collection of data elements, called nodes, where the linear order is
maintained with the help of pointers.
ii) Linked list is also called as one-way list.
iii) Each node in the linked list is divided into two parts. First part is called as INFO part, called as
LINK part, which is next pointers field i.e., it contains the address of next node in the list.
iv) e.g.
Start
10
Info Link (Pointer to next node)

A 13 B 19 C 14 D 12 E 18

F X
18
(a) The above figure shows a linked list having six nodes.
(b) The left part of the node is the Info part, which contains information of the element, while the
right part is Link part, which is next pointers field i.e., it points to next node.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 36


(c) An arrow is drawn from Link part of one node to the next node to indicate link.
(d) The address of the list is stored in Start or Name of the list.
(e) The Link part of last node is null pointer i.e., it contains nothing.
(f) To trace the linked list, we just require the address of Start or Name.

Binary Tree
 We know the linear types of data structures: strings, arrays, lists, stacks and queues.
 Data structures also define nonlinear data structure called a tree.
 The tree structure is mainly used to represent data containing a hierarchical
relationship between elements: example: family trees, records etc.
 Binary tree is a tree, which can be easily maintained in the computer.

Q. What is Binary tree?


Ans. A binary tree T is defined as a finite set of elements, called nodes, such that:
(a) T is empty (called the null tree or empty tree),or
(b) T contains a distinguished node R, called the root of T and the remaining nodes of T form
an ordered pair of binary trees T1 and T2.
(c) If T is non-empty, then its root is called the left successor of R; similarly if T is non-empty,
then its root is called the right successor of R.
A binary tree T is frequently presented by means of a diagram. Specifically, the diagram
below represents a binary tree as follows:
(i) T consists of 11 nodes
(ii)The root of T is the node A.
(iii)A left-downward slanted line from a node N indicates a left successor of N, and a
right-downward slanted line from N indicates right successor of N.

Observe the following tree:- A

B C

D E F G

H I J

Nirmala Memorial Foundation Junior College of Commerce and Science Page 37


Any node N of a binary tree T has either 0,1,or 2 successors. The nodes A, B,C,G has two
successors while the nodes E, I have only one successor and the nodes H, K have no
successors. The nodes with no successors are called terminal nodes.
The above definition of binary tree T is recursive since T is defined in terms of binary tree T
and T1. This means, that every node N of T contains a left and a right subtree. Moreover, if N
is a terminal node, then both its left and right subtrees are empty.
Binary trees T and T1 are said to be similar if they have same structure or shape. The trees
are said to be copies if they are similar and if they have same contents at corresponding
nodes.

Example of Binary Tree:

Consider any algebraic expression E involving only binary operations, such as


E=(a-b)/((c*d)+e)
The binary tree will be constructed as:
=

E /

+
-

*
e
a
b

c d
Q. How binary tree is represented in memory?
Ans. A tree T can be maintained in memory be means of a linked representation which uses three
parallel arrays INFO , LEFT and RIGHT and a pointer variable ROOT.
Each node N of T will correspond to a location K such that:
1) INFO[K] contains the data at the node N.
2) LEFT[K] contains the location of the left child of node N.
3) RIGHT[K] contains the location of the right child of node N.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 38


Example:-

Sr. No. NAME LEFT RIGHT


SUCCESS SUCCESS
OR OR

1 0
2 Sita 0 12
3 Guru 0 0
ROOT 4 Girish 2 0
5 1
6 Bhawna 0 0
7 Leeta 3 10
14 8 11
9 Chandu 6 4
10 Ruby 0 0
11 13
12 Amit 0 0
13 5
14 Heena 9 7

Heena
Chandu Leeta

Bhawna Girish Guru Ruby


Sita

Amit

a) The value ROOT = 14 indicates that Heena is the root of the tree.
LEFT[14]=9 indicates that Chandu is the left child of Heena, and RIGHT[14]=7 indicates
that Leeta is the right child of Heena.
(Repeat the step for each node in the diagram)

Q. How to traverse binary tree?


Ans. There are three standard ways of traversing a binary tree T with root R. These three lgorithms,
called preorder, inorder and postorder, are as follows:

Preorder: (NLR)
1. Process the root R.
2. Traverse the left subtree of R in preorder.
3. Traverse the right subtree of R in preorder.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 39


Inorder: (LNR)
1. Traverse the left subtree of R in inorder.
2. Process the root R.
3. Traverse the right suntree of T in inorder.
Postorder: (LRN)
1. Traverse the left subtree of R in postorder.
2. Traverse the right subtree of R in postorder.
3. Process the root R.

The three algorithms are sometimes called, respectively, the node-left-right (NLR) traversal,
the left-node-right (LNR) traversal and the left-right-node(LRN) traversal.

Q. Explain LIFO and FIFO.


Or
Explain Stack & Queue.
Ans. A stack is a linear data structure in which the data elements can be inserted and deleted at
one end only i.e. the top. LIFO stands for Last-in-First-out. The element which is inserted last in stack
will be removed (deleted) first. The everyday example of Stack is stack of dishes, stack of plastic
cups.
When you want to insert any element in stack, it is known as “PUSH” and when you want to
delete any element from stack, it is known as “POP”.
Example: Suppose 11,12,43,24 ; is a set of data elements
Inserting element 65

PUSH
65 65
24 24
43 43
12 12
11 11
Suppose if we want to delete 43 from the stack, so we have to first delete the top element
i.e. 65, then the second, then third, until we pop the required element.
POP
65
POP
24
65 POP
24 24 43

43 43 43
12 12 12 12
11 11 11 11

Nirmala Memorial Foundation Junior College of Commerce and Science Page 40


Now, the stack contains the elements 11, 12.
FIFO
A queue is a linear data structure in which data elements can be inserted from one end and
deleted from the other end. The element which is inserted first is deleted first and the element
which has entered in the end will be deleted last, so the term FIFO. The everyday example of
queue is line in a bus stop. The person standing first in the queue enters first in the bus and the
person who has entered last in the queue , gets in last in the bus.
We insert the element from the “rear” and delete the element from the “front”.
Example: Suppose, 11,12,43,24 is a set of data elements

11 12 43 24

front rear
Inserting element 65.

11 12 43 24 65

front
rear
(inserted the element)
Now, if we want to delete the element 11.

12 43 24 65

front rear
(deleting element 11)
Q. What are pointer arrays?
Ans. i) An array is called pointer array, if each element of that array is a pointer.
ii) The variable is called as pointer variable, it points to another variable i.e. it
contains the memory address of other variable.
iii) consider an organization, with divides its employee list into four groups,
depending on certain conditions. Following figure shows the list of 4 groups.
There are 15 employes and groups contains 2, 5, 4 and 4 employes respectively as
Group 1 Group 2 Group 3 Group 4

Deepak Swapnil Rajdeep Yashwant

Nitin Amit Amol Chintamani

 Vivek Yogesh Kishore

 Ravi Shekhar Rohit

 Omprakash  

iv) If these groups are to be represented in memory, the most efficient way is to use 2

Nirmala Memorial Foundation Junior College of Commerce and Science Page 41


arrays. The first is Employee array, which contains list of employees in all four groups
sequentially, while the second array is Group array, which is a pointer array, which
contains the starting address of each group in the Employee array, respectively.
v) It is shown is figure :

vi) Each element of Group array is a pointer, which holds the starting addresses of
different groups. Hence, it is called as pointer array.

Q. Draw the binary tree for the following expression :


1. E = (a + b) / [(c * d) – e] 2. (2x + y) (a – 7b)3

Nirmala Memorial Foundation Junior College of Commerce and Science Page 42


CHP-3. INTRODUCTION TO C++
Q. What is C++? What are the advantages of C++?

Ans. : C++ is an object oriented programming language. Initially C++ was named as “C with classes”.
C++ was developed by Bjarne Stroutstrup at AT & T Bell Laboratories, USA, in the early eighties. Advantages of
C++:-
1. C++ is an incremented version of C. It is a superset of “C”. Almost all C programs can also run in
C++ compiler.
2. The important facilities are added in C++ such as classes, function overloading & operator
overloading.
3. C++ allows user to create abstract data types, to inherit properties from existing data types.
4. C++ supports polymorphism.
5. Any real life application system such as editor, complier, and database communication systems can
be built by C++.
6. Object oriented libraries can be built by C++.
7. C++ programs can be easily implemented, maintained and expanded.

Q. Differentiate between Procedural Oriented Programming (POP’s) and Object Oriented


Programming (OOP’s).
Ans. :

Procedural Oriented Programming (POP’s) Object Oriented Programming (OOP’s)


1. In this approach, the problem is viewed as a 1. In this approach, the problem is
sequence of things to be done. decomposed into entities called objects.
2. Emphasis is on doing things. 2. Emphasis is on the data rather than
procedure.
3. Large programs are divided into smaller 3. Programs are divided into entities known
programs known as functions. as objects.
4. Data can move openly (easily) from functionto 4. Data is hidden and cannot be accessed by
function. external functions.
5. It is a top-down approach in program design. 5. It is a down-up approach in program
design.
6. Data security is not there 6. Data is secured.
7. The concept of class is not defined. 7. The concept of class is defined.
8. Data and functions do not work together. 8. Data and functions work together.
9. E.g. C,COBOL, FORTON 9. E.g. C++, VB, Java

Nirmala Memorial Foundation Junior College of Commerce and Science Page 43


Q. What are the different data types in C++?
Ans. : The different data types in C++ are as follows:

C++ Data types

User defined type Built-in type Derived type

Structure Array
Union void Function
Integral Floating Pointer
Class
type type
Enumeration

int char float double

1. C++ provides three data types which are user-defined data type, built-in data type and derived
data type.
2. User-defined data type provides structure, union and class while derived data type provides
arrays, function and pointer.
3. Built-in data type provides three types which are integral type, void and floating type.
4. Integral includes integer and character (string) while floating type includes float and double.

Q. Enlist the basic data types used in C++ with size of data in terms of bytes for each.
Ans. : Built-in type
Or
Basic data type

Integral void Floating

int char floa double

There are three basic data types which are integral data type, void and floating data type.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 44


1. Integral data type : It includes integer (int) & character (char).
*Any int variable required 2 bytes to store and a character variable requires 1 byte.
*Integer variable are also of two types:
Short int: Which requires 2 bytes.
Long int: Which requires 4 bytes.

2. void : It is used for:


To specify the return type of a function when it is not returning any value and to indicate an empty
argument list to a function.

3. Floating : Floating are of two types


*Float: It requires 4 bytes to store in memory.
*Double: It requires 8 bytes to store in memory.

Q. Explain the structure of a general C++ program.


Ans. :The structure of a general C++ program contains 4 sections. These sections may be placed in
different code files and then complied independently or jointly.

Include files
Class Declaration
Class functions
and definitions
Main functions
program
1. The class declaration is placed in header file and the definition of the member function is placed
in other file.
2. This above approach enables the programmer to separate the abstract of the interface from the
implementation details.
3. Finally, the main program that uses the class is placed in third file, which includes the previous two
files as well as any other files required.

Q. Syntax of C++ program


Ans. :
Header file
Data Member
Member Function
Main (Function)

Nirmala Memorial Foundation Junior College of Commerce and Science Page 45


* Note to Remember:

cout for printing

Keyword extracting symbol (operator)

cin for inserting

Keyword inserting symbol (operator)

Header file is a file in which the in-built functions are defined, included and declared.

Arrays

 Introduction Refer to the notes of


 Needs of Arrays Data Structure

 Types of Arrays
Single (one) dimensional array – Refer to notes of data structure
Two-Dimensional Array
Multi-Dimensional Array

Q. Explain two-dimensional Array (Matrix-2-D Array).


Ans. A two- dimensional (mxn) array A is a collection of mxn data elements such that each element is
specified by a pair of integers.
The number of elements in a 2-D array can be determined by multiplying number of rows withnumber of
columns. Explanation : number of elements in an array A[2] [3] is calculated as 2 3=6.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 46


Example of two-dimensional array

The general form of a two-dimensional array declaration in C++ is as follows:Syntax:

type array_name [rows][columns]

Eg- int A[3][1] or int A[2][3]

An example of C++ program of two-dimensional or Matrix 2-D array is as follows:

#include<isotream.h>
#include<conio.h>int main()
{
int A[3][3],B[3][3], C[3][3], r, c, ch, ans;
clrscr();
cout<<”Enter first matrix”;
for (r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
cin>>A[r][c];
}
}
cout<<”Enter second matrix”;
for(r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
cin>>B[r][c];
}
}
cout<<”Matrix A is”<<endl;
for (r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
cout<<A[r][c];
}
}
cout<<”Matrix B is”<<endl;
for (r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
cout<<B[r] [c];

Nirmala Memorial Foundation Junior College of Commerce and Science Page 47


}
}
cout<<”Addition is”<<endl;

for(r=0; r<3; r++)


{
for(c=0; c<3; c++)
{
C[r] [c] = A[r] [c] + B[r][c];
cout<< C[r] [c] << “\t”;
}
cout<< “\n”;
}
}
return 0;
}
 Multi-dimensional Array:
Multi-dimensional arrays are defined in the same manner as one dimensional arrays, except that a separate pair of
square brackets is required for each subscript.
The general form (syntax) of a multi-dimensional array declaration isType
name[a] [b] [c] .................................. [z]
The arrays of three or more dimensions are not often used because of their huge memory
requirements and the complexity involved with their manipulation. Manipulation in multi-
dimensional array is more complicated as compared to single and two-dimensional array.

Principles of OOP’s
Q. What is object oriented programming? Enlist the features of object oriented programming.
Ans. : “Object oriented programming is an approach that provides a way of modularizing programs by
creating partitioned memory area for both data and functions that can be used as templates for creating
copies of such modules on demand.”
The features of OOP’s are:
i. Emphasis is on data rather than procedure.
ii. Programs are divided into what are known as objects.
iii. Data structures are designed such that they characterize the objects.
iv. Follows bottom-up approach in program design.
v. Data is hidden and cannot be accessed by external functions.
vi. Objects may communicate with each other through functions.
vii. New data and functions can be easily added whenever necessary.
viii. Functions that operate on the data of an object are tied together in data structure.

Q. What are the basic concepts of OOP’s?


Ans. : The basic concepts of OOP’s are as follows:
1) Objects 5) Inheritance

Nirmala Memorial Foundation Junior College of Commerce and Science Page 48


2) Classes 6) Polymorphism
3) Data Abstraction 7) Dynamic Binding
4) Data encapsulation 8) Message Passing

1. Objects:-
i. Objects are the basic runtime entities in an object oriented system. Eg: they may represent a person,
place, a bank account or any item that the program must handle.
ii. Programming problem is analyzed in terms of objects & the nature of communication between them.
iii. Program objects should be chosen such that they match closely with the real-world objects.
OBJECT:
Student

DATA:
Name Way of representing objects
Marks
FUNCTION:
Total()
Avg()
show()

2. Classes:-
i. Class is a way to bind data and its associated functions together.
ii. An object is nothing but a variable, whose data type is class.
iii. Once a class has been defined, user can define any number of objects belonging to that class.
iv. A class is a collection of objects of similar type.
v. Example: mango, orange & apple are members of the class fruit.

3. Data Abstraction:-
i. Abstraction refers to the act of representing essential features.
ii. Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight & cost, and functions to operate on these attributes.
ii. The attributes are sometimes called data members because they hold information.

4. Data Hiding and Encapsulation:-


i. The wrapping up of data and functions into a single unit (called class) is known as
encapsulation.
ii. The functions which are wrapped in the class can access the data.
iii. This insulation of the data by the program is called data hiding.

5. Inheritance:-
i. Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
ii. In OOP’s, inheritance stands for reusability. This means that the additional features can be
added to an existing class without modifying it.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 49


iii. The mechanism of deriving a new class from an existing one is called as inheritance.

6. Polymorphism:-
i. It is another important OOP concept. Polymorphism means the ability to make one form.
Eg- if the 2 operands are string, then it would (the operation) produce a third string.

ii. It plays an important role in allowing objects having different internal structures to share the
external interface.

Shape

Draw()

Circle object Box object Triangle object

Draw(circle) Draw(Box) Draw(Triangle)

7. Dynamic Binding:-
i. Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
ii. Dynamic binding means that the code associated with a given prodecure call is not known
until the time of the call at run time.
iii. It is associated with polymorphism & inheritance.

8. Message Passing:-
i. The process of communication in OOP’s involves following steps.
a. Creating classes that define objects and their behavior.
b. Creating objects from class definition.
c. Establishing communication among objects.
Eg- employee salary (name);

object message information


Q. What are the benefits of OOP’s?
Ans. : OOP’s refers several benefits to both the program designer & the user. It contributes to the solution
of many problems associated with the development and quality of the software.
The principal advantage of OOP’s are:-
1. Through inheritance, we can elimate redundant code & extend the use of existing classes.
2. The principle of data hiding helps the programmer to build secure programs that cannot be
used in other parts of the program.
3. It is possible to have multiple instances of an object to co-exist without any inheritance.
4. It is easy to partition the work in a project based on objects.
5. It can be easily upgraded from small to large systems.
Nirmala Memorial Foundation Junior College of Commerce and Science Page 50
6. Message passing techniques for communication between objects makes the interface with
external system much simpler.
7. Software complexity can be easily managed.
8. The data and functions are wrapped together in a class.

Classes and Objects


Q. What is a class? Explain general form of class declaration?
Ans. : 1. Class is a way to bind its associated functions together.
2. It allows the data and functions to be hidden.
3. While defining a class, we can create a new abstract data type that can be treated like any other
built in data type.
4. Generally, a class specification has two parts:
i. Class declaration
ii. Class functions declaration
The general form of class declaration is

Class classname
{ private:
Declaration of data members;
Declaration of member functions;
public:
Declaration of data members;
Declaration of member functions;
};

The body of a class is enclosed with braces and terminated with a semicolon. The data members and
member functions are grouped together under private and public. The members, declared as private can be
accessed only within the class and public can be accessed from outsidethe class also. It’s a key feature of
OOP’s .
Class item
{ private:
int number;
float cost;
public:
void getdata(int a, int b);
void putdata();
};

Q. Explain the Scope of Member Function.


OR
Describe how member functions of class can be defined.
Ans. : Member Functions can be defined and accessed in two ways.
i) Outside the class: The general form of accessing the data from outside the class definition is
classname :: functionname

Nirmala Memorial Foundation Junior College of Commerce and Science Page 51


where the classname indicates the name of the class and “::”, called the scope resolution operator,specifies that
the scope of the function is restricted to the class classname
Syntax: return type classname :: functionname (parameter list)
{
function body
}
ii) Inside the class:
Another method for defining a member function is to replace the function declaration by the actualfunction
definition .
Inside the class Outside the class
class circle class circle
{ {
public : int r = 2; public : int r = 2;
void area() void area();
{ };
float c = 2 *3.14*r; circle :: void area()
cout<<c; {
} float c = 2*3.14*r;
}; cout << c;
}

Q. What is the Scope of class & its members?


Ans. :
1. Public members-
They are the members that can be accessed by any function. Eg-
class x
{ public : int a;
int sqr( int a)
{
return a*a;
}
};
void main ()
{ x a1; //object created for class x
int b;
a1.a=10; //public data member can be used in any function
}

2. Private members-
They are the members that are hidden from the outside world. The private members implement theOOP’s
concept of data hiding. They can be used only by member functions and friends.
Eg- class x
{
private: a;

Nirmala Memorial Foundation Junior College of Commerce and Science Page 52


public:
int sqr(int a)
{
return a*a ;
}
};
void main ()
{ x a1;
a1.a=10;
cout << the value of square is “<<a*a;
}
Here ,”a” is private which can be used only in public class of x.

Q. What is an object ? Describe how members of a class be accessed using object of that class?
Ans. : 1) An object is a variable whose datatype is class.
2) User can have more than one object for a class. The objects can be declared as :
class_name object1, object2.
Accessing members of class using objects.
1. The private data of a class can be accessed only through the member function of that class.
2. To use a member function, the dot operator (.) connects the object name & the member function.
The dot operator is called as class member access operator.
3. Syntax: objectname. functionname (actual argument)

4. Eg : class student
{
int a;
public: getdata(int a)
{
cout << “Please enter the number”;
}
display ()
{
cout << “The number is”<< a;
}
};
void main ()
{
student a; //object is created
a.getdata(); //getdata() member function is accessed through object ‘a’
a.display(); //display() is accessed through object ‘a’
}
Here, student is a class with object name a and the dot operator is used to access the data by
a.getdata(); function.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 53


Q. What is friend function? Give the characteristics of friend function.
Ans. :
1. A non- member function that is allowed to access the private variable of a class is called a friend
of the class.
2. A function is made a friend of a class by the keyword “friend”.
Eg- class classname
{
private :
public :
friend return- type function name (arguments);
};
3. The characteristics of friend function are as follows.
- A friend function can access the private members of a class.
- The friend declaration is unaffected by its location in the class.
- The definition of a friend function does not require the name with the scope resolution operator
prefixed to it, as it is required for a class member function.

Q. How does a friend function work?


Ans. : To declare a non-member function as a friend of a class, its prototype declaration starting with thekeyword
“friend” should be included in the class definition.
Eg: There is a class sample and has a friend function as check(), the class definition may look
like as follows:
class sample
{
private: int a, b;
public: friend void check(int a); //declaration included
};
The above function definition of friend function does not use the keyword “friend”.
Important points of friend function:
a. A function may be declared friend of more than one class.
b. It does not have the class scope, rather it depends upon its original declaration and definition
c. It can be invoked like a normal function (does not require any object)
d. Since it is not a member function (it is a friend function), it cannot access the members of the class
directly and has to use an object name and membership operator with each member name.
Eg- To access member X of a class ABC, it has to use A.X where A is an object of the class.
e. It can be declared anywhere in the class without affecting its meaning.
Example of a friend function:
#include<iostream.h>
#include<conio.h> class A
{ private: int m,n;
public : void setvalue( )
{ m = 5, n= 6; }
friend void sum()
{
cout<< m+n;

Nirmala Memorial Foundation Junior College of Commerce and Science Page 54


}
};
void main()
{
A ab;
ab.setvalue();
sum(); // sum() is called without object as it is declared friend
}
In the above example, the function sum() is a friend function and it is accessed directly without an object
and dot operator.

Q. What is Data Hiding and Encapsulation?


Ans.: Abstraction supports data hiding.
Abstraction refers to the act of representing essential features without including the background details or
explanation. Eg- using a “switch board”, we needn’t know its essential features, that is, when all switches
are pressed, at that time, the background details like connection are hidden from us.
It supports data hiding so that only relevant information is exposed to the user and rest of the information
remains hidden from the user.
Encapsulation is a way to implement abstraction by wrapping up and associated functions into a single unit.
The class of C++ is a vehicle for translating a data abstraction to a user-defined type. The class binds the
data & associated functions together into a single unit (type) which is encapsulation.

Q. What is Static Class Member and Static Member Function?


Ans.: Static Data Member:
The members (data member and member functions) of a class may be qualified as static.
A static data member of a class is just like a global variable for its class, that is, this data member is
globally available for all the objects of that class type. The static data members are usually maintained to
store values common to the entire class. Eg- A class may have a static data member to keep a track of its
number of existing objects. It is different from ordinary data member of a class in various aspects.
1. There is only one copy of this data member maintained for the entire class which is stored by all the
objects of that class.
2. It is visible only within the class, however, its lifetime (the time for which it remains in the memory)
is the entire program.
Object 1 Object 2 Object 3

count
Static Member function
A member function is that access only the static members of a class may be declared as static. This can be
done by putting keyword “static” before the function declaration in the class definition.

Eg- class x
{ static int count;
static void show (void)

Nirmala Memorial Foundation Junior College of Commerce and Science Page 55


{ cout << count << endl; }
};
int x :: count;

By just passing the keyword static in the class definition, you have declared the function static.
A static member function is different from other member function in various ways:
1. A static member function can access only static members (functions or variables) of the same class.
2. A static member function is invoked by using the class name instead of its objects as given below
classname :: function-name
Example:
class A
{ static int a = 0;
int b;
public : void getdata(int c)
{
b = c;
a = a + 1;
}
void putdata()
{
cout<<c;
cout<< “counter:”<<a;
}
};
void main()
{ A a1, a2;
a1.getdata(5);
a1.putdata();
a2.getdata(10);
a2.putdata();
}
In above example, static ‘a’ keeps the counter track for both a1 and a2.

Q. What is object? Explain Array of object.


Ans.: Object – Refer to Page 52
Array of objects:- C++ supports arrays of any data type including class type. An array having classtype
elements is known as Array of objects. An array of objects is declared after the class definition is over & it is
defined in the same way as any other type of array is defined.
Consider the following example:
class item
{
public:
int itemno;
float price;
void getdata(int i, float j)
{
Nirmala Memorial Foundation Junior College of Commerce and Science Page 56
itemno=i;
price =j;
}
void putdata (void)
{
cout<< “ item no :”<<item no<<endl;
cout<< “ price :”<<price;

}
};
void main ()
{ item order[10]; //Array of order to contain 10 objects of item type.
for (i = 0; i <=9; i++)
{
cout<<order[i].getdata();
cout<<order[i].putdata();
}
}
The array order contains 10 objects, namely, order [0], order [1], order [2] …& so on. To access data
member of item no 3 object in the array , we will give
order 2. itemno
Similary , to invoke putdata() for 7th object in the array order, we will give
order 6.putdata();

CONSTRUCTOR AND DESTRUCTOR


Q. What is constructor?
Ans. :
a. “A constructor is a special member function of a class. Its task is to initialize the objects of its class”.
b. It is special because its name is same as that of the class to which it belongs.
c. The constructor is invoked (active) whenever an object of its associated class is created.
d. It is called constructor because it constructs the values of data members of the class.
e. A constructor can never return any value. Hence, it is written with no return type.
f. Example:
class A
{
public: A(); //constructor declared
{
cout<<”this is a constructor”;
}
};
void main()
{ clrscr();
A a1();
}

Nirmala Memorial Foundation Junior College of Commerce and Science Page 57


Q. What are the syntax rules for writing constructors?
OR
Give the characteristics of a constructor function.
Ans. :
1. The constructor name is always same as the class name.
2. They do not have return types, not even void and therefore, they cannot return values.
3. They cannot be static.
4. They should be declared in public section.
5. They can have default arguments.
6. A constructor is invoked automatically when the objects are created.
7. They cannot be inherited though a derived class can call base class constructor.
8. An object with a constructor cannot be used as a member of union.

Q. What is Multiple Constructor?


Ans. :
1. When two or more functions are of the same name as that of the class then it is called multiple
constructor.
2. Example:
class ABC
{
public : ABC(int a)
{
a = 5;
cout<<a;
}
ABC (float b, float c)
{
b = 10;
c = 15;
cout<<b<<c;
}
};

Any class which contains many constructors with different parameters is called multiple constructor.

Q. What is Parameterize Constructor?


Ans. : A constructor with parameters (one or more than one parameter) is called parameterize constructor.
Example:
class A
{
int x, y;
public: A (int a) //parameterize constructor created
{
x =a;
y = a;
Nirmala Memorial Foundation Junior College of Commerce and Science Page 58
}
getdata( )
{
.......
.......
}
};
void main( )
{
A aa(5), ab(6), a( );
aa.getdata ( );
ab.getdata( );
}

Q. Why do we need constructor? [V.imp] include in every answer of constructor

Ans. : A constructor for a class is needed so that the compiler automatically initializes an object as soon as
it is created. A class constructor, if defined, is called whenever a program creates an object of that
class.

Q. What is a destructor? Give syntax rules for writing destructor function.


Ans. :
1. A destructor, as the name implies, is used to destroy the objects that have been created by a constructor.
2. The destructor is invoked (activated) by the complier upon exit from the program to clean the storage
that is no longer accessible (in use). In other words, a destructor function gets executed whenever an
instance of the class to which it belongs goes out of existence.
3. It is good practice to declare destructors in a program since it releases memory space for future use.
Syntax Rules:
1. A destructor function name is same as that of its class name.
2. It is preceded by a tilde( ~ ).
e.g. ~display( );
3. It takes no arguments.
4. It is declared with no return type since it can never return any value.
5. It should have public access in the class declaration.

Operator Overloading
Q. What is operator overloading? Explain with example.
Ans. :
i) The mechanism of giving some special meaning to an operator is called as operator overloading.
ii) C++ permits to add two variables of user defined data types with the same syntax as the basic types.
This means that C++ has the ability to provide operators with a special meaning for a data type. This
is nothing but operator overloading.
iii) Operator overloading provides a flexible option for the creation of new definitions for most of the
C++ programs.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 59


iv) When an operator is overloaded, its original meaning is not lost. For eg. The operator ‘+’ has been
overloaded to add two vectors, can still be used to add two integers.
v) To define an additional task to an operator, a special function called ‘operator function’ is used to
specify the relation of the operator to the class.
vi) Following program shows overloaded ‘+’ operator
eg.-
#include<iostream.h>
int a=2;
int b=3;
class abc
{
public : int a,b;
int operator +(void); //overloading binary +
};
int abc::operator +(void) // defined operator overloading
{
return (a+b);
}
void main( )
{
abc A;
+A; //invokes operator +( )
}

Q. What is Operator Overloading? State the three steps involved in operator overloading.
Ans. :
i) The mechanism of giving special meanings to an operator is known as operator overloading.
ii) Operator overloading provides a flexible option for the creation of new definitions for most of the
C++ operators.
iii) To define an additional task to an operator, a special function called operator function is used.
iv) The process of overloading involves the following steps:
1) First create a class that defines the data type that is to be used in the overloading operation.
2) Declare the operator function operation op( ) in the public part of the class. It may be either a
member function or a friend function.
3) Define the operator function to implement the required operations.

Q. Describe the syntax of an operator function.


Ans. : A function which defines additional task to an operator or which gives a special meaning to an
operator is called the operator function.
The general form of operator function is:

return type class_name::operator op(argument ist)


{
function body //function Definition
}

Nirmala Memorial Foundation Junior College of Commerce and Science Page 60


where return type is the type of value returned by a specified operation and op is the operator being
overloaded.
The op is preceded by the keyword operator. Operator op is the function name.
Eg:-
operator + ;
operator - ; etc .........

Q. State any eight rules for overloading operators.


Ans. : There are certain restrictions and limitations for overloading operators. Some of them are as
follows:
i) Only existing operators can be overloaded. New operators cannot be created.
ii) The overloaded operator must have at least one operand that is of user defined type.
iii) The basic meaning of an operator cannot change ie. We cannot redefine the plus (+) operator to
subtract one value from the another.
iv) The overloaded operators must follow the syntax rules of original operators.
v) Unary operators, overloaded by means of a member function take no explicit arguments & return no
explicit values.

vi) Unary operators, overloaded by means of a friend function take one reference argument.
vii) Binary operators overloaded through a member function takes one explicit argument.
viii) Binary operators overloaded through a friend function takes two explicit arguments.
ix) When using binary operators overloaded through a member function, the left hand operator must be
an object of the relevant class.
x) Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must not
attempt to change their own arguments.

Q. Write a program in C++ to overload unary minus operator, so that unary minus operator
when applied to an object should change the sign of each of its data items.
Ans. : #include<iostream.h>
#include<conio.h> class space
{
private: x, y, z;
public: space(int a, int b, int c)
{
x=a;
y=b;
z=c;
}
void display (void);
void operator –( ); //overloaded unary -
};
void space::display ( )
{
cout<<x<<”\t” <<y<<”\t”<<z;
}

Nirmala Memorial Foundation Junior College of Commerce and Science Page 61


void space::operator -(void)
{
x = - x;
y = -y;
z = -z;
}
void main ( )
{
space s;
cout<< “Enter three numbers”;
cin >>x>>y>>z;
s.display ( );
-s;
cout<< “ –s:”;
s.display( );
}

Explanation:
In the above program, the operator ‘-’ is overloaded. When the main function goes to ‘-s’ (where
s is object of class space), it activities and overloads the function and the operator.

Output:
Enter three numbers10 -20
30
-s: -10 20 -30

Q. Write a program in C++ to overload binary + operator for addition of two complex numbers.
Ans. : #include<iostream.h>
#include<unio.h>
class complex
{
private: float x; //real no.
float y ; //imaginary no.
public:
complex (float, float);
complex operator + (complex);
void display (void);
};

Nirmala Memorial Foundation Junior College of Commerce and Science Page 62


complex :: complex (float real, float imag)
{
x=real;
y=imag;
}
void complex :: display (void)
{
cout<<x<< “+” <<y<< “i\n”;
}
complex complex :: operator +(complex c)
{
complex temp;
temp. x = x + c.x;
temp. y = y + c.y;
return (temp);
}
void main( )
{
complex c1, c2, c3;
c1 = complex (3.5,2.5);
c2 = complex (1.1, 1.7);
c3 = c1 + c2; //operator function is invoked (activated)
cout<< “c1 =”;

c1. display ( );
cout<< “ c2 =”;
c2. display ( );
cout<< “c3=”;
c3.display ( );
}

Virtual Function
Q What is polymorphism? Explain runtime and compile time polymorphism.
OR
What does polymorphism do in C++? How is the same achieved at (i) Compile time (ii)
Runtime
Ans. :
1. “Polymorphism refers to identically named methods(member functions) that have
different behaviour depending on the type of object they refer.”
2. Polymorphism simply means “one name, multiple forms”
3. The type of polymorphism and their examples are shown in the following figure.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 63


(I) Compile time polymorphism:
1. Function overloading and operator overloading are the examples of compile time polymorphism.
2. In this case, the overloaded member functions are selected for invoking by matching arguments, both
type and number.
3. This information is known to the complier at the compile time and, therefore the compiler is able to
select the appropriate function for a particular call at the compile time itself. This is known as
compile time polymorphism.
4. Compile time polymorphism is also called as early binding or static linking. Early
binding simply means that an object is bound to its function at compile time.

(II) Run time polymorphism:


1. In some situations, it is nice to select appropriate member function to be invoked while the program
is running. This is known as runtime polymorphism.
2. To achieve runtime polymorphism, C++ supports mechanism of virtual functions.
3. At runtime, it is known what class objects are under consideration, the appropriate version of
function is called.
4. Since the functions is linked with a particular class much after its compilation, this process is termed
as late binding. It is also called as dynamic binding because the selection of appropriate function is
done dynamically at runtime.

Q. Explain the difference between static and dynamic binding with example.
Ans. :
1. In static binding, object is bound to its function call at compile time. While in dynamic binding
selection of the appropriate function is done dynamically at runtime.
2. In static binding, compiler knows the function information (argument type, number etc) at the
compile time itself so as to select appropriate function for a particular call (also called early binding).
In dynamic binding, function is linked with a particular class much later after the compilation (also
known as late binding).
3. Function overloading and operator overloading are the examples of static binding. Virtual functions

Nirmala Memorial Foundation Junior College of Commerce and Science Page 64


are used to implement dynamic binding.
4. For Example:
Consider the following class definitions:
class A
{ int x;
public: void show( )
{
cout <<” Base class”;
}
};
class B: public A
{
int y;
public: void show ( )
{
cout<< “Derived class”;
}
};

In above example. compiler does not know which show( ) function is executed either of base class or
derived class. So compiler defers this decision and at the run time select appropriate function using concept
of virtual function.
In dynamic binding, classes are defined as :-
class A
{ int x;
public: virtual void show ( )
{
cout<<” Base class”;
}
};
class B: public A
{ int y;
public: void show( )
{
cout<<” Derived class”;
}
};

Q. Explain the concept of virtual function.


Ans. :
1. When user use the same function name in both the base and derived classes, the function in base
class is declared as virtual using the keyword ‘virtual’ preceding its normal declaration.
2. When a function is made virtual, C++ determines which function to use at runtime, based on the
type of object pointed to the base pointer.
3. Thus, by making the base pointer to point two different objects, it can execute different versions of
the virtual function.
Nirmala Memorial Foundation Junior College of Commerce and Science Page 65
4. Virtual functions can be accessed through the use of a pointer declared as a pointer to the base class.
5. Also, the prototype of the base class version of a virtual function & all the derived class versions
must be identical.
6. If two functions with the same name have different prototype, C++ considers them as overloaded
functions, and the virtual function mechanism is ignored.

Q. State any eight basic rules for virtual functions that satisfy the compiler requirements.
Ans. :
When virtual functions are created for implementing late binding, we should observe following basicrules that
satisfy the compiler requirements:
1. The virtual functions must be members of some class.
2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be a friend of another class.
5. A virtual function in a base class must be defined, even though it is not used.
6. The prototypes of the base class version of virtual function & all derived class version must be
identical. If two functions have different prototypes, then C++ considers them as overloaded
functions & not as virtual functions.
7. We cannot have virtual constructors, but we can have virtual destructors.
8. A base pointer can point to any type of derived object, the reverse is not true. i.e. we cannot use a
pointer to derived class to access an object of the base type.
9. When base pointer is only relative to its base type.
10. Virtual functions are defined in base class; they need not be redefined in derived class.

Inheritance
Q. Explain Inheritance in detail.
Ans. :
Inheritance is the process of creating new classes from an existing class. The existing class is known as the
base class and the newly created class is known as the derived class. The derived classinherits all capabilities
of the base class. It can also add some more features to this class . The base class is unchanged by the process.
The advantages of inheritance are as follows.
 The idea of reusability of the code. Inheritance allows the additional features to an existing class
without modifying it.
 It increases the reliability of the code.
 The major reason behind using inheritance is the capability to express the inheritance relationship
that ensures the closeness with the real-world objects.
 One reason is transitive nature of inheritance. For example, C is a class which is derived from base
class B which itself is a derived class of A, that is, C can also access A (inheritance is transitive)

Syntax:
Class derived classname : visibility mode base classnameExample:
class B
{
int a;

Nirmala Memorial Foundation Junior College of Commerce and Science Page 66


public:int b;
void getdata( ) Private: int a;
{ Public: int b;
a=5;b=6; Void getdata();
} Void show();
void show( )
{
cout<<a<<b;
}
};
class C:public B
{
int c; Private: int c;
public: void mul( ) Public: Void mul();
{ Void display();
c = a*b; int b;
}
Void getdata(); Inherited from
void display ( ) Void show(); class B publicly
{
cout<<c;
}
};
The properties of class B is inherited publicly in class C. So, the member function and data members of
class B are also in class C. This is inheritance. There are different visibility modessuch as private, public
and protected.

Q. Explain different types of inheritance with suitable diagram.


Ans. :
There are different types of inheritance in C++. They are as follows:
i) Single Inheritance:
When a subclass inherits only from one base class, it is known as single inheritance.

A Base class

B Derived class
ii) Multiple Inheritance:
When a derived class inherits from multiple base class, it is known as multiple inheritance.
Base class

A B

C Derived class

Nirmala Memorial Foundation Junior College of Commerce and Science Page 67


iii) Hierarchical Inheritance:
When derived classes inherits only from single base class, it is known as hierarchical inheritance.

A Base class

B C D

Derived class

iv) Multilevel Inheritance:


When a derived class inherits from a class that itself inherits from another class, it is known as
multilevel inheritance.

A Base class

B Derived class of A
Base class of C

C Derived class of B

v. Hybrid Inheritance: (Combination of Hierarchical and Multiple)


When a subclass/derived class inherits from multiple base classes and all of its base classes
inherits from a single base class, this form of inheritance is known as hybrid inheritance.

A
Hierarchical

B C
Multiple

Q. What are the different visibility modes?


Ans. : The different visibility modes are as follows:
1. Public visibility mode-

Nirmala Memorial Foundation Junior College of Commerce and Science Page 68


The public derivation means that the derived class can access the public and protected members of the
base class but not the private members of the base class. The public members of the base class become the
public members of the derived class and protected members become protected. In other words, the public
derivation does not change the specifies for inherited members in the derivedclass.

Example:class A
{
int a;
public: int b;
void getdata( )
{
cout<<”Enter the value of a”;
cin >>a;
}
};

class B: public A
{
public: void putdata( )
{
cout<<”Enter the value of b”;
cin>>b;
}
};
int main ( )
{
B b1;
b1.getdata();
b1.putdata();
return 0;
}
In the program, as we have defined public A for derived class B which means it can access only the
public members of class A and not the private members i.e. it can access getdata( ), int b but not int a
2. Private visibility mode:
The private derivation means the derived class can access the public members of the base class privately.
The public and protected member of the base class becomes private members of the derived class. The
inherited members become private in the derived class, they cannot be to be thebase class of any other class.
Example:
class super
{ private: int x;
void check(int);
Nirmala Memorial Foundation Junior College of Commerce and Science Page 69
public: int y;
void display(void);
protected: int z;
void getval ( );
};
class sub : private super
{
private: int a;
void getdata ( );
public: int b;
protected:int c;
void putdata( );
};

Class super Class sub


private: int x; private: int a, int y ;
void check (int); void getdata();
public: int y; void display(void);
void display(void); public: int b;
void show(); protected: int c;
protected: int z; void putdata();
void getval();

3. Protected visibility mode-


The protected derivation means that the derived class can access the public & private members ofthe base
class protectedly. With protectedly derived class, the public & private members of the derived class become
protected members of the derived class. These members can be inherited further if any classes are inheriting
from the derived class.
Example:
class super
{ private: int x;
void check(int);
public: int y;
void display(void);
protected: int z;
void getval( );
};
class sub: protected super
{
private:int a;
void getdata ( );
public: int b;
protected:int c;
void putdata( );

Nirmala Memorial Foundation Junior College of Commerce and Science Page 70


};
Q. What is Virtual Base Class?
Ans. : An element of ambiguity can be introduced in C++ program when multiple base classes are
inherited. For eg: consider this incorrect program:

#include<iostream.h>
#include<conio.h>
class base
{ public: int a; };
class D1: public base //D1 inherits base
{ public : int b; };
class D2: public base //D2 also inherits base
{ public: int c; };

class D3: public D1, public D2 //D3 inherits D1 and D2


{ public: total; }; //so there are 2 copies of base in D3.
int main ( )
{
D3 ob;
ob.a = 25; //this is ambiguity which a?
//since a is in D2 as well as in D3
//and D3 inherits from both.
ob.b = 50;
ob.c = 75;
ob.total = ob.a + ob.b + ob.c; //a ambiguous
cout<<ob.a<< “/t”<<ob.b<< “/t” <<ob.c<< “/t” <<ob.total <<”/n”; return 0;
}

As both D1 and D2 inherits base, they both have copies of base. However, D3 inherits both D1 and
D2. This means that there are 2 copies of base present in an object of type D3. Therefore, in an
expression like
ob.a = 25;
which “a” is being referred to the one in D1 or the one in D2? Because there are 2 copies of base
present in the object ob, there are 2 ob.a. Thus, the statement is inherently ambiguous.
So there are two ways of remedy.
The first one is to apply the scope resolution operator (::) to “a” and manually select one “a”.
Example:
int main ( )
{
D3 ob;
ob.D1::a = 25; //scope resolution used D1’s “a”
ob.b = 50;
ob.c = 75;
ob.total = ob.D1::a + ob.b + ob.c;
cout<<ob.D1::a<< “/t” <<ob.b << “/t”<<ob.c<< “/t” << ob.total << “/n”

Nirmala Memorial Foundation Junior College of Commerce and Science Page 71


return 0;
}
As scope resolution operator(::) was applied, the propram has manually selected D1’s version of base.
The second one is to declare the class as “virtual”

Example:
#include<iostream.h>
#include<conio.h>
class base
{ public: int a; };
class D1: public virtual base //D1 inherits base as virtual
{ public: int b; };

class D2: public virtual base


{ public: int c; };
class D3: public D1, public D2 //this time, there is only one copy of base
{ public: total; };
int main( )
{
D3 ob;
ob.a = 25; //now unambiguous
ob.b = 50;
ob.c = 75;
ob.total = ob.a + ob.b + ob.c; //unambiguous
cout<<ob.a<< “/t” <<ob.b<< “/t” <<ob.c<< “/t” <<ob.total << “/n”
return 0;
}

The above program produces the following output

25 50 75 150
In the above program, both D1 and D2 have inherited base as virtual, any multiple
inheritance involving them will cause only one copy of base to be present. Therefore, in D3, there is
only one copy of base, therefore ob.a=10 are perfectly valid and unambiguous. Another thing is that
even though both D1 & D2 specify base as virtual, base is still present in any objects of either type.

WORKING WITH FILES


Q. What are input and output streams?
Ans. :
1. The I/O system of C++ handles file operations which are much similar to console input & output
operations.
2. It uses file streams as an interface between the programs and the files.
3. The streams that supplies data to the program is known as input stream, while the stream that
receives data from the program is known as output stream.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 72


4. In other words, input stream extracts (or reads) data from the file and the output stream inserts (or
writes) data to the file.
5. The input operation involves the creation of an input stream and linking it with the program & the
input file.
Similarly, the output operation involves the creation of an output stream and linking it with theprogram & the
output file.

Input stream

Data program
files

File input & output stream


Q. Describe the various classes available for file operations.
Ans. :
1. The I/O system of C++ contains a set of classes that defines the file handling methods. These
include ifstream, ofstream & fstream.
2. These classes are derived from fstream base & the corresponding iostream.h classes.
3. These classes, designed to manage the disk files, are declared in fstream.h & therefore, we must
include this file in any program that uses files.

Q. How we can open a file using open( ) function?


Ans. : We can open file using open( ) by two ways:
a. In first method, open( ) function takes only one argument & that is file name.
This is done as follows:
file.stream_class stream.object
Stream_object.open(“file name”)
E.g. ofstream fout;
fout. Open (“Try”)
b. A file can also be opened using open( ) by passing two arguments. The first argument is file name
and the second argument is used to specify the file mode. The general form of open ( ) with two
arguments is,
Stream_object.open(“Shreyas”,ios::app); This
opens the file in append mode.

Q. What are the different file modes?


Ans. :
1. ios::app--- append to end-of-file.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 73


2. ios::ate--- go to end-of-file on opening.
3. ios::binary--- binary file.
4. ios::in--- open a file for reading only.
5. ios::nocreate--- open fails if the file already exists.
6. ios::noreplace--- open fails if the file already exists.
7. ios::out--- open file for writing only.
8. ios::trunk--- delete contents of file, if it exists.

Q. Explain the purpose of following functions with example.


Ans. :
1. put( ):-
This function is used to store a single character into file, specified by object ofstream. Syntax:-

Example:
ofstream object.put (character variable)
ofstream outf;
outf.open(“xyz”);
char c = ‘A’;
outf.put (c);

2. get( ):-
This function is used to read character from a file, specified by object ifstream. Syntax:

Example:- ifstream object.get (character variable);


char c;
ifstream inf(“xyz”);
while(inf.eof( ) ==0)
{
inf.get (c);
cout<<c;
}

3. write( ) :-
This function is used with object of ofstream & it is used to store data into file in binary mode, that is,
general user cannot read data of file by using ‘type’ command. Here all the variables of different type are
first of all converted into (char*) i.e. pointer to character and second parameter isnumber of bytes required
to store given variable.
Syntax:
write ((char*)& variable, size of (variable);
Example:
struct s;
{
char n[20];
int t;
};

Nirmala Memorial Foundation Junior College of Commerce and Science Page 74


struct s m;
ofsteam outf(“xyz”);
cin>>m.n.;
cin>>m.t;
outf.write((char*)&m, sizeof (m);
}
4. read( ):-
Data which is stored by using write ( ) can be read by using read ( ). This function is used to readin
binary mode from file. This function is associated with ifstream object. Generally read( ) & write( )
functions are used with structures or objects to store the records.
Syntax:
read ((char*)& variable, size of (variable);
Example:
struct s;
{
char n[20];
int t;
};
main( )
{
ifsteam outf(“xyz”);
struct s m;
while(inf.eof( ) ==0)
{
read ((char*)& m, sizeof (m);
cout<<m.n;
cout<<m.t;
}
Q. What are pointers? Give the advantages of using pointers.
Ans. :
1) “A pointer is a variable, which holds the memory address of other variable”
2) * operator is used to declare pointer in C++. It has the syntax

Data type * variable name;


Eg.- int *ptr;

The above declaration will create a variable ptr, which is a pointer variable and which will point to a
variable, whose data type is integer.
1) The data type of ptr is not integer, but data type of variable which ptr will point is integer.
2) Advantages of using pointers are as under:
i) It allows passing variables, arrays, functions, strings, structures, and objects as function arguments.
ii) It allows to return structured variables from functions
iii) It supports dynamic allocation and deallocation of memory segments.
iv) By using pointers, variables can be swapped, without physically moving them

Nirmala Memorial Foundation Junior College of Commerce and Science Page 75


v) It allows to establish link between data elements or objects.

Q. What is call by reference? What is the advantage of call by reference over call by value?
Ans. : A function can be called by two methods:
i) Call by value
ii) Call by Reference
1) When a function call passes arguments by value (call by value) the called function creates a new set
of variables and copies the values of arguments into them.
2) The function does not have access to the actual variables in the calling program and can only work on
the copies of values.
3) Provision of reference variables in C++ permits to pass parameters to the function by reference.
4) When pass arguments by reference (call by reference) the formal arguments in the called function
become alises to the actual arguments in the calling function. This means that when the function is
working with its own arguments, it is actually working on the original data.
5) The mechanism of call by value is good, if the function does not need to alter the values of the
original variables in the calling program.

Example of call by Reference:

#include<iostream.h>
void swap(int*, int*)
void main( )
{
int a,b;
cout<< “Enter 2 nos.”;
cin>>a>>b;
swap(&a, &b); //call by reference
cout<< “a=” <<a;
cout<< “b=” <<b;
}
void swap (int *a, int *b) //function definition
{
int t;
t = *a; //assigns the value at address a to t.
*a = *b; //put the value at b into a.
*b = t; //put the value at t into b.
}

Q. Short Notes on Inline Function:-


Ans. :
1) When a function is called, a lot of time is spent in executing a series of instructions, for task such
as jumping to the function, saving registers and returning to the calling function.
2) C++ provides a solution of inline functions to this problem inline functions makes a program run
faster because the overhead of a function call and return is eliminated.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 76


3) However, it makes program to take up more memory, because the statements that define inline
function are reproduced at each point where the function is called
4) “An inline function is a function that is expanded inline when it is invoked.”
i.e. the compiler replaces function call with the corresponding function code.
5) The inline function are defined (syntax) as follows:

inline function name


{
function body
}
Eg- inline int area (int a, int b)
{
return (a*b);
}
6) The function are generally made inline, when they are small enough to be defined in one or two lines.
7) The keyword inline is not a command, but it is a request to the compiler.
8) Following are some situations in which the compiler may ignore to the compiler.
(i) For functions returning value, if loop, switch or goto statements exists.
(ii) For function not returning value, if a return statement exists.
(iii) If function contain static variables.
(iv) If inline functions are recursive.

Q. Explain the concept of function overloading.


Ans. :
i) “The use of same function name to create functions that perform a variety of different
tasks is called as function overloading”.
ii) Overloading refers to the use of same thing for different purpose. Function overloading is an
example of compile time polymorphism.
iii) Using the concept of function overloading it creates a family of functions with one function name
but with different argument lists.
iv) The function would perform different operation, depending on argument list in function call.
(v) The correct function to be invoked is determined by checking the number and the type of the
arguments and not on the function type.
(vi) Example:

#include<iostream.h> class A
{
public: int area(int s)
{
return(s*s);
}
int area (int l, int b)

Nirmala Memorial Foundation Junior College of Commerce and Science Page 77


{
return (l*b);
}
};
void main( )
{
A a1;
a1.area(5);
a1.area(5,10);
}
In the above program, there are two member function named ‘area’ but with different arguments. When the
main function calls ‘area(5)’, at that time the function which has one argument is invoked (activates) and
when the main function calls ‘area(5,10)’, at that time the function checks the number of arguments and then
the matched argument member function is invoked (activated).
This is, function overloading.

Q. What are default arguments? Give the advantages of using default arguments.
Ans. :
i) C++ allows to call a function without specifying all its arguments. In such case, the function assigns
a default value to the parameter, which does not have a matching argument in the function call.
ii) Default values are specified when the function is declared.
iii) Consider the following function:
float area(int r, float Pi = 3.14);
The above function declares default value 3.14 to the arguments Pi. Suppose, a subsequent function
call like:
A = area(7); //one argument is missing
At this time the value of Pi will be 2.5 and not the default value 3.14.
iv) Advantages of using default arguments:
1) They are useful in situations, where some arguments have same values.
2) It provides better flexibility to programmers by allowing to use particular arguments that are
meaningful to particular solution.
3) Use default arguments to add new parameters to the existing functions.
4) Default arguments can be used to combine similar functions into a single function.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 78


CHP-4. HYPER TEXT MARKUP LANGUAGE (HTML)

Q. What is HTML?
Ans:
1. It is the simplest, text oriented programming language.
2. HTML Stands for HyperText Mark-Up Language.
3. Hypertext is an ordinary text and adding text with extra features such as formatting, images,
multimedia and links to other documents.
4. Markup is the process of taking ordinary text and adding extra symbols, such as editor’s proof
reading symbols. Each of the symbols used for markup in HTML is command that tells the browser
how to display the text.
5. Markup Languages are special type of computer languages. They are concerned with only parts of
documents according to their functions.
6. HTML is not a programming language in real sense.

Q. Explain the Features of HTML.


Ans:
1. Hypertext Markup Language or HTML is a set of codes that is used to create document and then it
can be published on the World Wide Web.
2. HTML lets user jump from topic rather than finding and reading information linearly.
3. Documents prepared in HTML include reference graphics and formatting tags.
4. HTML is hyperlink specification language.
5. HTML supports to frames including target windows and borderless frames.
6. It contains powerful formatting facilities for text, page, images etc.
7. HTML support forms which make it possible to create documents that collect and process user input.
8. This tells how to make a document interactive through special hypertext links.

Q. What are the Advantages of HTML?


Ans:
1. Only Text editor is needed to create the HTML document. No Special software is needed
2. HTML document can be created on any hardware platform using any text editor.
3. HTML is easy to learn, use of implement.
4. It contains powerful formatting facilities.
5. It can update very easily, without changing whole document.
6. Any HTML document can be traversed due to hyper linking.
7. Independent work can be done and no need to worry about editing programs.
8. Finding Errors in HTML is very easy.
9. HTML will not cost anything for its use. There are no expensive licenses to buy or no upgrades.
10. Learning HTML is simple than any programming language.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 79


Q. What are the Disadvantages of HTML?
Ans:
1. HTML is not a Programming language in real sense.
2. Any simple calculation cannot be done in HTML.
3. It cannot be used to display even present date.
4. Interactive web pages cannot be built by HTML.
5. The web pages developed in HTML cannot behave like an application.
6. The web pages developed in HTML do not have their own interface.
7. Hyperlink is provided in HTML. But for that we need a trip to server at each step.

Standard Procedure for creating a Web Page:


1. Type the code in notepad.
2. Save the file as *.html file ( Filename.html )
Note:
1. Extension ( .html ) is mandatory.
2. It is advisable to create a folder and save all you HTML files in one folder.
For the Output:
1. Open the desired browser ( Internet Explorer )
2. Click on File (menu ) -> Open -> Browse -> Select the file -> Click on Open -> Click OK
3. The file will be displayed on the browser.

Q. Give the Structure of HTML.


Ans:
1. Every HTML documents has the same general structure and it consists of few tags that define the
page as a whole.
2. The primary part of an HTML document is denoted by <HTML>. <HEAD> and <BODY> tags.
Each of these tags is known as Document Structure Tags.
3. HTML file always starts with <HTML> tag. Similarly ended with </HTML> tag. It declares the text
within web page viewed in a web browser.
4. HTML document is divided into two sections:
(a) The head : It is like an introduction to the page. It generally consists of title of the page. To
define head , add <HEAD> tag at beginning and </HEAD> tag at end of heading.
(b) The body : In this user enters the text, an images and other tags that will actually appear on the
web page. To define the body, Place <BODY> tag at beginning and </BODY> tag at the end,
after head section.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 80


<HTML>

<HEAD>
<TITLE>

Title of the Document

</TITLE>

</HEAD>

<BODY>

Actual Document

</BODY>

</HTML>

Standard Procedure for creating a Web Page:


3. Type the code in notepad.
4. Save the file as *.html file ( Filename.html )
Note:
3. Extension ( .html ) is mandatory.
4. It is advisable to create a folder and save all you HTML files in one folder.
For the Output:
4. Open the desired browser ( Internet Explorer )
5. Click on File (menu ) -> Open -> Browse -> Select the file -> Click on Open -> Click OK
6. The file will be displayed on the browser.

 List of tags along with its attributes:


<br> Break tag used for inserting new line
<p> paragraph <p>
<hr> Horizontal rule tag used for getting a line
Attributes of Horizontal Rule <HR>
<hr color = “blue” size = 8 width = 50% align = right>
<body bgcolor =”red”>

Nirmala Memorial Foundation Junior College of Commerce and Science Page 81


<body bgcolor = “red” text = “white”>
<body background = “Img name” bgproperties = “fixed”>
</body>
(The Bgcolor option gives background color as red and the text is displayed in white)
(The Background option will use an image as a background while BgProperties option of fixed will
scroll down only the text on the image and not the background image)
<font color = “blue” size = 12 face = “arial black”> ------ </ font>
<b> it makes the text Bold </b>
<I> it makes the text Italic </I>
<u> it underlines the text. </u>

Note: combination of all three can be given


<sup> superscript </sup>
<sub>Subscript </sub>

 P Tag:
<p align = left>
<p align = right>
<p align = center>
<pre> the preformatted text tag
This tag will display the text in the same manner as it has been typed in Notepad
</pre>
<pre></pre>

 Heading Tag:
<h1></h1>
<h2></h2>
<h3></h3>
<h4></h4>
<h5></h5>
<h6></h6>
These tags are used for giving size to the text. <h1> is largest size and <h6> is lowest size.

 Marquee Tag:
<marquee>
<marquee bgcolor=”red”>
<marquee direction=right></marquee>
<marquee direction=left> </marquee>
<marquee direction=up></marquee>
<marquee direction=down></marquee>
</marquee>

LIST
Lists are everywhere on the refrigerator for groceries, on a scratch pad for the to-do lists, in front of
the books for the table of contents etc. hence list are the one of the most natural ways to organize
information.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 82


1) Ordered List <ol>
The <ol> tag helps us to arrange the data in the list format.
The syntax for <ol> tag must be preceded with the <li>i.e list item
e.g
<ol>
<li>Eng
<li> Mar
<il> hin
</ol>
by default the list will be numbered as 1, 2,3….

 Attributes for <ol>


Suppose the user wants the list in Roman numbers

Syntax :
Unorder list <ul></ul>
List item <li></li>
Order list type <ol type =A> (Starts the list from A, B, C…)
Order list type <ol type = a> (Starts the list from a, b, c…)
Order list type <ol type = i> (starts the list from i, ii, iii…)
Order list type <ol type = I> (Starts the list from I, II,III…)

Order list start <ol start =any number> (Starts the list from any number)

Normal Numbered list


<ol>
<li> Food Science and Nutrition
<li> Human Development
<li> Textiles and Clothing
<li> Food Science and Quality Control
</ol>

Roman number list


<ol type =”I”>
<li> Food Science and Nutrition
<li> Human development
<li> Familty Recourse Management
<li> Textiles and Clothing
<li> Food Science and Quality Control
</ol>
</body>
</html>

2) UnOrdered List <ul>


The <ul> tag is similar to the <ol> tag but instead of numbered list the user prefers a bulleted list. The
syntax for <ul> tag must be proceeded with <li> i.e List
There are three type of bullets
Disc •
Circle O
Square

Nirmala Memorial Foundation Junior College of Commerce and Science Page 83


The default will be listed in rounded bullets like this: • Disc bullet
 Attributes for <ul>
Suppose the user wants the square bullet
Syntax
Unorder list <ul></ul>
List item <li></li>
Unorder list type <ul type= disk>
Unorder list type <ul type =square>
Unorder list type <ul type=circle>
E.g
<html>
<head>
<title> Order List </title> </head>
<body>
Unorder list (It uses Square Bullets)
<ul type=square>
<li> Food Science and Nutrition
<li> Human Development
<li> Family Resource Management
<li> Textiles and Clothing
<li> Food Science and Quality Control
</ul>
Unordered List (It uses circle Bullets)
<ul type=circle>
<li> Food Science and Nutrition
<li> Human Development
<li> Family Resource Management
<li> Textiles and Clothing
<li> Food Science and Quality Control
</ul>
</body>
</html>

Tables
The tables can be used to enhance the layout of the text on your page. Tables are used to arrange data in
Row and Column format. In the world of the web , HTML tables have become, one the most useful and
powerful tools for formatting web pages.

The basic syntax for a table

<table>--</table>
<tr>--</tr> (The table row element creates a horizontal row of cells and contains the table headings and table
data.)
<th>--</th> (The Table Heading element creates the heading cells)
<td>--</td> (The Table Data element creates individual cell.)

Sub tags in the table


<table></table>
<table border=1 bordercolor=red>
<table bgcolor=black> (The Table Bgcolor attribute gives background color to the table)
<table cellspacing=10> (Cellspacing attribute creates more space between each cell in the table)
Nirmala Memorial Foundation Junior College of Commerce and Science Page 84
<table cellpadding=10> (Cellpadding attribute increases the space between the cell border and the cell data)
<table width=”100%”> (The Width option is used to increase the size of the table)
Table row <tr></tr>
<tr width=”100%”>
Table Data <td></td>
<td width =”33%”> </td>
<td bgcolor=red>
Table Heading <td></td>
<th width =”33%”></th>
<th bgcolor =red>

<tr> : is Table row


<td> : is table data
<th> : It defines the table heading
<colspan=num of cells> : this merges the number of cells specified column wise
<rowspan=num of cells> : this merges the number of cells specified row wise

In similar manner if you want to align the data within a cell or to the entire column
The syntax is
<td align=center>
Or
<tr align=center>

Note: If alignment is specified in the <tr>, then the data of all the cells in that <tr> i.e Table Row will be
aligned in that <tr> i.e Table Row will be aligned in the specified position

Vertical Alignment:
The tag <valign=”top/bottom/middle>
It will vertically align the data in the cell according to the attribute specified in the tag

Table. Html
E.g
<html>
<head>
<title> Table Spanning </title>
</head>
<body>
<table bgcolor ="red"border=”1” width=100%>
<caption> Marklist </caption>
<tr>
<th> Names </th>
<th> English </th>
<th> Maths</th>
</tr>
<tr>
<td > Reena </td>
<td > 50</td>
<td > 40 </td>
</tr>
<tr>
<td> Seema</td>

Nirmala Memorial Foundation Junior College of Commerce and Science Page 85


<td> 40 </td>
<td>30</td>
</tr>
<tr>
<td colspan=2> Tina </td>
<td>40</td>
</tr>
<tr>
<td colspan=2> Gita</td>
<td> 30 </td>
</tr>
<tr>
<td colspan=3 bgcolor=”black” align=center> <font
color =”red”> <h3> <marquee direction =right> ** Second Year**
</marquee></td>
</tr>
<tr>
<td rowspan=2 colspan=2 valign=top align=righ> Ram </td>
<td> 45 </td>
</tr>
<tr>
<td> Shyam </td>
</tr>
<td> Sam </td>
<td> 45 </td>
<td> 40 </td>
</tr>
<tr>
<td> Tom </td>
<td> 35 </td>
<td> 40 </td>
</tr>
</table>

Anchors and Hyperlinks


HTML or a web page is an Anchored or the Linked page, each link that one views on the web page as
hyperlinked to another page which has some data.

Hypertext is the very essence and heart of the World Wide Web. Without Hyperlinks, the web would
nothing but a bunch of separate, unrelated files. Linking different files into a single unit can be seen on a
small scale in the composition of on HTML page, on a larger scale in the construction of a web site.

 USES OF HYPERLINKS:

Hyperlinks are used in several different ways:


1. Connecting to other HTML pages that are a part of a Web site or to related material from other web
sites. Hyperlinks are most often implemented in this way by using the ANCHOR element.
2. Embedding objects such that as images and sounds, in a HTML page.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 86


Hyperlinks are generally used so that the web site can be broken up into several different HTML pages of all
which are linked to each other. The alternative of having only a single, very long page would be unwieldy
and will definitely have a long download time.

The syntax for Linking a particular word of image is


<a href = “filename.html”> Text </a>
a href stands for Anchored Hyper Reference and if the image has to be linked.
<a href = “filename.html”> < img src= “filename.jpg/gif”> </a>
Ending the Anchored link is important i.e </a>

Images

<Img src = “Img address”>


<Img Src= “Img Address” width =200 height=200>
<img src = “Img address” alt=Img name> (The image name is displayed instead of the image when the
image is not available)
<Img src= “Img address” border = 10>

VB SCRIPT
Q. What is script? Explain VB script. Give one
example. Ans. :
1. A script means a series of commands that will be executed by host environment (Server).
2. Scripting enables us to set and store variables, perform operations on variable .
3. By integrating script, it makes static HTML page active or dynamic, so that is called
asDHTML i.e. dynamic hyper text mark up language.
4. Scripting languages are special programming languages. These are used on web pages
tocontrol different elements of the page including control frames and browser
interface.
5. There are two famous scripting languages:
i) V.B. Script
ii) Java Script

6. VB Script allows web author to write small scripts, that will be executed on users.
7. Another importance of VB script is increased functionality introduced to the web authors
in the form of applet, plugs-in, active x-command and objects. Each of these things can be
usedto add extra functions and interactivity to the web pages.

8. Examples:-
<HTML>
<HEAD>
<TITLE> Hello World </TITLE>
<SCRIPT> Hello World</TITLE>
<SCRIPT LANGUAGE = “VB SCRIPT”>
SUB can ( )
Msg BOX “Hello World”END

Nirmala Memorial Foundation Junior College of Commerce and Science Page 87


SUB
</SCRIP>
</HEAD>
</BODY>
<FORM NAME = “FORM 1”>
<INPUT TYPE = “BUTTON” NAME = “B1”
VALUE =”Click” ONclick = “can( )”>
</FORM>
</BODY>
</HTML>

Q. What is <SCRIPT>
tag?Ans. :
1. The VB SCRIPT can be placed in <SCRIPT> start tag and </SCRIPT> end tag. It contains attribute
LANGUAGE = “VB SCRIPT” as shown:
<SCRIPT LANGUAGE = “VB Script>
<Scripting code>
</SCRIPT>

2. When browser hits <SCRIPT> tag, it calls VB Script.


1. VB Script designed to be fast:
VB Script does not support any strict data type (integer, Characters). The only
dataType available is variant. It is special all purpose data type, which can be used
to Store any kind of data.
2. VB Script is safe:
It provides file system components which consist of objects, which can be used to perform I/O. But,
all languages feature that enable access to local files on which.
Application is running has been removed from VB script to enhance the security.
3. Rich set of functions:
VB Script with rich set of functions for performing various types of operations via. array,
manipulating functions, data and time functions, string functions,
mathematical functions, conversion functions.
4. Error handling:
VB Script allows to access and handle errors through the use of error object.

Q. What are limitations of VB


Script. Ans. :
1. Array handling:
All VB Script arrays are zero based. It does not allows user to change the base of an array variablefor
specific implementation.
2. VB Script cannot create user defined data type:
VB Script provides with certain objects and collections but does not give provision for a user tocreate
user defined data type.
3. Dynamic data exchange:
It is not supported in VB Script as it may violet the integrity of serve.

Nirmala Memorial Foundation Junior College of Commerce and Science Page 88

You might also like