Professional Documents
Culture Documents
com
By:-
-- 03MX
(2003-2006)
This watermark does not appear in the registered version - http://www.clicktoconvert.com
I) Computer Networks - 3 - 40
2
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Part – I
COMPUTER NETWORKS
3
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Topics Covered:-
4
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(i)
Interconnection of autonomous computer . One system cannot force other system to shut
down.
Data Communication is the exchange of data between two devices via some form of
transmission medium.
3. What is Protocol?
Line Configuration refers to the way two or more communication devices attach to a link.
5. What is Link?
Link is the physical communication pathway that transfers data from one device to
another.
i. Point-to-Point
A Point-to-Point line configuration provides a dedicated link between two
devices.
ii. Multipoint
A multipoint line configuration is one in which more than two specific devices
share a single link.
7. What is Topology?
In a Mesh Topology, every device has a dedicated point-to-point link to every other
device.
Advantages:
5
This watermark does not appear in the registered version - http://www.clicktoconvert.com
2] It is robust.
Disadvantages:
The main disadvantage of a mesh is related to the amount of cabling & the number of I/O
ports required.
In a star topology, each device has a dedicated point-to-point link to central controller,
called a hub.
It is used to define the direction of signal flow between two linked devices.
2] In Half-duplex, each station can both transmit and receive, but not at the same
time.
To use connection-oriented service, the user first establishes a connection, uses the
connection and then releases the connection. The sender sends the data in one end, and
the receiver takes them out in the same order at the other end.
In connectionless service, each message carries the full destination address and each
one is routed through the system independent of all the others. Here the Order of injection
is not same as order of delivery.
6
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A device used to connect two separate networks that use different communication
protocols.
A communications device between networks that determines the best path between them
for optimal performance. Routers are used in complex networks of networks such as
enterprise-wide networks and the Internet.
A network traffic monitoring device that controls the flow of traffic between multiple
network nodes.
2] It defines the characteristics of the interface between the devices and the
transmission medium.
The number of bits sent each second is known as transmission rate or data rate.
Note:
Physical Layer -the first layer of the OSI model, responsible for the mechanical and
electrical specifications of the medium.
7
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(ii)
The Data link layer takes the packets it gets from the network layer and
encapsulates them into frames. Each frame consists of
1) Frame Header
2) Payload Field ( for holding the packet)
3) Trailer
3) What are the services provided by Data Link Layer to the Network Layer?
When are they used?
5) What are the different framing methods available with Data link layer?
8
This watermark does not appear in the registered version - http://www.clicktoconvert.com
2) Flag bytes with byte stuffing: Start and end of frames are FLAG bytes. 2
consecutive FLAG bytes denote a frame.
Disadvantage : FLAG byte could also occur as data
Rectified by: Stuffing ESC character before the byte (byte stuffing)
3) Starting and ending flags with bit stuffing : Here , a unique byte
“01111110” is used as frame delimiter.
Disadvantage: The pattern of flag could also occur as data
Rectified by: Stuffing 0 after 5 consecutive 1’s (Bit Stuffing)
4) Physical layer coding violation : This is applicable only for those n/wks
where encoding in physical medium contains some redundancy
7) What are the strategies in Error handling? When are they used?
8) What is a codeword?
A frame of ‘m’ bits of data (message) has ‘r’ redundant bits (check bits). The bit
unit containing data and check bits is called as codeword.
Therefore, codeword n = m + r
From the list of legal codewords, find 2 codewords whose hamming distance is
minimum. This is the hamming distance for the complete code.
9
This watermark does not appear in the registered version - http://www.clicktoconvert.com
They could correct only single bit errors. They can be used to correct burst errors but
then they can correct only one error per code word.
A burst error does not imply that all the bits are wrong but it implies that at least the
first and last are wrong.
Results
10
This watermark does not appear in the registered version - http://www.clicktoconvert.com
4) A polynomial code with r checkbits will detect all the burst errors of
length < r;
17) What does the destination Data link layer do as son as it receives a frame?
This extracts the packet from the frame and passes the packet to destination network
layer.
18) What are the different elementary Data link layer protocols? What are the
assumptions made in each protocol?
11
This watermark does not appear in the registered version - http://www.clicktoconvert.com
20) What is piggy backing? What is its advantage? What is the complication it
introduces?
The complication it introduces is how long the data link layer must wait to send piggy
backed acknowledgements. If it is more than sender’s time out period , frame
retransmitted.
They are bidirectional protocols. At any instant of time , sender maintains a set of
sequence numbers corresponding to frames it is permitted to send. The sender’s window
and the receiver’s window need not have the same lower and upper limit or even have the
same size.
They refer to the Sliding Window Protocol with maximum window size 1. Such protocols
uses stop and wait since sender transmits a frame and waits for its
acknowledgement before sending next one.
The time required for the ack frame to come back to sender is called Round Trip Delay.
The product of Bandwidth and Round Trip delay (bandwidth * Round Trip Delay)
basically tells what the capacity of pipe is and the sender needs the ability to fill it
without stopping in order to operate at higher efficiency. This technique is known as
Pipelining.
24) What are the approaches to deal with errors in presence of Pipelining?
12
This watermark does not appear in the registered version - http://www.clicktoconvert.com
25) What is NAK? What does NAK 2 signify in a) Go Back n and b) Selective
Repeat ?
NAK generally stands for Negative Acknowledgement. It is sent by the receiver to the
sender whenever the receiver encounters an error like checksum error and frame out of
sequence.
a) NAK 2 in Go Back n would cause the sender to retransmit all the frames from
frame no 2
b) NAK 2 in Selective Repeat would cause the sender to retransmit only frame no 2
Transition occurs when a frame is sent, when a frame is sent, when a frame arrives,
when timer expires , when an interrupt occurs etc.
From the initial state ( ie the state corresponding to the description of the system
when it starts running), it could be possible to determine which states are reachable
and which are not. This technique is called Reachability Analysis. Its significance is
determining whether a protocol is correct or not.
This is the situation in which the protocol makes no forward progress (ie deliver
packets to n/w layer) no matter what sequence of events happen. In graph model,
deadlock is characterized by existence of subset of states that is reachable from initial
state and has 2 properties:
i) There is no transition out of subset.
ii) There is no transition in subset that cause forward progress.
13
This watermark does not appear in the registered version - http://www.clicktoconvert.com
This model , like finite state machine is a technique for formally specifying protocols.
A Petri Net has four elements namely :-
Broadcast channels are also called as multi-access channels or random access channels.
E.g.: A conference call involving connection of several telephone lines.
The protocols used to determine who goes next on a multi-access channel belong to a
sublayer of datalink layer called the MAC.
Note:
Many of LANs use multi-access channel as basis for communication.
WAN uses point-to- point links, except for satellite networks.
14
This watermark does not appear in the registered version - http://www.clicktoconvert.com
ADVANTAGES:
Ø There is no interference between users.
Ø When there is small and constant number of users, FDM is simple and effective
mechanism.
DISADVANTAGES:
Ø When some users are quiescent , their bandwidth is simply lost.
Ø They are not applicable to bursty traffics.
Ø Permissions will be denied if there are N users.
3. What are the key assumptions in dynamic channel allocation in LANs and
MANs.
Station Model:
The model consists of N independent stations or terminals. Once frames are generated
here, station is blocked and does nothing until frame successfully transmitted.
Single channel assumptions.
Collision assumption:
When transmitted frames overlap in time, resulting signal is garbled. This event is called
collision.
Carrier Sense: Stations can tell if the channel is in use before using.
No carrier sense: Stations cannot sense the channel before using.
4. What is a “Carrier”?
15
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Systems in which multiple users share a common channel in a way that can lead to
conflicts are widely known as contention systems.
Here the time is divided into discrete interval, each interval corresponding to one frame.
Here a computer is not permitted to send whenever carriage return is typed but is
requested to wait for the beginning of next slot.
In local area networks, it’s possible for stations to detect what other stations are doing
and behave accordingly. protocols in which stations listen for a carrier (ie. A
transmission) and act accordingly are called carrier sense protocols.
Persistent:
Ø When station has data to send , it listens to channel to find whether it is busy.
Ø If busy then station waits until it becomes idle.
Ø When channel idle, station transmits a frame.
Ø If collision occurs, each station waits for a random amount of time and starts all
over again.
Here the station transmits with a probability 1 when channel is idle.
Non-persistent:
Ø Same as former but difference is that:
Ø Whenever the channel is busy, the station does not continually monitor channel
but waits for a random period of time and repeats the algorithm.
P-persistent:
Ø This appears to slotted channels.
Ø When station ready to send and channel idle, transmits with a probability “p”.
Ø With probability of q=1-p, it differs until the next slot.
16
This watermark does not appear in the registered version - http://www.clicktoconvert.com
This stands for carrier sense multiple access with collision detection. whenever the
collisions occur with CSMA and when they are detected, then the transmission is aborted.
The CSMA/CD protocol is widely used in LANs in the MAC sublayer.
They are detected by looking at power or pulse width of the received signal and
comparing it with transmitted signal.
17
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(iii)
1. Which is the lowest layer that deals with end to end transmission?
Network Layer.
If connectionless service is offered in n/w layer, packets are injected into the
subnet individually and routed independently of each other. No advance setup is
needed. These packets are frequently called datagram. And the subnet is called
Datagram Subnet.
In connection oriented service, a path from the source router to the destination
router must be established before any data packet can be sent. This connection is
called a Virtual Circuit.
They change their routing decisions to reflect changes in the topology. It is said to
be Dynamic Routing.
Ex: Distance Vector Routing, Link State Routing.
7. What are the key differences between Distance Vector Routing and Link
State Routing?
Distance Vector Routing:
a. It has knowledge about the whole network.
18
This watermark does not appear in the registered version - http://www.clicktoconvert.com
When too many packets are present in the subnet, performance degrades. It is said
to be congestion.
Congestion control has to do with making sure the subnet is able to carry the
offered traffic. It is a global issue, involving the behavior of all the hosts, all the
routers that store and forwarding processing within the routers.
Flow Control:
Flow Control relates to the pt. to pt. traffic b/w a given sender and receiver. It
makes sure that a fast sender cannot automatically transmit data faster than the
receiver is able to absorb. It gives some direct feedback from receiver to sender.
19
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Computers that inter connect two networks and pass packets from one to the other
is said to be Internet Gateway.
A scheme analogous to physical n/w addressing in which each host on the internet
is assigned a 32 bit integer address is called IP Address.
ARP: Address Resolution protocol is used to associate the 32 bit IP address with the
48 bit physical address, used by a host or a router to find the physical address of
another host. It performs Dynamic Address Resolution.
RARP: Reverse Address Resolution Protocol allows a host to discover is IP
addressing when it knows only its physical address.
The small pieces into which a datagram is divided are called fragments and the
process of dividing a datagram is known as Fragmentation.
Whenever a node injects a datagram into the internet it sets a maximum time that
the datagram should survive. Router and hosts that process datagram must
increment the TTL field as time pass. And it returns the datagram from the
internet when the time expires.
Timestamps give the time and date at which a router handles the datagram,
expressed as milliseconds.
20
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Direct Delivery, the transmission of a datagram from one m/c across a single
physical network directly to another. Indirect Delivery occurs when the
destination is not on a directly attached n/w, forcing the sender to pass the
datagram to a router for delivery.
A datagram travels from router to router until it reaches one that can deliver the
datagram directly into its final destination. If a router cannot route or deliver a
datagram or if the router detects an unusual condition that affects its ability to
forward the datagram, the router needs to inform the original source to take action
to avoid or correct the problem.
Packet Internet Groper, it’s a blind search. It’s a message generated by hosts
which runs IP application without knowing whether the destination is there or not.
PING is followed by an IP address.
Classless Inter Domain Routing, a technique followed in super netting, which treats
IP addresses as arbitrary integers and collapses a lock of contiguous class C number
to a given site or a network within a site. Hosts & Routers that use super netting
should have routing software that understands ranges of addresses.
a. Operates at low level using it requires direct access to the n/w hardware.
b. Requires a packet exchange b/w a client m/c and a computer that answers
to its request.
c. RARP uses a computer’s hardware address to identify the machine.
In BOOTP data are carried in IP, hence data may be lost, corrupted, and out of order.
IP does not provide a checksum for data. To avoid corruption, BOOTP requires that
UDP uses checksum and set don’t fragment bit. Hence it uses the technique Time Out
and Retransmission.
21
This watermark does not appear in the registered version - http://www.clicktoconvert.com
30. What is known as Interior Router Protocol & Exterior Router Protocol?
22
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Network Layer does not see any relationship between the packets of data. It treats
each as an independent entity where as transport layer, packs all the incoming
packets properly (Concatenation) and makes sure that the delivery of an entire
message from source destination. It is said to be End – To – End Delivery.
In Transport layer, the communication is not just from one end machine to other
but from one end application to other end application. Data generated by an
application in one network must be received not just by the other machine but by
the correct application in some other network. So we need to define transport
addresses to which processes can listen for this particular application. It is said to
be Service Access Points or Ports. This kind of addressing is done at the
Transport Layer. It is said to be Transport Service Access Points (TSAP).
36. What are the commonly used protocols in the Transport Layer?
TCP: Transmission Control Protocol
1. It is connection oriented.
2. Designed to provide reliable communication between pairs of processes
across a variety of reliable and unreliable networks.
23
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Clients that take service from the service from the server are said to be Active
Machines. They advertise their routes to others.
Server, that waits for the connection from the other side is said to be Passive
Machine. They listen and update their routes based on advertisement, but they do
not advertise.
The number of hops along a path from a given source to the destination refers to
the number of routers that datagram encounters along the path.
The unit of transfer between the TCP software on two machines is called a
Segment.
They are exchanged to
i. Establish connections.
ii. To transfer data.
iii. To send acknowledgement.
iv. To advertise window size.
v. To close connections.
41. How many hand shakes are used in TCP to establish and close connection?
Window Advertisement specifies how many octets of data the receiver is prepared
to accept. If the receiver’s buffer begins to become full, it sends a smaller window
advertisement. Hence the size of the window changes with time, it is also said to be
Zero Window Advertisement. If the buffer is full in receiver, then the size of the
24
This watermark does not appear in the registered version - http://www.clicktoconvert.com
It is sometimes important that one end of a connection to send data out of band,
without waiting for the program at the other end of the connection to consume
octets already in the stream. The TCP allows the sender to specify data as urgent,
meaning that the receiving program should be notified of its arrival. It is said to be
“Urgent Mode”. When the Urgent Bit is set, the urgent pointer specifies the
position in the segment where urgent data ends.
In the Link State Routing, when a router floods the network with the information
about its neighborhood, it is said to be advertising. The packet send during the
advertisement is said to be Link State Packet.
25
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(iv)
1. What is DNS?
2. When many computers were connected together often host name conflicts were
used to occur.
3. What is Resolver?
4. What is domain?
Com - commercial
Edu - educational institutions.
Gov - Us federal goverment
Mil - armed forces
Int – international organizations.
Name servers:
A single name server can contain the entire DNS data base.
When one server donesnt have the required information it searches for other servers and
gets back the needed information.
26
This watermark does not appear in the registered version - http://www.clicktoconvert.com
9. What is MIME ?
27
This watermark does not appear in the registered version - http://www.clicktoconvert.com
It doesnot delete the mails from the mail box after download instead it assumes that the
mail will exist indefinitely in multiple mail boxes.
It is a small text file stored by the server containing the information about that of the
client with respect to the server.
When a cookie expires in an certain amount of time specified in the date field then it is
said to be persistent cookie.
28
This watermark does not appear in the registered version - http://www.clicktoconvert.com
When one page is viewed often then the some amount of information about the page is
stored in the client. This is used for easy access in the subsequent hits.
It is called as caching.
The server replicates its contents to improve the access. This technique is called as
mirroring.
Mp3
MPEG audio layer 3 .
It is an very popular audio compression technique.
A cipher is a character for character or bit for bit transformation, without regard to the
linguistic structure of the message.
The general symbol for symbol substitution is called a mono alphabetic substitution.
Substitution ciphers preserve the order of the plaintext symbols but disguise them.
Transposition ciphers in contrast, re order the letters but do not disguise them.
Choose an random bit string as key. Then convert the plain text in to bit string. Compute
xor between the two strings. The resulting cipher text cannot be broken because in an
large amount of cipher text each letter will occurs equally often, as will every diagram
and every tri gram and so on.
29
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Cipher modes.
The different types of cipher modes available are,
Electronic code book mode
Cipher block chaining mode
Cipher feed back mode
Stream cipher mode
Counter mode
This scheme is based on the idea of one way hash function that takes an arbitrarily long
piece of plain text and from it computes a fixed length bit string.
The hash function is called as message digest.
Example
Md5
SHA-1
30
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(v)
TCP/IP
1. What is an IP address?
2. IP Address:
starts with netid (bits) hostid (bits)
Class A 0 7 24
Class B 10 14 16
Class C 110 21 8
Class D 1110 Multicast address
Class E 11110 Reserved for future use
Yes. Such hosts are called as Multi- homed hosts. Routers belong to this category.
These multi- homed hosts require multiple IP addresses, where each address
corresponds to one of the machine's network connections.
NOTE:
A broadcast address has hostid with all bits set to 1.A network address has all bits
of hostid equal to 0.
The address resolution protocol (ARP) allows a host to find the physical address
of a target host on the same physical network, given only the target's IP address.
31
This watermark does not appear in the registered version - http://www.clicktoconvert.com
ARP request is broadcasted to all the hosts in the network whereas ARP response
is sent only to the host who broadcasted the request.
6. What is an IP datagram?
The fundamental unit of information passed across any network utilizing Internet
protocol. An IP datagram contains source and destination addresses along with
data and a number of fields that define such things as the length of the datagram,
the header checksum, and flags that indicate whether the datagram can be (or has
been) fragmented.
8. What is a gateway?
A gateway is a computer that lies at the intersection of two networks and routes
traffic correctly from one network to another, while keeping traffic internal to the
two networks separated.
A router is a network device that transmits message packets, routing them over
the best route available at the time. Routers are used to connect multiple network
segments, including those based on differing architectures and protocols. Routers
operate on network layer information and participate in running one or more
network layer routing protocols. Routers use routing tables in determining where
to forward transmissions. Tables for routers include information about different
paths between other routers.
32
This watermark does not appear in the registered version - http://www.clicktoconvert.com
TTL-Time to Live. It specifies the time in seconds for which the datagram is
allowed to stay in the internet. When a router process the datagram header, the
TTL field is decremented by 1.When TTL reaches 0 before the datagram reaches
its destination , the datagram is discarded and an error message is sent to the
source.
12.What is ICMP?
13.What is IP?
Internet Protocol (IP) is the central, unifying protocol in the TCP/IP suite. It
provides the basic delivery mechanism for packets of data sent between all
systems on an internet, regardless of whether the systems are in the same room or
on opposite sides of the world. All other protocols in the TCP/IP suite depend on
IP to carry out the fundamental function of moving packets across the internet.
IP does not guarantee to actually deliver the data to the destination, nor does it
guarantee that the data will be delivered undamaged, nor does it guarantee that
data packets will be delivered to the destination in the order in which they were
33
This watermark does not appear in the registered version - http://www.clicktoconvert.com
sent by the source, nor does it guarantee that only one copy of the data will be
delivered to the destination.
14.What is TCP?
Before sending data across the network, TCP establishes a connection with the
destination via an exchange of management packets. The connection is destroyed,
again via an exchange of management packets, when the application that was
using TCP indicates that no more data will be transferred.
15.What is UDP?
User Datagram Protocol (UDP) provides an unreliable packet zed data transfer
service between endpoints on an internet. UDP depends on IP to move packets
around the network on its behalf. UDP does not guarantee to actually deliver the
data to the destination, nor does it guarantee that data packets will be delivered to
the destination in the order in which they were sent by the source, nor does it
guarantee that only one copy of the data will be delivered to the destination. UDP
does guarantee data integrity, and it does this by adding a checksum to the data
before transmission.
34
This watermark does not appear in the registered version - http://www.clicktoconvert.com
18.What is SNMP ?
19.What is Telnet ?
A source quench message is a request for the host to reduce its current state of
datagram transmission. It is an ICMP message reporting congestion to the source.
The routers send one source quench message for every datagram that they discard.
22.What is a PING?
35
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The ICMP echo request messages are named as ping. A host sends an ICMP echo
request message to a specified destination. The machine that receives the echo
request formulates an echo reply and returns it to the original sender. This
mechanism is used to test whether a destination is reachable and responding.
A port identifies the ultimate destination within a machine. Each port is assigned a
small integer value. A port is what an Internet server uses to distinguish between
requests for different service uses.
24. What is the difference between TCP and UDP if they both operate at the
Transport layer?
Although both TCP and UDP are Transport layer protocols and provide the same
basic function, TCP is a connection-oriented protocol, which means a session is
established before data is transmitted, and acknowledgments are sent back to the
sending computer to verify that the data did arrive and was accurate and complete.
UDP is connectionless; no session, or one-to-one connection, is established prior
to data transmission. This makes UDP the faster of the two, and TCP the more
reliable.
25.What is IPv6?
IP Version 6 (IPv6) is the newest version of IP, sometimes called Ping for "IP,
Next Generation". IPv6 is fairly well defined but is not yet widely deployed. The
main differences between IPv6 and the current widely-deployed version of IP
(which is IPv4) are:
IPv6 uses larger addresses (128 bits instead of 32 bits in IPv4) and so can support
many more devices on the network, and IPv6 includes features like
authentication and multicasting that had been bolted on to IPv4 over the years.
Each application running over TCP or UDP distinguishes itself from other
applications using the service by reserving and using a 16-bit port number.
Destination and source port numbers are placed in the UDP and TCP headers by
the originator of the packet before it is given to IP, and the destination port
number allows the packet to be delivered to the intended recipient at the
destination system. So, a system may have a Telnet server listening for packets on
TCP port 23 while an FTP server listens for packets on TCP port 21 and a DNS
server listens for packets on port 53. TCP examines the port number in each
36
This watermark does not appear in the registered version - http://www.clicktoconvert.com
received frame and uses it to figure out which server gets the data. UDP has its
own similar set of port numbers.
27.What is FTP?
FTP stands for File Transfer Protocol. FTP is the best means for moving large
files across the Internet. FTP is a client/server protocol that enables a user with an
FTP client to log on to a remote machine, navigate the file system of that remote
machine, and upload and download files from that machine. There are two basic
types of FTP on the Internet: Anonymous FTP and Private FTP. With
Anonymous FTP, one logs in as user "anonymous," giving one's email address as
a password. With Private FTP, one logs in with the username and password one
has established on that particular system.
The World Wide Web, which uses Hyper Text Transfer Protocol (HTTP), is a
connectionless client/server protocol that was invented in 1993 by Tim Burners
Lee at CERN. Web servers can deliver a wide variety of media files using MIME.
Web clients, like Netscape and MS Internet Explorer, make requests (i.e., they
send URL's to servers) of Web Servers, to which the Web server responds by
delivering the requested file, running the requested script, or generating an
appropriate error message
37
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Routing algorithms are used to build and maintain the IP routing table on a evice.
There are two primary methods used to build the routing table:
EGP is an exterior gateway protocol , one of the first protocols developed for
communication between autonomous systems. EGP assumes the network
contains a single backbone and a single path exists between any two autonomous
systems. Due to this limitation, the current use of EGP is minimal. In practice,
EGP has been replaced by BGP.
EGP is based on periodic polling using a hello/I-hear-you message exchange.
These are used to monitor neighbor reachability and solicit update responses. The
gateway connecting to an AS is permitted to advertise only those destination
networks reachable within the local AS. It does not advertise reachability
information about its EGP neighbors outside the AS.
38
This watermark does not appear in the registered version - http://www.clicktoconvert.com
All BGP packets contain a standard header. The header specifies the BGP packet
type. The valid BGP packet types include:
• OPEN2: This message type is used to establish a BGP session between two peer
nodes.
• UPDATE: This message type is used to transfer routing information between
BGP peers.
• NOTIFICATION: This message is send when an error condition is detected.
• KEEPALIVE: This message is used to determine if peers are reachable.
The protocol chosen for one type of network may not be appropriate for other
types of networks.
• Scalability to large environments: If support is needed for large, highly-
redundant networks, link state or hybrid algorithms should be considered.
Distance vector algorithms do not scale into these environments.
• Stability during outages: The counting to infinity problems may cause routing
loops or other non-optimal routing paths. Link state or hybrid algorithms reduce
the potential for these problems.
• Speed of convergence: Triggered updates provide the ability to immediately
initiate convergence when a failure is detected. One contributing factor to
convergence is the time required to detect a failure. In OSPF and EIGRP
networks, a series of hello packets must be missed before convergence begins. In
RIP environments, subsequent route advertisements must be missed before
convergence in initiated. These detection times increase the time required to
restore communication.
Others in the list are Ease of implementation, vendor interoperability, metrics etc.
39
This watermark does not appear in the registered version - http://www.clicktoconvert.com
39.What is a firewall?
A firewall is a system (or group of systems) that enforces a security policy
between a secure internal network and an untrusted network such as the Internet.
Firewalls tend to be seen as a protection between the Internet and a private
network. But generally speaking, a firewall should be considered as a means to
divide the world into two or more networks: one or more secure networks and one
or more non-secure networks.
40.Explain HTTP
The hypertext transfer protocol is a protocol designed to allow the transfer of
ypertext Markup Language (HTML) documents. HTTP is based on request-
response activity. A client, running an application called a browser, establishes a
connection with a server and sends a request to the server in the form of a request
method. The server responds with a status line, including the message's protocol
version and a success or error
code, followed by a message containing server information, entity information
and possible body content.
An HTTP transaction is divided into four steps:
1. The browser opens a connection.
2. The browser sends a request to the server.
3. The server sends a response to the browser.
4. The connection is closed.
40
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Part – II
DATABASE
MANAGEMENT
SYSTEM
41
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Topics Covered:-
ii) Storage, File Structure, Indexing (Hash based & Tree structure)
- Geethavahini N
42
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(i)
2. What is a Database?
3. What is DBMS?
43
This watermark does not appear in the registered version - http://www.clicktoconvert.com
ü Data independence.
ü Speedy handling of spontaneous request – real time
ü Controlled redundancy
ü Versatility in representing relationships between data items
ü Security protection
ü Real time accessibility
ü Reduction of redundancy
ü Shared data
ü Integrity
ü Security
ü Conflict resolution
ü Data isolation
ü Data independence
44
This watermark does not appear in the registered version - http://www.clicktoconvert.com
10. What is a data model? What are the different kinds of data models?
Data model is a type of abstraction that models data and their relationship. Data
model hides storage and implementation details (hence abstraction).
The different kinds of data models are
Primitive data model – File based
Traditional data model – Hierarchical data model
Network data model
Relational data model
Semantic data model - AI based
The goal of the three-schema architecture is to separate the user application and the
physical database. In this architecture, schemas can be defined at the following three
levels:
Ø The Internal level – Has an internal schema, which describes the physical storage
structure of the database.
Ø The Conceptual level – Has a conceptual schema, which describes the structure
of the whole database for a community of users.
45
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Some data are referred very frequently and others only occasionally. The process
of adjusting the storage of data to suit its popularity rating is called Data Migration.
In some cases the physical location of data is changed to archive storage. In some
cases the reference to them in the indices which are used for addressing them are changed
so that hey can be found more quickly.
People who are associated with the design, development and operation of the DBMS
software and system environment but not interested in the database itself are known as
‘Workers behind the Scene’.
Some of them are,
Ø DBMS system designers and implementers – persons who design and implement
the DBMS modules and interfaces as a software package.
Ø Tool developers – The persons who design and implement tools – the software
packages that facilitates database system design and use, and help improve performance.
46
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The Data referred which is not in the main memory at that time of reference is Virtual
data.
Transparent data appears not to exist but in fact it does exist. (Many of the complex
mechanisms used in the data storage and data transmission can be hidden from the
programmer so that he does not have to understand or even know about them.)
47
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Ø Multi-valued attributes – Attributes that can have a set of values for the same
entity Ex: Color of car painted in two colors
Ø Derived attribute - Attribute whose value can be derived from another attribute
Ex: Age can be derived from date of birth
Ø Stored attribute – Attribute from which other attribute values can be derived Ex:
Date of birth from which age can be derive
Ø Complex attributes – Attributes in which composite and multi- valued attributed
are nested
Ex: A person having more than one residence and each have more than one phone
number
Ø Entity types – An entity type defines a collection of entities that have the same
attributes
Ø Entity sets – The collection of all entities of a particular entity type in the
database at any point in time
An attribute of an entity type is associated with value set (domain of values), which
specifies the set of values that may be assigned to that attribute for each individual entity.
Relationship types usually have certain constraints that limit the possible
combinations of entities that may participate in the corresponding relationship set.
Two main types of relationship constraints are:
· Cardinality Ratio
· Participation
48
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Entity types that do not have key attributes of their own are called weak entity
types. In contrast, regular entity types that do have a key attribute are called strong
entity types.
Weak entity types are identified by being related to specific entities from another
entity (identifying or owner entity type) in combination with some of their attribute
values.
A weak entity type always has a total participation constraints with respect to its
identifying relationship, because a weak entity cannot be identified without an owner
entity.
An entity type usually has an attribute whose values are distinct for each
individual entity in the collection. Such an attribute is called a key attribute and its
values can be used to identify each entity uniquely.
(1) Candidate key - If a relation schema has more than one key, each is a candidate key.
(2) Primary key - One of candidate keys is arbitrarily designated to be the primary key.
(3) Superkey – A superkey of a relation schema R = { A1,A2,….An } is a set of
attributes
S ÍR with the property that no two tuples t1 ant t2 in any legal relation state r of
R will have t1[S] = t2[S]. A key K is a superkey with the additional property that removal
of any attribute from K will cause K not to be a superkey anymore.
(4) Foreign key – A foreign key specifies a referential integrity constraints between the
two relation schema R1 and R2.
49
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The usage of pointers and high complexity are demerits of hierarchical and network
model. The relational model represents the database as a collection of relations. Each
relation resembles a table of values or, to some extent, a flat file of records.
The two constraints of a relational model are unique identification and non-
redundancy.
Unique Identification:
Each tuple of the relation should be uniquely identifiable by means of a special
attribute known as key(s). No two rows can have the same key.
Non-Redundancy:
No attribute that a part of a key can be removed without destroying property of
unique identification. The key should be minimal.
Entity Integrity contraint states that no primary key value can be null.
Referential Integrity contraint states that a tuple in one relation that refers to another
relation must refer to an existing tuple in that relation.
It is procedural query language. It consists of a set of operations that take one or two
relations as input and produce a new relation.
50
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Union
A binary operator for which arity of both the relations must be same. It gives a
relation of the same arity with set of all tuples in both the operand relations. Ex: RUS
Difference
A binary operator for which arity of both the relations must be same. Ex: R-S. It
gives a relation of the same arity that contains all tuples in R but not in S.
Cartesian product
A binary operator. Ex: RXS. It is a typical cross product o two relations R, S.
Thus, if arity( R ) = K1, arity ( S ) = K2, then arity ( RXS ) = K1+K2.
Projection
The project operation selects certain columns from the table and discards the
other columns.
Selection
The select operator is used to select a subset of the tuples from a relation that
satisfy a selection condition.
41. What are the advanced level operations in Relational algebra? Explain.
Intersection
A binary operator for which arity of both the relations must be same. It gives a
relation of the same arity with set of tuples which are comman in both the operand
relations. Ex: RnS
Quotient
A binary operator. Let R be of arity r and S be of arity s where r>s (pre requisite).
Then R÷S is a set of all (r-s) tuples t such that for all s tuples u in S, the tuple tu is in R.
Join
A join operation is used to combine related tuples from two relations into single
tuple.
Ø Theta join – A join operation with general join condition. [ σ (R X S) ]
( σ – Condition)
Ø Equi-join – A join operation with only comparison operators in
condition.
Ø Natural join – A join operation based on a common column that have
same values in both the relations. [ σ <R.b=S.b>(R X S)]
51
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Tuple Relational Calculus - A Query framed in TRC has the following syntax.
{ t/ p(t) } i.e, the formula retrieves the set of tuples formula p(t) is satisfied.
Domain Relational Calculus - DMC has the following syntax
{ <x1,x2,x3….,xn> | p(x1,x2,x3….xu) }
A varient of join that keeps all pieces of information from the operands.
It “pads with nulls” the tuples that have no counterpart
Three pads:
left : only tuples of the first operand are padded
right : only tuples of the second operand are padded
full : tuples of both operands are padded
The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted
values are tuples of that relation. Ex: QUEL
The domain-oriented calculus has domain variables i.e., variables that range over the
underlying domains instead of over relation. Ex: ILL, DEDUCE.
The universal quantifier, ("t)(F) is true if every possible tuple that can be
assigned to free occurrences of t in F is substituted for t and F is true for every such
substitution. It is called universal quantifier because every tuple in “the universe of “
tuples must make F true to make the quantified formula true.
52
This watermark does not appear in the registered version - http://www.clicktoconvert.com
49. How domain relational calculus is different from tuple relational calculus?
The domain calculus differs from the tuple calculus in the type of variables used
in formulae: rather than having variables range over tuples, the variables range over
single values from domains of attributes.
The oracle data dictionary is read-only set of tables that keeps the metadata- i.e ,
the schema description for a database.
The term schema refers to a collection of data definition objects. Schema objects
are the individual objects that describe tables, views etc. There is a distinction between
the logical schema objects and the physical storage components called tablespaces.
Oracle constantly monitors database activity and records in tables called Dynamic
Performance tables.
53
This watermark does not appear in the registered version - http://www.clicktoconvert.com
· Queries are translated by the query optimizer into the procedural language
internal to the DBMS
· The programmer should focus on reliability, not on effiency.
Assertions are used to specify more general constraints. Each assertion is a given
a constrained name and is specified via a condition similar to where clause in an SQL
query.
Ex:
CREATE ASSERTIONS SALARY_CONSTRAINT
CHECK ( NOT EXISTS (SELECT * FROM EMPLOYEE E, EMPLOYEE
M, DEPARTMENT D WHERE E.SALARY>M.SALARY AND
E.DNO=D.DNUMBER AND D.MGRSSN=M.SSN));
54
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Ex:
void DisplayDepartmentSalaries(char DeptName[])
{
char FirstName[20], Surname[20];
long int Salary;
$ declare DeptEmp cursor for
select FirstName, Surname, Salary
from Employee
where Dept = :DeptName;
$ open DeptEmp;
$ fetch DeptEmp into :FirstName, :Surname, :Salary;
printf(“Department %s\n”,DeptName);
while (sqlcode == 0)
{
printf(“Name: %s %s ”,FirstName,Surname);
printf(“Salary: %d\n”,Salary);
$ fetch DeptEmp into :FirstName, :Surname, :Salary;
}
$ close DeptEmp;
}
55
This watermark does not appear in the registered version - http://www.clicktoconvert.com
56
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Each database must contain one or more rollback segments, which are used for
“undoing” transactions. A rollback segment records old values of data that are used to
provide read consistency to rollback a transaction and for recovering a database.
A cursor is similar to a file variable or file pointer, which points to a single row
from the result of a query. Cursors are controlled by three commands – OPEN, FETCH
and CLOSE.
57
This watermark does not appear in the registered version - http://www.clicktoconvert.com
58
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(ii)
Off- line data: data stored on tapes, on- line data: data stored in disk.
It contains a bank of tapes that are catalogued and can be automatically loaded onto
tape drives and are becoming as a Tertiary Storage.
For Example: NASA's EOS (Earth Observation Satellite) system stores archived
data in this fashion.
“Time taken to position the read/write head on the track containing data".
"The beginning of desired block rotates into position under the read/write head."
9. What is Data Striping?
59
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Its Goal: To make the wide different rates of performance improvements of disks
even against those in memory and micro processor.
Given a key, the hash function resolves and returns the address of a record.
60
This watermark does not appear in the registered version - http://www.clicktoconvert.com
It is an ordered file with a multi level primary index on its ordering key field
It is slightly different from a multilevel index with order p such that each node contains
at most p-1 search values and p pointers.
B-tree when used as an access structure on a key field to search records in a data
file can be defined as follows:
Ø Each node has almost p tree pointers
Ø Each node is of the form <P1, <K1,Pr1>,P2,<K2,Pr2>………….< Kq-
1,Pprq-1>,Pq> where Pi is a tree pointer and Pri is a data pointer, Ki is
the node.
Ø Each node, except the root and leaf nodes has at least p/2 tree pointers.
Ø All leaf nodes are at the same level.
B-tree is a balanced tree structure in which each node is atleast half full.
61
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Collection of operations that for a single logical unit of work are called
transactions. In other words, a transaction is a unit of program execution that
accesses and possibly updates various data items.
ü Active
ü Partially committed
ü Failed
ü Aborted
ü Committed
During the transaction failure, either we can restart the transaction or kill the
transaction.
62
This watermark does not appear in the registered version - http://www.clicktoconvert.com
When a transaction needs to update the db, then it can set the lock, and proceed.
When the db is locked be one transaction, the other can’t access the db. Once the
transaction gets over, the lock will be released and the other transactions can
access it.
Each transaction in the system follows a set of rules called locking protocol,
indicating when a transaction may lock and unlock each of the data items.
63
This watermark does not appear in the registered version - http://www.clicktoconvert.com
ü Locking protocol
ü Graph-based protocol
ü Timestamp-based protocol
ü Validation-based protocol
One approach ensures that no cyclic waits can occur by ordering the
request for locks or requiring all locks to be acquired together. The other approach
is closer to deadlock recovery, and performs transaction rollback instead of
waiting for a lock, whenever the wait could potentially result in a deadlock.
The transactions are sketched as a wait- for- graph and check for a presence of a
cycle.
Recovery from Deadlock involves the following steps:
ü Selection of a victim (the transaction which is responsible for deadlock)
ü Rollback
18) List the classification of a db system failure.
· Transaction Failure
o Logical Error: The transaction can no longer continue with its normal
executing because of some internal conditions, such as bad input, data not
found, overflow or resource limit exceeded.
o System Error: The system has entered an undesirable state like deadlock.
· System Crash:
o There is a hardware malfunction or a bug in the db software or the os, that
causes the lost of the content of volatile storage and brings transaction
processing to a halt.
· Disk Failure:
o A disk block loses its content as a result of either a head crash or failure
during a data transfer operation.
19) Which are all the storage types used for db?
Based on the relative speed, capacity and resilience to failure I is classified
as follows:
· Volatile storage
· Non volatile storage
· Stable storage
64
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(iv)
DATABASE DESIGN & TUNNING (NORMALIZATION &
DENORMALIZATION)
1).What are the Phases involved Database Application System Life Cycle?
a. System definition: the scope of database system, its users, and its applications are
defined.
b. Database design: At the end of this phase, a complete logical and physical design of
the database system on the chosen DBMS is ready.
c. Database implementation: specify the conceptual, external, and internal database
definitions, creating empty database files, and implementing the software applications.
d. Loading or data conversion: the database is populated either by loading the data
directly or by converting existing files into the database system format.
e. Application conversion: any software applications from a previous system are
converted to the new system.
f. Testing and validation: the new system is tested and validated.
g. Operation: the database system and its applications are put into operation.
h. Monitoring and maintenance: the system is constantly monitored and maintained.
Growth and expansions can occur in both data content and software applications.
65
This watermark does not appear in the registered version - http://www.clicktoconvert.com
b. Maintenance cost: This is the recurring cost of receiving standard maintenance service
from the vender and for keeping the DBMS version up to date.
c. Hardware acquisition cost: New hardware may be needed, such as additional memory,
terminals, disk units, or special DBMS storage.
d. Database creation and conversion cost. This is the cost of either creating the database
system from scratch or converting an existing system to the new DBMS software.
e. Personnel cost: Acquisition of DBMS software for the first time is often accompanied
by hiring new database people.
f. Training cost. Because DBMSs are often complex systems, personnel must often be
trained to use and program the DBMS.
g. Operating cost. The cost of continued operation of the database system is typically not
worked into an evaluation of alternatives because it is incurred regardless of the DBMS
selected.
Logical database design is called the Data Model Mapping. The Mapping can be carried
out in two phases.
System independent mapping: the mapping does not consider any specific characteristics
or special cases that apply to the DBMS implementation of the data model.
Tailoring the schemas to a specific DBMS: we may have to adjust the schemas obtained
in stage 1 to conform to the specific implementation features of a data model as used in
the selected DBMS.
6).What is a Physical database design?
Physical database design is the process of choosing specific storage structures and access
paths for the database files to achieve good performance for the various database
applications. Each DBMS offers a variety of options for file organization and access
paths. These usually include various types of indexing, clustering of related records on
disk blocks, linking related records via pointers. Once a specific DBMS is chosen, the
physical database design process is restricted to choosing the most appropriate structures
for the database from among the options offered by that DBMS.
7).What are the Elements of a Good Database Design ?
66
This watermark does not appear in the registered version - http://www.clicktoconvert.com
This is the elapsed time between submitting a database transaction for execution and
receiving a response. A major influence on response time is under the control of the
DBMS is the database access time for data items referenced by the transaction. Response
time is also influenced by factors not under DBMS control, such as system load,
operating system scheduling, or communication delays.
Space utilization: This is the amount of storage space used by the database files and their
access path structures.
This is the average number of transactions that can be processed per minute by the
database system; it is a critical parameter of transaction system such as those used for
airline reservations or banking. Transaction throughput must be measured under peak
conditions on the system. Typically, average and worst-case limits on the preceding
parameters are specified as part of the system performance requirements. Analytical or
experimental techniques, which can include prototyping and simulation, are used to
estimate the average and worst-case values under different physical design decisions, to
determine whether they meet the specified performance requirements.
Disadvantages are
i. Foreign keys that are based on surrogate keys have no meaning to the users.
ii. When data shared among different databases contain the same ID, merging
those tables might yield unexpected results.
If the parent in an ID-dependent relationship has a surrogate key as its primary key, but
the child has a data key, use the parent’s surrogate key as a primary key. A mixture of a
surrogate key with a data key does not create the best design as the composite key will
have no meaning to the users. Therefore, whenever any parent of an ID-dependent
relationship has a surrogate key, the child should have a surrogate key as well. By using
67
This watermark does not appear in the registered version - http://www.clicktoconvert.com
surrogate keys in the child table, the relationship type has changed to
1:N non- identifying relationship
If default referential integrity constraint is too strong, overriding the default referential
integrity enforcement could be defined during database design. The policy will be
programmed into triggers during implementation.
1).Cascading updates: automatically change the value of the foreign key in all related
child rows to the new value
2).Cascading deletions: automatically delete all related child rows
When enforcing the minimum cardinality between the child and the parent, a required
child can be represented by creating update and delete referential integrity actions on the
child and insert referential integrity actions on the parent. Such referential integrity
actions must be declared during database design and trigger codes must be written during
implementation
68
This watermark does not appear in the registered version - http://www.clicktoconvert.com
i. MUST NOT constraint: the binary relationship indicates combinations that are
not allowed to occur in the ternary relationship
ii. MUST COVER constraint: the binary relationship indicates all combinations
that must appear in the ternary relationship
iii. Because none of these constraints can be represented in the relational design,
they must be documented as business rules and enforced in application programs
or triggers
DATABASE TUNING
• Troubleshooting:
Make managers and users happy given an application and a DBMS
•Capacity Sizing:
Buy the right DBMS given application requirements
• Application Programming:
Coding your application for performance
69
This watermark does not appear in the registered version - http://www.clicktoconvert.com
· One of the goals of tuning an Oracle8i server is to ensure that SQL statements
access the smallest possible number of Oracle blocks needed to complete their
work. This speeds up the response time for the statement and reduces the impact
on other queries and data manipulation language (DML) statements being
executed in the database.
· Another goal of tuning is to ensure that frequently used data blocks are cached in
memory. Data blocks cached in memory can be readily accessed. The availability
of needed data in memory reduces the number of overall physical reads.
· An additional goal of tuning is to ensure that users share code, such as frequently
used SQL statements, within memory areas. This helps to avoid reparsing and
duplicate storage of such SQL statements.
· A further goal of tuning the Oracle8i server is to ensure that reading and writing
are performed as rapidly as possible. For example, separating different segment
types across tablespaces can minimize write contention. Maximizing the number
of blocks that are obtained during a read operation minimizes the number of read
operations required.
· Minimizing or preventing contention for resources is another goal of Oracle8i
server tuning. Good application tuning and database design help ensure that users
have access to data when required.
· Finally, the database should be tuned to optimize the speed in which backup
procedures and housekeeping tasks are performed. This protects data and
minimizes the impact of those tasks on database performance.
70
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Everyone involved with the system has some role in the tuning process. When people
communicate and document the systems characteristics, tuning becomes significantly
easier and faster.
· Business executives must define and then reexamine business rules and
procedures to provide a clear and adequate model for application design. They
must identify the specific kinds of rules and procedures that can influence the
performance of the whole system.
· Application designers must design around potential performance bottlenecks.
They must communicate the system design so that everyone can understand the
flow of data in an application.
71
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Decisions made in application development and design have the most impact on
performance. Once the application is deployed the database administrator usually has the
primary responsibility for tuning--within the limitations of the design.
10).Is it necessary for setting the performance goal of the system while tuning?
Brief.
When designing the system, we should set a specific goal: for example, an order entry
response time of less than three seconds. If the application does not meet that goal,
identify the bottleneck causing the slowdown (for example, I/O contention), determine
the cause, and take corrective action. During development, you should test the application
to determine if it meets the designed performance goals before deploying the application.
With clearly defined performance goals, we can readily determine when performance
tuning has been successful. Success depends on the functional objectives we have
established with the user community, our ability to objectively measure whether or not
the criteria are being met, and our ability to take corrective action to overcome any
exceptions. The rest of this tuning manual describes the tuning methodology in detail,
with information about diagnostic tools and the types of corrective actions we can take.
DBAs who are responsible for solving performance problems must keep a wide view of
the all the factors that together determine response time. The perceived area of
performance problems is frequently not the actual source of the problem. Users in the
preceding example might conclude that there is a problem with the database, whereas the
actual problem is with the network. A DBA must monitor the network, disk, CPU, and so
on, to find the actual source of the problem--rather than simply assume that all
performance problems stem from the database. Ongoing performance monitoring enables
you to maintain a well tuned system. Keeping a history of the application's performance
over time enables you to make useful comparisons. With data about actual resource
72
This watermark does not appear in the registered version - http://www.clicktoconvert.com
consumption for a range of loads, you can conduct objective scalability studies and from
these predict the resource requirements for load volumes you may anticipate in the future.
12).What are the basic methodology involved in tuning the Database Server and
Clients?
Determine the level of tuning - Component- level tuning or system- level tuning? Do you
want to tune the database server as an isolated component or as part of a larger
application?
Understand the end-user community - Gather metrics regarding the manner in which
the database will be accessed. What SQL queries will be executed? What business
transactions will be executed? How often are transactions executed?
Gather performance requirements - Determining the exit criteria for tuning needs to be
established in order to know when sufficient testing has occurred.
Automate test scripts - Create automated test scripts that issue the necessary SQL
queries, updates and deletes. Generate automated test scripts that emulate the business
scenarios.
Execute & analyze tests - Run the planned tests and collect metrics, such as response
times, transaction volumes, operating system statistics, database server statistics.
As a result of Database Tuning the database server capability and scalability is increased
by addressing:
a. The use of a small packet size between the client and the server.
b. Chatty conversation over high latency network links.
c. Large amounts of unused data returned to the client.
d. Redundant database queries. additional tuning methods.
The system architect communicates information about the Oracle8i database design to the
database administrator (DBA) and the application developer. The database design
includes the logical structure of the database along with database size information. The
database must be designed correctly to ensure that database performance does not
deteriorate. It is difficult to tune an Oracle8i database that is based on a poor design.
Often, an application designer performs some of the system architect's duties, focusing
only on the logical structures and sizing involved with the applications as they are
73
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A DBA's tuning responsibility is to configure the database and monitor and document
system activity, so that system performance problems can be identified and corrected as
quickly as possible.
A hardware/software administrator documents and communicates the configuration of the
system environment in which the database and application reside. The configuration is
communicated to the system architect, the DBA, and the application developer. This
helps in designing and administering the system effectively.
If a query runs slower than expected, check if an index needs to be re-built, or if statistics
are too old.
Sometimes, the DBMS may not be executing the plan
you had in mind. Common areas of weakness:
–Selections involving null values.
–Selections involving arithmetic or string expressions.
–Selections involving OR conditions.
–Lack of evaluation features like index-only strategies orcertain join methods or poor size
estimation
Check the plan that is being used then adjust the choices of indexes or rewrite the
Query/Views.
74
This watermark does not appear in the registered version - http://www.clicktoconvert.com
19).What are the ways of achieving refined conceptual schema in terms of Tuning?
75
This watermark does not appear in the registered version - http://www.clicktoconvert.com
22).What is Normalization?
1NF: The domain of attribute must include only atomic (simple, indivisible) values.
2NF: A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R
is fully functionally dependent on primary key.
3NF: A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the
following is true,
X is a Super-key of R.
A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
24).What is BCNF?
25).What is 4NF?
26).What is 5NF?
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn}
that holds R, one of the following is true:
76
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Ri = R for some i.
The join dependency is implied by the set of FD, over R in which the left side is
key of R.
A relation is said to be in DKNF if all constraints and dependencies that should hold on
the the constraint can be enforced by simply enforcing the domain constraint and key
constraint on the relation.
30).How will you Denormalize Contracts (Cid, Sid, Jid, Did, Pid, Qty, Val) into
BCNF.
There are 2 ways to decompose CSJDPQV into BCNF:
–SDP and CSJDQV; lossless-join but not dependent-preserving.
–SDP, CSJDQV and CJP; dependent-preserving as well
77
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(v)
SQL REFRESHER
‘||’
eg: select lastname || ‘works in ‘ || compname from employees.
It’s same as concat.
IN (set)
eg: select name from employees where name like ‘%sa\_%’ escape ‘\’;
‘ \’ -escape sequence
IS NULL
Logical operators:
AND,OR,NOT
Sorting:
ORDER BY [DESC}
78
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Ø Character Functions:
o Case Manipulation:
§ LOWER (‘attr’)
§ UPPER(‘attr’)
§ INITCAP(‘attr’)
o Character manipulations
§ CONCAT
§ SUBSTR
§ LENGTH
§ INSTR- instr(column,string,[m],[n])
§ LPAD/RPAD –lpad/rpad(column,n,string)
§ TRIM-trim(‘H’ from “hello world”)
§ REPLACE – replace(text,search-string,replacement-string)
Ø Number functions:
o Round(column, n)
o Trunk(column, n)
o Mod(m, n)
Ø Date functions:
o months_between (date1,date2)
o add_months (date,n)
o next_day(date,’char’)
o last_day(date)
o round(date,[format])
o trunc(date,[format])
79
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Ø Conversion functions:
o To_char (date,’format_model)
Format model: {yyyy,year,month,mon,dy,day,dd}
o to_char(number,’format_model’)
Format model: {9 L 0 $ . ,}
o To_number(char,’format_model’)
o To_date(char,’format_model’)
Ø General functions:
o NVL(expr1,expr2)
o NVL2(expr1,expr2,expr3)
o NULLIF(expr1,expr2)
o Coalesce(expr1,expr2…,exprn) -- return 1st not
null in expr list.
o NVL(jobid,’No job yet’)
· Case:
Eg: case expr when comp_expr1 then return expr1
[when..
when
else else – expr]
· Decode:
Eg: select name,salary decode(trunk(salary,
OUTER JOIN:
Put (+) on the side that is deficient in information.
Eg:
Select tab1.col, tab2.col from table1, table2 where tab1.col=tab2.col(+)
SELF JOIN:
Eg:
select work.last_name ||’works for’|| manager.lastname from employee
work,employee manager where work.manager_id=manager.employee_id.
NATURAL JOIN:
Eg:
-- Select deptid,deptname,locid,city from department NATURAL JOIN locations
80
This watermark does not appear in the registered version - http://www.clicktoconvert.com
81
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Some commands:
DDL commands;
- create
- alter
- drop
- rename
- truncate
- comment
Constraints:
Not null
Unique
Primary key
Foreign key
Check
82
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Part – III
OPERATING
SYSTEM
83
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Topics Covered:-
84
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(i)
Operating system controls and coordinates the use of the hardware among the various
applications programs for various uses. Operating system acts as resource allocator and
manager. Since there are many possibly conflicting requests for resources the operating
system must decide which requests are allocated resources to operating the computer
system efficiently and fairly. Also operating system is control program which controls the
user programs to prevent errors and improper use of the computer. It is especially
concerned with the operation and control of I/O devices.
A file management system is a set of system software that provides services to users and
applications related to the use of files.
· To meet the data management needs and requirements of the user and the ability
to perform various operations.
· To guarantee, to the extent possible that the data in the files are valid.
· To optimize performance
· Tp provide I/O support for a variety of types of storage deivces.
· To minimize or eliminate the potential for lost or destroyed data.
· To provide a standardized set of I/O interface routines.
· To provide support for multiple users.
Fixed blocking: Records of fixed length are used. An integral number of records are
stored in a block. There may be unused space at the end of each block.
Variable-length spanned blocking: Variable length records are used and are packed
into blocks with no unused space. Thus, some records may span 2 blocks.
Variable-length unspanned blocking: Here the records are of variable length but the
records cannot span over a block. Thus, the length of a record cannot be greater than 1
block.
85
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A pre-allocation policy would require that the maximum size of the file be declared at the
time of the file creation request. A dynamic allocation policy allocates space to a file in
portions as and when required.
Multiple disks can be used to store a single file by a technique called disk inter- leaving or
disk stripping. A group of disks are said inter- leaved if successive portions of a file are
stored on different disks. Since a file is stored across many disks, any request for file I/O
tends to be uniformly distributed across all the disks, hence yielding a better throughput
and improved response time.
Just as a file should be opened before it is used, a file system must be mounted before it
can be available to the processes on the system. To mount a file system, the name of the
device and the location within the file system is given to the operating system.
The location within the file structure at which we attach the file system is called as the
mount point. Typically, a mount point is an empty directory at which the mounted file
system will be attached.
Input spooling takes the information from the input device, prepares the job for
scheduling, and places an entry in a job queue. Using input spooling, you can usually
shorten job run time, increase the number of jobs that can be run sequentially, and
improve device throughput.
Job queue
An ordered list of batch jobs submitted to the server for running and from which
batch jobs are selected to run.
Reader
A function that takes jobs from an input device or a database file and places them
on a job queue.
When a batch job is read from an input source by a reader, the commands in the input
stream are stored in the server as requests for the job, the inline data is spooled as inline
data files, and an entry for the job is placed on a job queue. The job information remains
86
This watermark does not appear in the registered version - http://www.clicktoconvert.com
stored in the server where it was placed by the reader until the job entry is selected from
the job queue for processing by a subsystem.
Output spooling allows the server to produce output on multiple output devices, such as
printer and diskette devices, in an efficient manner. It does this by sending the output of a
job destined for a printer or diskette to disk storage. This process breaks a potential job
limitation imposed by the availability or speed of the output devices.
Device description
A description of the printer or diskette device
Spooled file
A file containing spooled output records that are to be processed on an output
device
Output queue
An ordered list of spooled files
Writer
A program that sends files from an output queue to a device
Application program
A high- level language program that creates a spooled file using a device file with
the spooling attribute specified as SPOOL(*YES)
Device file
A description of the format of the output, and a list of attributes that describe how
the server should process the spooled file
A base set of job queues is provided with your server. In addition, you may create
additional job queues that you need.
87
This watermark does not appear in the registered version - http://www.clicktoconvert.com
· Process & Job Control: with end, abort, load, execute, create/fork or submit,
get/set attributes, terminate/exit, wait, dump, trace, etc. system calls which
perform controlling over processes, process status, and memory.
· File manipulation: with open, create, delete, read, write, reposition, close, and
get/set file attributes, etc..
· Device Management: with request, release, read, write, and reposition, which
provide additional resources needed by processes.
· Information Maintenance: with time, date, version, memory, chmod, get/set
process attributes, etc..
· Communication: with get hostid, get processid, open/close connection, accept
connection, wait for connection, read message, write message, map memory, etc..
API, standing for Application Program Interfaces, is the interface between a process and
the operating system; which provides convenience of interactions between users and an
operating system, and is implemented by a bunch of system calls.
The issue of a higher priority thread being blocked from execution because a lower
priority thread is holding a resource (e.g., lock) needed to run is described as priority
inversion. The dispatcher should address this problem through priority inheritance.
· DOS
o Disk Operating System
o only really provides a files system – as name implies
o virtually no resource protection
o no multi- tasking
o little fault monitoring
o little convenience in input/output
o no built- in networking
o commercial product
· Windows 3.x
o added Graphic User Interface (GUI) to DOS
o basic operating system is DOS with all its imperfections
o improved user convenience
o some multitasking
o little protection
o no built- in networking
o commercial product
88
This watermark does not appear in the registered version - http://www.clicktoconvert.com
· Windows 95 (98)
o different OS from DOS but provides some DOS and Win 3.x compatibility
o improved convenience – better GUI
o easier addition and management of resources like devices and drivers
o integrates some basic networking support
§ built in Internet clients
§ support for Internet protocols – TCP/IP
o still basically single user
o some crude multi- tasking
o little process protection
o commercial product
· Windows NT
o all the advantages of Windows 95 including GUI
o different operating system from Windows 95
o fully multi- tasking
o more advanced networking than Windows 95
§ incorporates Internet client/server capabilities
§ supports Internet protocols – TCP/IP
§ networking applications based on NETBIOS and the associated
NETBUI protocol
§ BIOS – basic input/output system available on PC’s, DOS etc
§ NETBIOS – extends input/output over a network
§ NETBUI
§ NETBIOS Extended User Interface
§ includes NETBIOS plus additions done by IBM and
Microsoft
o comes as
§ single user for high end PCs
§ multi- user on network servers – limitations – security problems
o commercial product
· UNIX – LINUX
o LINUX is a UNIX clone running on PC and workstations
o multi- tasking
o multi- user
o better user process and resource protection
o many arguable advantages over Windows NT
o more robust system
o better process logging
o built in networking – TCP/IP
o better device drivers
o FREE and down- loadable from Internet
o several freely available applications
o ideal for research & development environments
o disadvantage – less friendly user interface but GUIs under development
89
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Device files are files that provide access to attached devices such as tapes, diskettes,
printers, displays, spools, and other systems that are attached by a communications line.
Example- Tape files, which allow access to data files on tape devices.
GUI - Short for Graphical User Interface a GUI Operating System contains graphics and
icons and is commonly navigated using by using a computer mouse Below are some
examples of GUI Operating Systems.
System7.x
Windows98
Windows CE
Multi-user - A multi- user Operating System allows for multiple users to use the same
computer at the same time and/or different times. Below are some examples of multi- user
Operating Systems.
Linux
UNIX
Windows 2000
Linux
UNIX
Windows 2000
90
This watermark does not appear in the registered version - http://www.clicktoconvert.com
UNIX
Windows 2000
Linux
UNIX
Windows 2000
The term zeroth generation is used to refer to the period of development of computing,
which predated the commercial production and sale of computer equipment. The period
might be dated as extending from the mid-1800s, and Charles Babbage’s Analytical
Engine, to the development of the fist commercial computer in 1951.
Some of the new features that Windows 95 have which Windows 3.x Does not have are:
Plug and Play Allows hardware devices to be automatically installed into the computer
with the proper software. Does not require jumpers to be played with.
32 Bit 32-Bit operating system allowing the computer to run faster and more efficiently.
Registry Combines the power of multiple configuration files into two files allowing the
system configurations to be located easier.
Right mouse click Allows you new access and text manipulation by utilizing both
buttons instead of one.
91
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Microsoft Windows 98 is the upgrade to Microsoft Windows 95. While this was not as
big as release as Windows 95, Windows 98 has significant updates, fixes and support for
new peripherals. The following is a list of some of its new features.
Improved support - Improved support for new devices such as AGP, Direct
X,DVD,USB,MMX.
FAT32 - Windows 98 has the capability of converting your drive to FAT32 without
loosing any information.
Interface - Users of Windows 95 and NT will enjoy the same easy interface.
PnP - Improved PnP support, to detect devices even better then Windows 95.
Customizable Taskbar - Windows adds many nice new features to the taskbar which 95
and NT do not have.
Active Desktop - Includes Active Desktop which allows for users to customize their
desktop with the look of the Internet.
Windows Millennium also known as Windows ME was introduced September 14, 2000
to the general public as the upgrade for Windows 95 and Windows 98 users and is
designed for the end- users. Overall Windows ME has the look and feel of Windows 98
with some additional fixes and features not available in previous operating systems.
While Windows ME includes some of the latest fixes and updates and some enticing new
features we recommend this update only for users that may find or want some of the new
features listed below or for users who are purchasing a new computer with this operating
system included on it.
92
This watermark does not appear in the registered version - http://www.clicktoconvert.com
NEW FEATURES:
Protect important system files - Windows Me allows the user to protect important system
files and will not allow these files to be modified by any type of other software.
Movie editor - Allows users to edit and or combine Microsoft movie files. Importing
movies requires additional hardware.
Windows Media Player - Includes Media Player 7, which enables users a more advanced
way of listening and organizing their media files.
Windows NT 4.0 is the look and feel of Windows 95 however is a completely different
Operating System. Windows NT contains advanced security features, advanced network
support, Full 32-bit operating system, advanced multitasking, user administration and
much more. While NT is a very advanced operating system it does lack the support of
drivers, features, and gaming support when compared to Windows 95 / Windows 98 and
is why even today Windows NT is still used primarily by businesses and technical users.
HomeEdition
Professional
Windows XP includes various new features not found in previous versions of Microsoft
Windows. Below is a listing of some of these new features.
· New interface - a completely new look and ability to change the look.
· Updates - new feature that automatically obtains updates fro the Internet.
· Internet Explorer 6 - Includes internet explorer 6 and new IM.
· Multilingual support - added support for different languages.
In addition to the above features, Windows XP does increase reliability when compared
to previous versions of Microsoft Windows
93
This watermark does not appear in the registered version - http://www.clicktoconvert.com
25. What are the advantages and disadvantages of Monolithic and microkernel?
94
This watermark does not appear in the registered version - http://www.clicktoconvert.com
95
This watermark does not appear in the registered version - http://www.clicktoconvert.com
96
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(ii)
PROCESS MANAGEMENT
1. What is a process?
A program under execution that competes for CPU time and other resources. It is
an active entity where as program is a passive entity.
The number of process running simultaneously and competing for the CPU is
known as the degree of multiprogramming.
Switching from one process to another process without changing the state of
process that is currently in the running state.
The state of a process is defined in part by the current activity of that process.
New, Running, Ready, Waiting and Terminated.
More than one processes running on a processor is former and the later is more
than one processes running on more than one processors.
By two factors
1) Competition
2) Co-operation
97
This watermark does not appear in the registered version - http://www.clicktoconvert.com
If a process terminates then all its children must also be terminated. This
phenomenon, referred to as cascading termination, is normally initiated by the
operating system.
User threads are supported above the kernel and are implemented by a thread
library at the user level. They are fast to create and manage. If kernel is single
threaded then a thread performing a blocking system call will cause the entire
process to block.
Kernel threads are supported by operating system.
Many-to-one: maps many user level threads to one kernel thread. Concurrency is
not achieved.
One-to-one: maps each user thread to a kernel thread. Has the burden of creating a
kernel thread for each user thread.
98
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Threads are created during process startup and placed into a pool called thread
pool, where they wait for work.
Dispatcher is the module that gives control of the CPU to the process selected by
the short-term scheduler. This involves
Switching context
Switching to user mode
Jumping to the proper location in the user program
The time taken by the dispatcher to stop one process and start another running is
known as the dispatch latency.
CPU utilization,
Throughput,
Turnaround time,
Waiting time,
Response time
99
This watermark does not appear in the registered version - http://www.clicktoconvert.com
All small process waiting for one big process to get off the CPU. It is usually
experienced in FCFS scheme.
It partitions the ready queue into several queues. The processes are permanently
assigned to one queue, generally based on some property of the process, such as
memory size, process priority, or process type. Each queue has its own scheduling
algorithm.
If no ready thread is found, the dispatcher will execute a special thread called the
idle thread.
A situation where several processes access and manipulate the same date
concurrently and the outcome of the execution depends on the particular order in
which the access takes place, is called a race condition.
Each process has a segment of code, in which the process may be changing
common variables, updating a table, writing a file, and so on. This section can be
executed only by one process at a time.
If one process is in the critical section no other process can enter the critical
section. This property is known as mutual exclusion.
Mutual exclusion,
Progress,
Bounded waiting.
100
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Process checks for CPU for every clock cycle or often when it is waiting to
resume its execution.
Two or more processes waiting indefinitely for an event that can be caused only
by one of the waiting process leads to dead lock.
Counting semaphore: its integer value can range over an unrestricted domain.
Binary semaphore: can take values 0 and 1 only.
i. Mutual exclusion
ii. Hold and wait
iii. No preemption
iv. Circular wait
Deadlock prevention is a set of methods for ensuring that at least one of the
necessary conditions cannot hold.
Deadlock avoidance on the other hand, requires that the operating system be
given in advance additional information concerning which resources a process
will request and use during its life time so that avoiding the deadlock well before
scheduling the processes.
101
This watermark does not appear in the registered version - http://www.clicktoconvert.com
102
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(iii)
MEMORY MANAGEMENT
· Input queue:
The collection of processes on the disk that is waiting to be brought into memory
for execution are placed in the input queue.
- compile time:
Deals with absolute code i.e., the compiler code will always start from
that location. Eg: MS_DOS .com format programs are absolute code
bound at compile time
- load time:
not known at compile time regarding the location where the process will
reside in memory, these codes are relocatable called as relocatable code.
Binding is done only during load time.
- execution time :
binding is done only during run time. Requires special hardware for this
scheme to work..
· Logical Address space: (Virtual Address space with regards to execution time
binding) Address generated by the CPU is commonly referred to as logical
address. The set of all logical addresses generated by a program is a logical
address space.
103
This watermark does not appear in the registered version - http://www.clicktoconvert.com
· Addresses seen by the memory unit i.e., the one loaded into the memory address
register is called the physical address and the set of all physical addresses
corresponding to the logical addresses is a physical address space.
· Overlays:
The idea of overlays is to keep in memory only those instructions and data that are
needed at any given time. When other instructions are needed, they are loaded into space
occupied previously by instructions that are no longer needed.
Generally, the memory required by the bigger process is allocated so that the other
processes can be overlaid at the same allocated memory.
Ex: in a 2 pass assembler the contents used during pass1 may not be required
during pass2 so the memory allocated for pass1 can be used to place the instructions of
pass2.
· Dynamic linking requires support from OS.
· Dynamic ling and overlays doesn’t require support from OS.
104
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Work of a dispatcher:
- check whether the next process in the queue is in the memory.
- If not and if there is no free memory region, the dispatcher swaps out a
process currently in memory and swaps in the desired process.
- Reload registers as normal and transfer control to the selected process.
In Microsoft windows 3.1 it is the user who decides on whether to swap a process (in or
out), rather than the scheduler deciding it.
The operating system is placed normally in the low memory since this is where the
interrupt vector is normally located. Interrupt vector is the one that mainly helps in
deciding the location of the os.
105
This watermark does not appear in the registered version - http://www.clicktoconvert.com
8. Memory Allocation:
106
This watermark does not appear in the registered version - http://www.clicktoconvert.com
- block list
- block header
hole: Available block of memory.
Memory allocation can also be done using the Buddy System technique.
Here division of memory in to two consecutively in the powers of 2 is done
during allocation and the parts are recombined during de-allocation if their adjacent node
is free.
Statistical analysis of first fit, for instance reveals that, even with some optimization,
given N allocated blocks, another 0.5N blocks will be lost due to fragmentation. That is
one-third of memory may be unusable. This property is known as 50-percent rule.
Solutions:
- Compaction: shuffling and placing all free memory together in one large
block.
- Permitting the logical address space of a process to be non-contiguous.
- Paging
- Segmentation
- Combination of segmentation and paging
107
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Paging is a memory management scheme that permits the physical address space of a
process to be non-contiguous.
Here in paging technique the address generated by the CPU i.e., the logical address is
divided into 2 parts
- page number : used as index in to page table.
- page offset
If the size of the logical address space is and the page size is addressing
units (bytes or words), then the high-order m-n bits of logical address designate the page
number and the n lower-order bits designate the page offset.
User view: user program views that memory as one single contiguous space, containing
only that program.
System view: the user program is scattered throughout physical memory, which also
holds other programs.
Contents of the frame table (data structure used in the paging technique):
- Allocated frames
- Available frames
- Total no of frames
108
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Those entries that cannot be removed from the TLB are called as wired down entries.
109
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Demand paging:
110
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Demand paging is one where a page is loaded in to main memory from the secondary
memory only on demand.
Lazy swapper:
A lazy swapper never swaps a page into memory unless that page will be needed.
111
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(iv)
INPUT/OUTPUT & DISC MANAGEMENT(MISC)
Buffer swapping is also know as double buffering and it smoothes out the flow of data
between the I/O device and a process. It is an improvement over the single buffering
technique and involves assigning two system buffers to the operation. A process now
transfers data to(and from ) one buffer while the operating system empties(or fills) the
other.
Double buffering is inadequate if the process performs rapid bursts of I/O. In this case
the problem can be alleviated by using more than two buffers. When more than two
buffers are used , the collection of buffers is itself referred to as circular buffer.
I/O devices are not directly used to communicate with the computer system. Instead,
there is an intermediate electronic device called the device controller. This device
controller is really a special purpose computer with a limited instruction set, limited to
input/output control. The processor gives it one instruction at a time. However some
device controllers do know how to execute programs of more than one instruction. Then
they are called as I/O processors (IOPs) or sometimes channels.
The SCAN algo is called the Elevator algo since it behaves like an elevator and goes in
one direction until there are no more requests in that direction, and then reverse and go
the other direction.
Seek time : The seek time is the time for the disk arm to move the heads to the cylinder
containing the desired sector.
Rotational latency : rotational latency is the additional time waiting for the disk to rotate
the desired sector to the disk head.
Access time : The sum of seek time, if any, and the rotational delay is called as access
time.
112
This watermark does not appear in the registered version - http://www.clicktoconvert.com
SCAN algorithm
LOOK Scheduling
C-LOOK Scheduling
N-STEP SCAN
F-SCAN
With SSTF, SCAN and C-SCAN it is possible that the arm may not move for a
considerable peroid of time. Arm stickiness occurs when one or more processes have
high access rates and monopolise the entire device by repeated request to that track . To
avoid this arm stickiness the disk request queue must be segmented. Two examples of
this approach is N-step-SCAN and FSCAN.
The n step scan policy segments the disk request into subqueues of the len L . Sub
quesues are processed one at at a time , using the SCAN . While a queue is being
processed , new requests must be added to some other queue.
If fewer than N requests are avilable at the ned of the scan , then all of them are
processed with the next scan.FSCAN policy uses two subqueues. When the scan begins,
all new request are in one of the queues , with the other empty. During the scan , all the
new requets are put in the other queue. Thus , the serveice of the new request is deferred
until all of the old processes have been processed.
113
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A new disk is simply is just a platter of magnetic material. Before we can store data , it
must be divided into sectors that the disk controller can read and write. This process is
called low- level formatting or Physical formatting. Logical formatting corressponds to "
making the file system " . In this step the operating system stores the initial file system
data structures onto the disk.
When the disk is intialised during the low level format at the factory , some spare sectors
are set aside and are not visible even by the operating system. When a bad sector is
encounterd , the controller replaces each bad sector logically with one of the spare
sectors. This scheme is called as sector sparing / Fowarding .
DRAM is not the best, but it’s cheap, does the job, and is available almost everywhere
you look. DRAM data resides in a cell made of a capacitor and a transistor. The capacitor
tends to lose data unless it’s recharged every couple of milliseconds, and this recharging
tends to slow down the performance of DRAM compared to speedier RAM types.
Dispatcher module gives control of the CPU to the process selected by the short-term
scheduler; this involves: Switching context, Switching to user mode, Jumping to the
proper location in the user program to restart that program, dispatch latency – time it
takes for the dispatcher to stop one process and start another running.
14) Why is rotational latency usually not considered in disk scheduling? How would
you modify SSTF, SCAN, and C-SCAN to include latency optimization?
114
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Most disks do not export their rotational position informationto the host. Even if they did,
the time for this information to reach the scheduler would be subject to imprecision and
the time consumed by the scheduler is variable, so the rotational position information
would become incorrect. Further, the disk requests are usually given in terms of logical
block numbers, and the mapping between logical blocks and physical locations is very
complex.
Three advantages:
Ø Easy debugging : Bugs are less likely to cause an operating system crash.
Ø Performance Optimization : Performance can be improved by utilizing
dedicated hardware and hard-coded algorithms.
Ø Thin kernel : The kernel is simplified by moving algorithms out of it.
Three disadvantages:
16) Why might a system use interrupt-driven I/O to manage a single serial port, but
polling I/O to manage a front-end processor, such as a terminal concentrator?
Polling can be more efficient than interrupt-driven I/O. This is the case when the I/O is
frequent and of short duration. Even though a single serial port will perform I/O
relatively infrequently and should thus use interrupts, a collection of serial ports such as
those in a terminal concentrator can produce a lot of short I/O operations, and
interrupting for each one could create a heavy load on the system. A well- timed polling
loop could alleviate that load without wasting many resources through looping with no
I/O needed.
The STREAMS driver controls a physical device that could be involved in a STREAMS
operation. The STREAMS module modifies the flow of data between the head (the user
interface) and the driver.
18) How does DMA increase system concurrency? How does it complicate hardware
design?
115
This watermark does not appear in the registered version - http://www.clicktoconvert.com
DMA increases system concurrency by allowing the CPU to perform tasks while the
DMA system transfers data via the system and memory buses. Hardware design is
complicated because the DMA controller must be integrated into the system, and the
system must allow the DMA controller to be a bus master. Cycle stealing may also be
necessary to allow the CPU and DMA controller to share use of the memory bus.
19) What problems could occur if a system allowed a file system to be mounted
simultaneously at more than one location?
There would be multiple paths to the same file, which could confuse users or encourage
mistakes (deleting a file with one path deletes the file in all the other paths).
20) Consider a system that supports the strategies of contiguous, linked, and
indexed allocation.What criteria should be used in decidingwhich strategy is best
utilized for a particular file?
116
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(v)
UNIX FAQs
The fork() function is used to create a new process from an existing process. The new
process is called the child process, and the existing process is called the parent. You can
tell which is which by checking the return value from fork(). The parent gets the child's
pid returned to him, but the child gets 0 returned to him. Thus this simple code illustrate's
the basics of it.
* process ID
* different parent process ID
* Own copy of file descriptors and directory streams.
* process, text, data and other memory locks are NOT inherited.
* process times, in the tms struct
* resource utilizations are set to 0
* pending signals initialized to the empty set
* timers created by timer_create not inherited
* asynchronous input or output operations not inherited
117
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Some systems have a system call vfork(), which was originally designed as a lower-
overhead version of fork(). Since fork() involved copying the entire address space of the
process, and was therefore quite expensive, the vfork() function was introduced (in
3.0BSD).
However, since vfork() was introduced, the implementation of fork() has improved
drastically, most notably with the introduction of `copy-on-write', where the copying of
the process address space is transparently faked by allowing both processes to refer to the
same physical memory until either of them modify it. This largely removes the
justification for vfork(); indeed, a large proportion of systems now lack the original
functionality of vfork() completely. For compatibility, though, there may still be a vfork()
call present, that simply calls fork() without attempting to emulate all of the vfork()
semantics.
As a result, it is very unwise to actually make use of any of the differences between fork()
and vfork(). Indeed, it is probably unwise to use vfork() at all, unless you know exactly
why you want to.
The basic difference between the two is that when a new process is created with vfork(),
the parent process is temporarily suspended, and the child process might borrow the
parent's address space. This strange state of affairs continues until the child process either
exits, or calls execve(), at which point the parent process continues.
This means that the child process of a vfork() must be careful to avoid unexpectedly
modifying variables of the parent process. In particular, the child process must not return
from the function containing the vfork() call, and it must not call exit() (if it needs to exit,
it should use _exit(); actually, this is also true for the child of a normal fork()).
3) Why use _exit rather than exit in the child branch of a fork?
There are a few differences between exit() and _exit() that become significant when
fork(), and especially vfork(), is used.
The basic difference between exit() and _exit() is that the former performs clean-up
related to user- mode constructs in the library, and calls user-supplied cleanup functions,
whereas the latter performs only the kernel cleanup for the process.
In the child branch of a fork(), it is normally incorrect to use exit(), because that can lead
to stdio buffers being flushed twice, and temporary files being unexpectedly removed. In
C++ code the situation is worse, because destructors for static objects may be run
incorrectly. (There are some unusual cases, like daemons, where the parent should call
_exit() rather than the child; the basic rule, applicable in the overwhelming majority of
cases, is that exit() should be called only once for each entry into main.)
118
This watermark does not appear in the registered version - http://www.clicktoconvert.com
In the child branch of a vfork(), the use of exit() is even more dangerous, since it will
affect the state of the parent process.
#include <stdlib.h>
#include <stdlib.h>
The string passed to putenv must not be freed or made invalid, since a pointer to it is kept
by putenv(). This means that it must either be a static buffer or allocated off the heap. The
string can be freed if the environment variable is redefined or deleted via another call to
putenv().
Now suppose you wanted to create a new environment variable called MYVAR, with a
value of MYVAL. This is how you'd do it.
sprintf(envbuf,"MYVAR=%s","MYVAL");
if(putenv(envbuf))
{
printf("Sorry, putenv() couldn't find the memory for %s\n",envbuf);
/* Might exit() or something here if you can't live without it */
}
If you don't know the names of the environment variables, then the getenv() function isn't
much use. In this case, you have to dig deeper into how the environment is stored.
119
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The sleep() function, which is available on all Unixes, only allows for a duration
specified in seconds. If you want finer granularity, then you need to look for alternatives:
Of the above, select() is probably the most portable (and strangely, it is often much more
efficient than usleep() or an itimer-based method). However, the behaviour may be
different if signals are caught while asleep; this may or may not be an issue depending on
the application.
Whichever route you choose, it is important to realise that you may be constrained by the
timer resolution of the system (some systems allow very short time intervals to be
specified, others have a resolution of, say, 10ms and will round all timings to that). Also,
as for sleep(), the delay you specify is only a minimum value; after the specified period
elapses, there will be an indeterminate delay before your process next gets scheduled.
Modern Unixes tend to implement alarms using the setitimer() function, which has a
higher resolution and more options than the simple alarm() function. One should
generally assume that alarm() and setitimer(ITIMER_REAL) may be the same
underlying timer, and accessing it both ways may cause confusion.
Itimers can be used to implement either one-shot or repeating signals; also, there are
generally 3 separate timers available:
ITIMER_REAL
counts real (wall clock) time, and sends the SIGALRM signal
ITIMER_VIRTUAL
counts process virtual (user CPU) time, and sends the SIGVTALRM signal
ITIMER_PROF
counts user and system CPU time, and sends the SIGPROF signal; it is intended for
interpreters to use for profiling.
Itimers, however, are not part of many of the standards, despite having been present since
4.2BSD. The POSIX realtime extensions define some similar, but different, functions.
120
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A parent and child can communicate through any of the normal inter-process
communication schemes (pipes, sockets, message queues, shared memory), but also have
some special ways to communicate that take advantage of their relationship as a parent
and child.
One of the most obvious is that the parent can get the exit status of the child.
Since the child inherits file descriptors from its parent, the parent can open both ends of a
pipe, fork, then the parent close one end and the child close the other end of the pipe.
This is what happens when you call the popen() routine to run another program from
within yours, i.e. you can write to the file descriptor returned from popen() and the child
process sees it as its stdin, or you can read from the file descriptor and see what the
program wrote to its stdout. (The mode parameter to popen() defines which; if you want
to do both, then you can do the plumbing yourself without too much difficulty.)
Also, the child process inherits memory segments mmapped anonymously (or by
mmapping the special file `/dev/zero') by the parent; these shared memory segments are
not accessible from unrelated processes.
9) What is a zombie?
When a program forks and the child finishes before the parent, the kernel still keeps some
of its information about the child in case the parent might need it -- for example, the
parent may need to check the child's exit status. To be able to get this information, the
parent calls wait(); when this happens, the kernel can discard the information.
In the interval between the child terminating and the parent calling wait(), the child is
said to be a `zombie'. (If you do `ps', the child will have a `Z' in its status field to indicate
this.) Even though it's not running, it's still taking up an entry in the process table. (It
consumes no other resources, but some utilities may show bogus figures for e.g. CPU
usage; this is because some parts of the process table entry have been overlaid by
accounting info to save space.)
This is not good, as the process table has a fixed number of entries and it is possible for
the system to run out of them. Even if the system doesn't run out, there is a limit on the
number of processes each user can run, which is usually smaller than the system's limit.
This is one of the reasons why you should always check if fork() failed, by the way!
If the parent terminates without calling wait(), the child is `adopted' by init, which
handles the work necessary to cleanup after the child. (This is a special system program
with process ID 1 -- it's actually the first program to run after the system boots up).
121
This watermark does not appear in the registered version - http://www.clicktoconvert.com
You need to ensure that your parent process calls wait() (or waitpid(), wait3(), etc.) for
every child process that terminates; or, on some systems, you can instruct the system that
you are uninterested in child exit states.
Another approach is to fork() twice, and have the immediate child process exit straight
away. This causes the grandchild process to be orphaned, so the init process is
responsible for cleaning it up. For code to do this, see the function fork2() in the
examples section.
The other technique is to catch the SIGCHLD signal, and have the signal handler call
waitpid() or wait3(). See the examples section for a complete program.
A daemon process is usually defined as a background process that does not belong to a
terminal session. Many system services are performed by daemons; network services,
printing etc.
Simply invoking a program in the background isn't really adequate for these long-running
programs; that does not correctly detach the process from the terminal session that started
it. Also, the conventional way of starting daemons is simply to issue the command
manually or from an rc script; the daemon is expected to put itself into the background.
1. fork() so the parent can exit, this returns control to the command line or shell
invoking your program. This step is required so that the new process is guaranteed not to
be a process group leader. The next step, setsid(), fails if you're a process group leader.
2. setsid() to become a process group and session group leader. Since a controlling
terminal is associated with a session, and this new session has not yet acquired a
controlling terminal our process now has no controlling terminal, which is a Good Thing
for daemons.
3. fork() again so the parent, (the session group leader), can exit. This means that we, as
a non-session group leader, can never regain a controlling terminal.
4. chdir("/") to ensure that our process doesn't keep any directory in use. Failure to do
this could make it so that an administrator couldn't unmount a filesystem, because it was
our current directory. [Equivalently, we could change to any directory containing files
important to the daemon's operation.]
5. umask(0) so that we have complete control over the permissions of anything we
write. We don't know what umask we may have inherited. [This step is optional]
6. close() fds 0, 1, and 2. This releases the standard in, out, and error we inherited from
our parent process. We have no way of knowing where these fds might have been
redirected to. Note that many daemons use sysconf() to determine the limit
_SC_OPEN_MAX. _SC_OPEN_MAX tells you the maximun open files/process. Then
122
This watermark does not appear in the registered version - http://www.clicktoconvert.com
in a loop, the daemon can close all possible file descriptors. You have to decide if you
need to do this or not. If you think that there might be file-descriptors open you should
close them, since there's a limit on number of concurrent file descriptors.
7. Establish new open descriptors for stdin, stdout and stderr. Even if you don't plan to
use them, it is still a good idea to have them open. The precise handling of these is a
matter of taste; if you have a logfile, for example, you might wish to open it as stdout or
stderr, and open `/dev/null' as stdin; alternatively, you could open `/dev/console' as stderr
and/or stdout, and `/dev/null' as stdin, or any other combination that makes sense for your
particular daemon.
Almost none of this is necessary (or advisable) if your daemon is being started by inetd.
In that case, stdin, stdout and stderr are all set up for you to refer to the network
connection, and the fork()s and session manipulation should not be done (to avoid
confusing inetd). Only the chdir() and umask() steps remain as useful.
The most portable way, by far, is to do popen(pscmd, "r") and parse the output. (pscmd
should be something like `"ps -ef"' on SysV systems; on BSD systems there are many
possible display options: choose one.)
In the examples section, there are two complete versions of this; one for SunOS 4, which
requires root permission to run and uses the `kvm_*' routines to read the information
from kernel data structures; and another for SVR4 systems (including SunOS 5), which
uses the `/proc' filesystem.
It's even easier on systems with an SVR4.2-style `/proc'; just read a psinfo_t structure
from the file `/proc/PID/psinfo' for each PID of interest. However, this method, while
probably the cleanest, is also perhaps the least well-supported. (On FreeBSD's `/proc',
you read a semi- undocumented printable string from `/proc/PID/status'; Linux has
something similar.)
* kill() returns 0
o this implies that a process exists with the given PID, and the system would allow
you to send signals to it. It is system-dependent whether the process could be a zombie.
* kill() returns @math{-1}, errno == ESRCH
o either no process exists with the given PID, or security enhancements are causing
the system to deny its existence. (On some systems, the process could be a zombie.)
123
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The most-used technique is to assume that success or failure with EPERM implies that
the process exists, and any other error implies that it doesn't.
An alternative exists, if you are writing specifically for a system (or all those systems)
that provide a `/proc' filesystem: checking for the existence of `/proc/PID' may work.
The return value of system(), pclose(), or waitpid() doesn't seem to be the exit value of
my process... or the exit value is shifted left 8 bits... what's the deal?
The man page is right, and so are you! If you read the man page for waitpid() you'll find
that the return code for the process is encoded. The value returned by the process is
normally in the top 16 bits, and the rest is used for other things. You can't rely on this
though, not if you want to be portable, so the suggestion is that you use the macros
provided. These are usually documented under wait() or wstat.
Macros defined for the purpose (in `<sys/wait.h>') include (stat is the value returned by
waitpid()):
WIFEXITED(stat)
Non zero if child exited normally.
WEXITSTATUS(stat)
exit code returned by child
WIFSIGNALED(stat)
Non-zero if child was terminated by a signal
WTERMSIG(stat)
signal number that terminated child
WIFSTOPPED(stat)
non-zero if child is stopped
WSTOPSIG(stat)
number of signal that stopped child
WIFCONTINUED(stat)
non-zero if status was for continued child
WCOREDUMP(stat)
If WIFSIGNALED(stat) is non- zero, this is non-zero if the process left behind a core
dump.
124
This watermark does not appear in the registered version - http://www.clicktoconvert.com
When you free memory back to the heap with free(), on almost all systems that doesn't
reduce the memory usage of your program. The memory free()d is still part of the
process' address space, and will be used to satisfy future malloc() requests.
If you really need to free memory back to the system, look at using mmap() to allocate
private anonymous mappings. When these are unmapped, the memory really is released
back to the system. Certain implementations of malloc() (e.g. in the GNU C Library)
automatically use mmap() where available to perform large allocations; these blocks are
then returned to the system on free().
Of course, if your program increases in size when you think it shouldn't, you may have a
`memory leak' -- a bug in your program that results in unused memory not being freed.
On BSDish systems, the ps program actually looks into the address space of the running
process to find the current argv[], and displays that. That enables a program to change its
`name' simply by modifying argv[].
On SysVish systems, the command name and usually the first 80 bytes of the parameters
are stored in the process' u-area, and so can't be directly modified. There may be a system
call to change this (unlikely), but otherwise the only way is to perform an exec(), or write
into kernel memory (dangerous, and only possible if running as root).
Some systems (notably Solaris) may have two separate versions of ps, one in `/usr/bin/ps'
with SysV behaviour, and one in `/usr/ucb/ps' with BSD behaviour. On these systems, if
you change argv[], then the BSD version of ps will reflect the change, and the SysV
version won't.
This would be a good candidate for a list of `Frequently Unanswered Questions', because
the fact of asking the question usually means that the design of the program is flawed. :-)
You can make a `best guess' by looking at the value of argv[0]. If this contains a `/', then
it is probably the absolute or relative (to the current directory at program start) path of the
executable. If it does not, then you can mimic the shell's search of the PATH variable,
looking for the program. However, success is not guaranteed, since it is possible to
invoke programs with arbitrary values of argv[0], and in any case the executable may
have been renamed or deleted since it was started.
125
This watermark does not appear in the registered version - http://www.clicktoconvert.com
If all you want is to be able to print an appropriate invocation name with error messages,
then the best approach is to have main() save the value of argv[0] in a global variable for
use by the entire program. While there is no guarantee whatsoever that the value in
argv[0] will be meaningful, it is the best option available in most circumstances.
The most common reason people ask this question is in order to locate configuration files
with their program. This is considered to be bad form; directories containing executables
should contain nothing except executables, and administrative requirements often make it
desirable for configuration files to be located on different filesystems to executables.
A less common, but more legitimate, reason to do this is to allow the program to call
exec() on itself; this is a method used (e.g. by some versions of sendmail) to completely
reinitialise the process (e.g. if a daemon receives a SIGHUP).
The correct directory for this usually depends on the particular flavour of Unix you're
using; `/var/opt/PACKAGE', `/usr/local/lib', `/usr/local/etc', or any of several other
possibilities. User-specific configuration files are usually hidden `dotfiles' under $HOME
(e.g. `$HOME/.exrc').
From the point of view of a package that is expected to be usable across a range of
systems, this usually implies that the location of any sitewide configuration files will be a
compiled-in default, possibly using a `--prefix' option on a configure script (Autoconf
scripts do this). You might wish to allow this to be overridden at runtime by an
environment variable. (If you're not using a configure script, then put the default in the
Makefile as a `-D' option on compiles, or put it in a `config.h' header file, or something
similar.)
User-specific configuration should be either a single dotfile under $HOME, or, if you
need multiple files, a dot-subdirectory. (Files or directories whose names start with a dot
are omitted from directory listings by default.) Avoid creating multiple entries under
$HOME, because this can get very cluttered. Again, you can allow the user to override
this location with an environment variable. Programs should always behave sensibly if
they fail to find any per-user configuration.
20) Why doesn't my process get SIGHUP when its parent dies?
SIGHUP is a signal that means, by convention, "the terminal line got hung up". It has
nothing to do with parent processes, and is usually generated by the tty driver (and
delivered to the foreground process group).
126
This watermark does not appear in the registered version - http://www.clicktoconvert.com
However, as part of the session management system, there are exactly two cases where
SIGHUP is sent on the death of a process:
* When the process that dies is the session leader of a session that is attached to a
terminal device, SIGHUP is sent to all processes in the foreground process group of that
terminal device.
* When the death of a process causes a process group to become orphaned, and one or
more processes in the orphaned group are stopped, then SIGHUP and SIGCONT are sent
to all members of the orphaned group. (An orphaned process group is one where no
process in the group has a parent which is part of the same session, but not the same
process group.)
There isn't a fully general approach to doing this. While you can determine the
relationships between processes by parsing ps output, this is unreliable in that it
represents only a snapshot of the system.
However, if you're lauching a subprocess that might spawn further subprocesses of its
own, and you want to be able to kill the entire spawned job at one go, the solution is to
put the subprocess into a new process group, and kill that process group if you need to.
The preferred function for creating process groups is setpgid(). Use this if possible rather
than setpgrp() because the latter differs between systems (on some systems `setpgrp();' is
equivalent to `setpgid(0,0);', on others, setpgrp() and setpgid() are identical).
Putting a subprocess into its own process group has a number of effects. In particular,
unless you explicitly place the new process group in the foreground, it will be treated as a
background job with these consequences:
In many applications input and output will be redirected anyway, so the most significant
effect will be the lack of keyboard signals. The parent application should arrange to catch
at least SIGINT and SIGQUIT (and preferably SIGTERM as well) and clean up any
background jobs as necessary.
22) Which address spaces would be accessed by the 2 modes or execution levels ?
User mode -> User stack and Kernel mode -> kernel stack
127
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Index
It duplicates parent process and gives a new PID to child, returned to calling process.
26) How many u areas can kernel access at any point of time ? why ?
1 uarea,using the only 1 register triplet for the currently running process.
When critical regions/shared regions are executed, processor execution level is RAISED.
True
For simple pipes: Only direct blocks are used, and data is transient here
33) what are the 3 logical sections of a process in the UNIX system ?
Data,Text/Code,Stack.
34) what are user register triples and kernel register triples ?
128
This watermark does not appear in the registered version - http://www.clicktoconvert.com
It is used to store Page Table Info, virtual address for kernel & user processes.
When a process gets its slot, the signal bits are checked for setting.
It's a mechanism that takes care of levels (or) process groups and an arithmetic for
priority that maintains an order, between processes from different groups also.
129
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Part – IV
OBJECT ORIENTED
PROGRAMMING
130
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Topics Covered:-
131
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(i)
2. Benefits of object-orientation?
Reuse
Increased quality
Emphasis on modeling the real world
Faster development
Increased Quality
Easier maintenance
Enhanced modifiability
Systems more change resilient, evolvable
Reduced development risks for complex systems
132
This watermark does not appear in the registered version - http://www.clicktoconvert.com
1. In C, when a function takes no parameters, its prototype has the word void inside
its function parameter list. Eg char f1(void).In C++, the void is optional ie char
f1()
2. In C an empty parameter list would mean nothing is said about the parameters to
the function. In C++, it means that the function has no parameters.
3. In C prototypes are optional, in C++ they are required.
4. In C++ if a function is declared as returning a value, it must return a value ie if a
function has a return type other than void, any return statement within that
function must contain a value. In C, a non-void function is not required to actually
return a value.
5. In C, if you don’t explicitly specify the return type of a function, an integer type is
assumed. In C++ you must explicitly declare the return type of all functions.
6. In C, local variables can be declared only at the start of a block. In C++, local
variables can be declared anywhere.
4. What is a class?
"A class is a set of objects that share a common structure and a common behavior."
(Booch)
general format:
class class_name{
//private functions and variables
public:
//public functions and variables
} object- list;
5. What Is An Object?
An object has state, behavior, and identity; the structure and behavior of similar objects
are defined in their common class; the terms instance and object are interchangeable.
(Booch)
6. What is a method?
133
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A method is a function or procedure which is defined in a class and typically can access
the internal state of an object of that class to perform some operation. It can be thought
of as a procedure with the first parameter as the object to work on. This object is called
the receiver, which is the object the method operates on. An exception exists with C++'s
static member functions which do not have a receiver, or "this" pointer.
Abstraction:
Inheritance : Inheritance is the process by which one object can acquire the
properties of another. More specifically, an object can inherit a general set of properties
to which it can add those features that are specific only to itself.
Encapsulation is the process of hiding all of the details of an object that do not
contribute to its essential characteristics.(Booch)
9. Constructor
134
This watermark does not appear in the registered version - http://www.clicktoconvert.com
10. Destructor
By default, the members of a class are private but the members of a structure
are public.
Syntax of a structure
Struct type_name
{
// public function and data members
private:
// private function and data members
} object-list;
è A union defines a class type that can contain both functions and data as members.
è Union similar to structure in that by default all members are public until the private
specifier is used. In union however , all data members share the same memory
location
è The unions ability to link code and data allows you to create class types in which all
data uses a shared location.
è They cannot inherit any other class and they cannot be used as a base class for any
other type.
è They also must not contain any object that has a constructor or destructor.
è The union itself can have a constructor and destructor.
è Unions cannot have virtual member functions.
135
This watermark does not appear in the registered version - http://www.clicktoconvert.com
è a friend function is not a member of a class but still has access to its private
members.
è Enables a function to have access to the private members of two or more different
classes.
è A friend function is not a member and cannot be qualified by an object name. It
must be called just like a normal function.
è Although a friend function has knowledge of the private elements of the class for
which it is a friend, it can only access them through an object of the class. A friend
can access the variables only in conjunction with an object that is declared within or
passed to the friend function.
è A friend function is not inherited.
è A friend function can be friends with more than one class.
class myclass{
int n,d;
public:
myclass(int i, int j) { n = i ; d = j; }
// declare a friend of myclass
friend int isfactor(myclass ob);
};
int main()
{
myclass ob1(10, 2);
return 0;
}
Here , myclass declares its constructor function and the friend isfactor()
inside its class declaration. Because isfactor() is a friend of myclass, isfactor() has access
136
This watermark does not appear in the registered version - http://www.clicktoconvert.com
to its private members. That is why, within isfactor(), it is possible to directly refer to
ob.n and ob.d.
Example
public:
void function_name(B obj) { cout<< a; }
};
class B
{
public:
friend void A:: function_name(B obj);
};
int main()
{
A obj1;
B obj2;
obj1.function_name(obj2);
return 0;
}
137
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(ii)
INHERITENCE
1.What is Inheritance?
The mechanism of deriving a new class from an old one is called Inheritance. The old
class is called as base class and the new class is called as derived class.
· Reusabilty
3.Types of Inheritance:
· Single Inheritance
· Multiple Inheritance
B1 B2
· Multilevel Inheritance
D
· Hybrid Inheritance
B1 B2
138
This watermark does not appear in the registered version - http://www.clicktoconvert.com
· D
Hierarchical Inheritance
D1 D2 D3
A derived class can be defined by specifying its relationship with the base class in
addition to its own details.
Class derieved_class_name : visibility_mode base_class_name
{
----------
----------
};
visibility_mode:
· specifies Public, Private, Protected….
· if not specified .. taken as private
· is optional
VISIBILITY MODES:
‘Public’ members of the base class become ‘Private’ members of derived class. Therefore
public members of base class can be accessed only through member functions of the
derived class. They are not accessible to the objects of the derived class.
‘Public ‘ members of the base class become ‘Public’ members of the derived class and
therefore are accessible to the objects of the derived class.
7. NOTE: In both private and public inheritance the private members of the base
class are not inherited.
139
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Both Public and Protected members of the base class become protected members of the
derived class.
12. What are the various functions that can access the private and protected members
of a class?
· Member functions of the class.
· A function that is a friend of the class.
· A member function of a class that is a friend of the class.
· A member function of a derived class.
13. Difference between Friend functions and member functions of derived class in
accessing the private and protected members of a class?
* The Friend functions and the member functions of a friend class can access both
the private and protected data.
* The member functions of a derived class can directly access only the protected
data. However, they can access the private data through the member functions of the base
class.
14. An object of a derived class can be treated as an object of the base class when
manipulated with pointers and references.
140
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Base Derived
Employee: Manager:
first_name
family_name first_name
… family_name
…
group
level
/* ….
If a class Derived has a public base class Base, then a Derived* can be assigned to a
variable of type Base* without the use of explicit type conversion. The reverse needs
explicit type conversion.
Eg:
Void fun(Manager mm, Employee ee)
{
Employee* pe = &mm; // ok : base class pointer pointing to
derived class object
Manager* pm = ⅇ // error : derived class pointer cannot point
to base class object….need explicit type
conversion
………..
………..
}
141
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Public:
Int I;
……
Void print() const;
……
Char * fam_name() const
{
return family_name;
}
……
};
A member function of the derived class can use the public and protected members of its
base class as if it where declared in the derived class it self
Void member :: print() const
{
cout<<”level”<<level<<endl; //ok derived class - member
cout<<”name is “<< fam_name()<<endl;//ok base class members accessed
through base class member functions
cout<<”I :”<<I<<endl; //ok base class-public member
cout<<”str is”<<str<<endl; //ok base class-protected member
cout<<”family_name: “<<family_name<<endl;//error base class-private
member
// a derived class cannot use the base class private names directly
class Employee
{
142
This watermark does not appear in the registered version - http://www.clicktoconvert.com
char *first_name,;
int dept;
Public:
Employee(char* fname, int dept);
};
Virtual Functions:
Class employee
{
….
public:
virtual void print() const; // virtual function
virtual void display()=0; // pure virtual function
};
void employee:: print() const
{
cout<<family_name<<”\t”<<dept<<endl;
}
143
This watermark does not appear in the registered version - http://www.clicktoconvert.com
public:
void print () const;
};
void manager::print() const
{
employee::print();
cout<<”\t”<<level;<<endl;
}
The keyword VIRTUAL indicates that the print() can act as an interface to the print()
function defined in the base class and the print() functions derived in classes derived from
it.
NOTE:
* The virtual function must be defined for the class in which it is first declared (unless it
is declared to be pure virtual function).
* A class with one or more pure virtual functions is called as abstract class, and no
objects can be created for the abstract class.
MULTIPLE INHERITANCE:
Class task
{
delay() { … }
virtual void pending()=0;
virtual int fun();
};
class Displayed
{
draw() { … }
virtual void draw()=0;
virtual int fun();
};
class Satellite : public task, public Displayed
{
transmit() { … }
void pending(); //override task::pending
void draw(); //override displayed::draw
void f(satellite * sp)
{
int g=sp->fun(); // error: ambiguous
g=sp->task::fun(); //ok
g=sp->displayed::fun(); //ok}};
144
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(iii)
Polymorphism
Virtual Function
class A{
...
...
virtual print(char *) =0 ; // Pure virtual function
};
class A{
...
...
virtual int print(char *);
...
...
};
145
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Class Hierarchy
Inheritance
simple inheritance
multiple inheritance
if A & B are two base classes for C and both contains int f(int) and char f(char)
respectively. Now with the help of using ( Keyword ) we can declare both.
e.g.
class A{
...
...
int f(int);
char f(char);
...
...
};
class B{
public:
double f(double);
...
...
};
146
This watermark does not appear in the registered version - http://www.clicktoconvert.com
};
A A
B D
class A{
...
...
};
147
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The following function and descriptions are common for all containers differences are
specified separately.
· The facilities of the Standard Template Library are defined in the Standard
namespace(std)
· A container is an object which holds other objects. e.g. : list, vector , stack, queue
etc.
· There are 2 ways to define container
o Define a base class container and extend it.( problem is in two containers
here may not be any common interface).
o Define them separately ( It follows in c++)
· Fat interface means a lot of methods in which all are not useful and necessary
present in the interface e.g. : subscripting in list is not necessary.
· In c++ all containers implements all the standard container interface. (but there is
no common iterator base class)
· To be used generally the containers use allocators which is passed as template
argument. It is necessary because a vector can contain numbers or a vector of
objects of a user defined class.
e.g.
Template <class T,class A : Allocator <T>>
Class ::vector{
----
----
}
· Iterator:
Iterator is used to navigate containers
Key member functions of iterator are:
1. iterator begin(); points to first element
2. const- iterator begin() const;
3. iterator end(); points to one past last element
4. const- iterator end() const;
5. reverse- iterator rbegin() points to 1st element of the reverse sequence.
6. reverse- iterator rend(); points to one past last element of reverse sequence
7. const for both also exists.
148
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Vector also provides [ ](script) and at() but at() checks for rangewhere as [ ]
doesn’t (like c);
149
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Vector <int>v3=v2; ok
Vector <int>v4=10; error; explicit not allowed.
How to pass containers into a function …the 3 methods are here 3rd shouldn’t be
used..
Use of assign.
Char s[]=”abcd”;
As a list , vector also provides facility to add and delete element at any position.
It also supports
Bool empty();
Sizetype max_size();
Size_type capacity();
150
This watermark does not appear in the registered version - http://www.clicktoconvert.com
When vector grows till range of reserve it needn’t be relocated but reserve
has no impact on size.
HELPER FUNCTIONS
Comparison: we can write our own comparison function or by default < is used.
e.g. : template <class A > void sort(A a,A b); // default < used here
Template <class A> void sort(A a,A b,Cmp cmp); // cmp( ) will specify the
comparison rule.
Now how a and b i.e., 2 objects of A will be compared is specified in function cmp.
it must return bool.
151
This watermark does not appear in the registered version - http://www.clicktoconvert.com
To sort names we must write cmp ( ) , if we want alphabetic (dictionary) order. i.e., a A
b B. By default (ASCII) AB ab
Relation operation !=,<=,>,>= are not included by default. It is defined in std: rel-
operators namespace.
A list provides all the member types and operations offered by vector except
subscripting, capacity() and reserve(),at()
LIST’s operations:
Void splice(iterator pos, list &x’) moves all element from x to before pos in this list
without copying.
Void splice(iterator pos, list &x,iterator p); moves *p before pos from list x without
copying.
Similarly
Above list operations are stable i.e., relative order of equal elements doesn’t change.
Reference front();
Void push_front(const t&) ;
Reference front()const;
Void push_front(const t&) const ;
Void remove(const t& val) removes val from list.
Template<class pred> void remove_if(pred p); removes on condition.
Void unique();
Template <class BinPred> void unique(Binpredb);
Void reverse(); reverses the list.
152
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Fruit.remove_if(initial(‘l’));
Unique(initial (‘P’)); will give pear apple apple if list contain peer pear apple apple.
ADAPTOR:
Stack, queue are adaptor of containers vector , dequeue and list. Because they can be
defined efficiently in terms of 3 containers.
Associative array also called map or dictionary keeps pairs of keys, given only we
can get other.
Miscellaneous:-
An object is a package that contains related data and instructions. The data relates to
what the object represents, while the instructions define how this object relates to
other objects and itself.
2. What is a message?
A message is a signal from one object to another requesting that a computation take
place. It is roughly equivalent to a function call in other languages.
3. What is a class?
153
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A class defines the characteristics of a certain type of object. It defines what its
members will remember, the messages to which they will respond, and what form the
response will take.
4. What is an instance?
5. What is a super-class?
Given a class, a super-class is the basis of the class under consideration. The given
class is defined as a subset (in some respects) of the super-class. Objects of the given
class potentially posses all the characteristics belonging to objects of the super-class.
6. What is inheritance?
Inheritance is property such that a parent (or super) class passes the characteristics of
itself to children (or sub) classes that are derived from it. The sub-class has the option
of modifying these characteristics in order to make a different but fundamentally
related class from the super-class.
An object's message protocol is the exact form of the set of messages to which the
object can respond.
8. What is polymorphism?
These represent an object's private memory. They are defined in an object's class.
These represent a class's memory which it shares with each of its instances.
154
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A constructors and destructors are methods defined in a class that are invoked
automatically when an object is created or destroyed. They are used to initialize a
newly allocated object and to cleanup behind an object about to be removed.
It is the process of, and ability to redefine the way an object responds to a C++
operator symbol. This would be done in the object's class definition.
They are objects corresponding to a program's default input and output files.
155
This watermark does not appear in the registered version - http://www.clicktoconvert.com
package called an object. Objects are meant to represent logically separate entities
(like real world objects). Objects are grouped together (and defined by) classes. (This
is analogous to user defined data types in procedural languages.) Classes may pass-on
their "makeup" to classes derived from them. In this way, Objects that are of a similar
yet different nature need not be defined from scratch. Computation occurs though the
intercommunication of objects. Programming this way is like writing a play. First the
characters are defined with their attributes and personalities. Next the dialog is
written so that the personalities interact. The sum total constitutes a drama.
By using the extern "C" linkage specification around the C function declarations. You
should know about mangled function names and type-safe linkages. Then you should
explain how the extern "C" linkage specification statement turns that feature off
during compilation so that the linker properly links function calls to C functions.
Another acceptable answer is "I don't know. We never had to do that." Merely
describing what a linker does would indicate to me that you do not understand the
issue that underlies the question.
19. What are the differences between a C++ struct and C++ class?
The default member and base class access specifiers are different. This is one of the
commonly misunderstood aspects of C++. Believe it or not, many programmers think
that a C++ struct is just like a C struct, while a C++ class has inheritance, access
specifiers, member functions, overloaded operators, and so on. Some of them have
even written books about C++. Actually, the C++ struct has all the features of the
class. The only differences are that a struct defaults to public member access and
public base class inheritance, and a class defaults to the private access specifier and
private base class inheritance. Getting this question wrong does not necessarily
156
This watermark does not appear in the registered version - http://www.clicktoconvert.com
disqualify you because you will be in plenty of good company. Getting it right is a
definite plus.
20. How many ways are there to initialize an int with a constant?
Two.
There are two formats for initializers in C++ as shown in Example 1. Example 1(a)
uses the traditional C notation, while Example 1(b) uses constructor notation. Many
programmers do not know about the notation in Example 1(b), although they should
certainly know about the first one. Many old-timer C programmers who made the
switch to C++ never use the second idiom, although some wise heads of C++ profess
to prefer it.
A reader wrote to tell me of two other ways, as shown in Examples 2(a) and 2(b),
which made me think that maybe the answer could be extended even further to
include the initialization of an int function parameter with a constant argument from
the caller.
21. How does throwing and catching exceptions differ from using setjmp and
longjmp?
The throw operation calls the destructors for automatic objects instantiated since
entry to the try block. Exceptions are in the mainstream of C++ now, so most
programmers, if they are familiar with setjmp and longjmp, should know the
difference. Both idioms return a program from the nested depths of multiple function
calls to a defined position higher in the program. The program stack is "unwound" so
that the state of the program with respect to function calls and pushed arguments is
restored as if the calls had not been made. C++ exception handling adds to that
behavior the orderly calls to the destructors of automatic objects that were instantiated
as the program proceeded from within the try block toward where the throw
expression is evaluated. It's okay to discuss the notational differences between the
two idioms. Explain the syntax of try blocks, catch exception handlers, and throw
expressions. Then specifically address what happens in a throw that does not happen
in a longjmp. Your answer should reflect an understanding of the behavior described
in the answer just given.
One valid reason for not knowing about exception handling is that your experience is
exclusively with older C++ compilers that do not implement exception handling. I
would prefer that you have at least heard of exception handling, though.
It is not unusual for C and C++ programmers to be unfamiliar with setjmp/ longjmp.
Those constructs are not particularly intuitive. A C programmer who has written
recursive descent parsing algorithms will certainly be familiar with setjmp/ longjmp.
Others might not, and that's acceptable. In that case, you won't be able to discuss how
setjmp/longjmp differs from C++ exception handling, but let the interview turn into a
157
This watermark does not appear in the registered version - http://www.clicktoconvert.com
discussion of C++ exception handling in general. That conversation will reveal to the
interviewer a lot about your overall understanding of C++.
A good programmer will insist that the statement is never to be used if the class is to
be used by other programmers and instantiated as static, extern, or automatic objects.
That much should be obvious.
The code has two built- in pitfalls. First, if it executes in a member function for an
extern, static, or automatic object, the program will probably crash as soon as the
delete statement executes. There is no portable way for an object to tell that it was
instantiated on the heap, so the class cannot assert that its object is properly
instantiated. Second, when an object commits suicide this way, the using program
might not know about its demise. As far as the instantiating program is concerned, the
object remains in scope and continues to exist even though the object did itself in.
Subsequent dereferencing of the pointer can and usually does lead to disaster.
A reader pointed out that a class can ensure that its objects are instantiated on the
heap by making its destructor private. This idiom necessitates a kludgy DeleteMe
kind of function because the instantiator cannot call the delete operator for objects of
the class. The DeleteMe function would then use "delete this."
I got a lot of mail about this issue. Many programmers believe that delete this is a
valid construct. In my experience, classes that use delete this when objects are
instantiated by users usually spawn bugs related to the idiom, most often when a
program dereferences a pointer to an object that has already deleted itself.
A constructor that has no arguments or one where all the arguments have default
argument values. If you don't code a default constructor, the compiler provides one if
there are no other constructors. If you are going to instantiate an array of objects of
the class, the class must have a default constructor.
A constructor that accepts one argument of a different type. The compiler uses this
idiom as one way to infer conversion rules for a class. A constructor with more than
one argument and with default argument values can be interpreted by the compiler as
a conversion constructor when the compiler is looking for an object of the type and
sees an object of the type of the constructor's first argument.
158
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A copy constructor constructs a new object by using the content of the argument
object. An overloaded assignment operator assigns the contents of an existing object
to another existing object of the same class.
First, you must know that a copy constructor is one that has only one argument,
which is a reference to the same type as the constructor. The compiler invokes a copy
constructor wherever it needs to make a copy of the object, for example to pass an
argument by value. If you do not provide a copy constructor, the compiler creates a
member-by- member copy constructor for you.
You can write overloaded assignment operators that take arguments of other classes,
but that behavior is usually implemented with implicit conversion constructors. If you
do not provide an overloaded assignment operator for the class, the compiler creates a
default member-by- member assignment operator.
This discussion is a good place to get into why classes need copy constructors and
overloaded assignment operators. By discussing the requirements with respect to data
member pointers that point to dynamically allocated resources, you demonstrate a
good grasp of the problem.
There are three acceptable answers: "Never," "Rarely," and "When the problem
domain cannot be accurately modeled any other way."
There are some famous C++ pundits and luminaries who disagree with that third
answer, so be careful.
Let's digress to consider this issue lest your interview turn into a religious debate.
Consider an Asset class, Building class, Vehicle class, and CompanyCar class. All
company cars are vehicles. Some company cars are assets because the organizations
own them. Others might be leased. Not all assets are vehicles. Money accounts are
assets. Real-estate holdings are assets. Some real-estate holdings are buildings. Not
all buildings are assets. Ad infinitum. When you diagram these relationships, it
becomes apparent that multiple inheritance is an intuitive way to model this common
problem domain. You should understand, however, that multiple inheritance, like a
chainsaw, is a useful tool that has its perils, needs respect, and is best avoided except
when nothing else will do. Stress this understanding because your interviewer might
share the common bias against multiple inheritance that many object-oriented
designers hold.
159
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The simple answer is that a virtual destructor is one that is declared with the virtual
attribute.
28. Explain the “IS A” and “HAS A” class relationships. How would you
mplement each in a class design?
A specialized class "is a" specialization of another class and, therefore, has the ISA
relationship with the other class. An Employee ISA Person. This relationship is best
implemented with inheritance. Employee is derived from Person. A class may have
an instance of another class. For example, an Employee "has a" Salary, therefore the
Employee class has the HASA relationship with the Salary class. This relationship is
best implemented by embedding an object of the Salary class in the Employee class.
The answer to this question reveals whether you have an understanding of the
fundamentals of object-oriented design, which is important to reliable class design.
There are other relationships. The USESA relationship is when one class uses the
services of another. The Employee class uses an object (cout) of the ostream class to
display the employee's name onscreen, for example. But if you get ISA and HASA
right, you usually don't need to go any further.
When you are designing a generic class to contain or otherwise manage objects of
other types, when the format and behavior of those other types are unimportant to
their containment or management, and particularly when those other types are
unknown (thus the genericity) to the designer of the container or manager class. Prior
to templates, you had to use inheritance; your design might include a generic List
container class and an application-specific Employee class. To put employees in a
list, a ListedEmployee class is multiply derived (contrived) from the Employee and
List classes. These solutions were unwieldy and error-prone. Templates solved that
problem.
int __ = 0;
main() {
int ___ = 2;
printf("%d\n", ___ + __);
}
160
This watermark does not appear in the registered version - http://www.clicktoconvert.com
On GNU compiler both C and C++ give output as 2. I believe other C++ compiler
will complain "syntax error", whereas C compiler will give 2.
31. What is the difference between C and C++ ? Would you prefer to use one
over the other ?
32. What are the access privileges in C++ ? What is the default access level ?
The access privileges in C++ are private, public and protected. The default access
level assigned to members of a class is private. Private members of a class are
accessible only within the class and by friends of the class. Protected members are
accessible by the class itself and it's sub-classes. Public members of a class can be
accessed by anyone.
Data Encapsulation is also known as data hiding. The most important advantage of
encapsulation is that it lets the programmer create an object and then provide an
interface to the object that other objects can use to call the methods provided by the
object. The programmer can change the internal workings of an object but this
transparent to other interfacing programs as long as the interface remains unchanged.
Inheritance is the process of deriving classes from other classes. In such a case, the
sub-class has an 'is-a' relationship with the super class. For e.g. vehicle can be a
super-class and car can be a sub-class derived from vehicle. In this case a car is a
vehicle. The super class 'is not a' sub-class as the sub- class is more specialized and
may contain additional members as compared to the super class. The greatest
advantage of inheritance is that it promotes generic design and code reuse.
35. What is multiple inheritance ? What are it's advantages and disadvantages ?
Multiple Inheritance is the process whereby a sub-class can be derived from more
than one super class. The advantage of multiple inheritance is that it allows a class to
inherit the functionality of more than one base class thus allowing for modeling of
complex relationships. The disadvantage of multiple inheritance is that it can lead to a
lot of confusion when two base classes implement a method with the same name.
161
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Polymorphism refers to the ability to have more than one method with the same
signature in an inheritance hierarchy. The correct method is invoked at run-time
based on the context (object) on which the method is invoked. Polymorphism allows
for a generic use of method names while providing specialized implementations for
them.
When a class member is declared to be of a static type, it means that the member is
not an instance variable but a class variable. Such a member is accessed using
Classname.Membername (as opposed to Object.Membername). Const is a keyword
used in C++ to specify that an object's value cannot be changed.
Memory is allocated in C using malloc() and freed using free(). In C++ the new()
operator is used to allocate memory to an object and the delete() operator is used to
free the memory taken up by an object.
40. What is the difference between a shallow copy and a deep copy?
A shallow copy simply creates a new object and inserts in it references to the
members of the original object. A deep copy constructs a new object and then creates
in it copies of each of the members of the original object.
One that can be modified by the class even when the object of the class or the
member function doing the modification is const. Understanding this requirement
implies an understanding of C++ const, which many programmers do not have. I have
seen large class designs that do not employ the const qualifier anywhere. Some of
those designs are my own early C++ efforts. One author suggests that some
programmers find const to be such a bother that it is easier to ignore const than to try
to use it meaningfully. No wonder many programmers don't understand the power
and implications of const. Someone who claims to have enough interest in the
162
This watermark does not appear in the registered version - http://www.clicktoconvert.com
language and its evolution to keep pace with the ANSI deliberations should not be
ignorant of const, however.
A conversion constructor declared with the explicit keyword. The compiler does not
use an explicit constructor to implement an implied conversion of types. Its purpose is
reserved explicitly for construction.
The ability to determine at run time the type of an object by using the typeid operator
or the dynamic_cast operator.
Multiple providers of libraries might use common global identifiers causing a name
collision when an application tries to link with two or more such libraries. The name-
space feature surrounds a library's external declarations with a unique namespace that
eliminates the potential for those collisions. This solution assumes that two library
vendors don't use the same namespace, of course.
Yes. The ANSI committee added the bool intrinsic type and its true and false value
keywords and the wchar_t data type to support character sets wider than eight bits.
Other apparent new types (string, complex, and so forth) are implemented as classes
in the Standard C++ Library rather than as intrinsic types.
163
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(iv)
OPERATOR OVERLOADING
It allows us to provide an intuitive interface to users of our class, plus makes it possible
for templates to work equally well with classes and built- in/intrinsic types. Operator
overloading allows C/C++ operators to have user-defined meanings on user-defined types
(classes). Overloaded operators are syntactic sugar for function calls.
inline
int& Array::operator[] (unsigned i) // Some people don't like this syntax
164
This watermark does not appear in the registered version - http://www.clicktoconvert.com
{
...
}
Some people don't like the keyword operator or the somewhat funny syntax that goes
with it in the body of the class itself. But the operator overloading syntax isn't supposed
to make life easier for the developer of a class. It's supposed to make life easier
for the users of the class:
int main()
{
Array a;
[3] = 4; // User code should be obvious and easy to understand...
}
165
This watermark does not appear in the registered version - http://www.clicktoconvert.com
You should provide mixed- mode arithmetic operators only when they make logical sense
to users. For example, it makes sense to add a duration (say 35 days) to a date (say July
4, 1776), so you might define date + duration to return a Date. Similarly date - duration
could also return a Date. But duration - date does not make sense at the conceptual level
(what does it mean to subtract July 4, 1776 from 35 days?) so you should not define that
operator.
9.What is the rule to be followed when using constructive operators?
If you provide constructive operators, they should return their result by value.If it returns
by reference, that will probably run into lots of problems figuring out who owns the
referent and when the referent will get destructed. Doesn't matter if returning by reference
is more efficient; it is probably wrong. If you provide constructive operators, they should
not change their operands and allow promotion of the left hand operand.
10.While using x==y, what does it mean by ‘the objects need be behaviourally
equivalent’?
If you define x == y, then x == y should be true if and only if the two objects are
behaviorally equivalent. The term "behaviorally equivalent" means the observable
behavior of any operation or sequence of operations applied to x will be the same as
when applied to y. The term "operation" means methods, friends, operators, or just about
anything else you can do with these objects (except, of course, the address-of operator).
You won't always be able to achieve that goal, but you ought to get close, and you ought
to document any variances (other than the address-of operator).
11.Is it recommended to overload short-circuiting operatos?
Avoid overloading short-circuiting operators: x || y or x && y. The overloaded versions
of these do not short-circuit — they evaluate both operands even if the left- hand operand
"determines" the outcome, so that confuses users.
12.Why should we avoid overloading the comma operator?
Avoid overloading the comma operator: x, y. The overloaded comma operator does not
have the same ordering properties that it has when it is not overloaded, and that confuses
users.
13.How do I create a subscript operator for a Matrix class?
Use operator() rather than operator[].
When there are multiple subscripts, the cleanest way to do it is with operator() rather
than with operator[]. The reason is that operator[] always takes exactly one
parameter, but operator() can take any number of parameters (in the case of a rectangular
matrix, two parameters are needed).
166
This watermark does not appear in the registered version - http://www.clicktoconvert.com
15.How can I overload the prefix and postfix forms of operators ++ and --?
Via a dummy parameter.
Since the prefix and postfix ++ operators can have two definitions, the C++ language
gives us two different signatures.Both are called operator++(), but the prefix
version takes no parameters and the postfix version takes a dummy int.(Although
this discussion revolves around the ++ operator, the -- operator is completely
symmetric, and all the rules and guidelines that apply to one also apply to the
other.) However we must *not* make the postfix version return the 'this' object by
reference.
167
This watermark does not appear in the registered version - http://www.clicktoconvert.com
(v)
No.
Encapsulation != security.
The members and base classes of a struct are public by default, while in class, they
default to private. struct and class are otherwise functionally equivalent.
A struct simply feels like an open pile of bits with very little in the way of encapsulation
or functionality. A class feels like a living and responsible member of society with
intelligent services, a strong encapsulation barrier, and a well defined interface. Since
that's the connotation most people already have, you should probably use the struct
keyword if you have a class that has very few methods and has public data.
A big difference!
Suppose that List is the name of some class. Then function f() declares a local List object
called x:
void f()
{
List x; // Local object named x (of class List)
...
}
But function g() declares a function called x() that returns a List:
void g()
{
List x(); // Function named x (that returns a List) ... }
168
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Initialization lists. In fact, constructors should initialize as a rule all member objects in
the initialization list. One exception is discussed further down.
Consider the following constructor that initializes member object x_ using an
initialization list: Fred::Fred() : x_(whatever) { }. The most common benefit of doing this
is improved performance. For example, if the expression whatever is the same type as as
member variable x_, the result of the whatever expression is constructed directly inside
x_ - the compiler does not make a separate copy of the object. Even if the types are not
the same, the compiler is usually able to do a better job with initialization lists than with
assignments.
The other (inefficient) way to build constructors is via assignment, such as: Fred::Fred() {
x_ = whatever; }. In this case the expression whatever causes a separate, temporary
object to be created, and this temporary object is passed into the x_ object's assignment
operator. Then that temporary object is destructed at the ;. That's inefficient.
As if that wasn't bad enough, there's another source of inefficiency when using
assignment in a constructor: the member object will get fully constructed by its default
constructor, and this might, for example, allocate some default amount of memory or
open some default file. All this work could be for naught if the whatever expression
and/or assignment operator causes the object to close that file and/or release that memory
(e.g., if the default constructor didn't allocate a large enough pool of memory or if it
opened the wrong file).
Conclusion: All other things being equal, your code will run faster if you use
initialization lists rather than assignment
Here is something that always works: the {body} of a constructor (or a function called
from the constructor) can reliably access the data members declared in a base class and/or
the data members declared in the constructor's own class. This is because all those data
members are guaranteed to have been fully constructed by the time the constructor's
{body} starts executing.
Here is something that never works: the {body} of a constructor (or a function called
from the constructor) cannot get down to a derived class by calling a virtual member
function that is overridden in the derived class. If your goal was to get to the overridden
function in the derived class, you won't get what you want. Note that you won't get to the
override in the derived class independent of how you call the virtual member function:
explicitly using the this pointer (e.g., this->method()), implicitly using the this pointer
(e.g., method()), or even calling some other function that calls the virtual member
function on your this object. The bottom line is this: even if the caller is constructing an
object of a derived class, during the constructor of the base class, your object is not yet of
that derived class. You have been warned.
Here is something that sometimes works: if you pass any of the data members in this
object to another data member's initializer, you must make sure that the other data
member has already been initialized. The good news is that you can determine whether
the other data member has (or has not) been initialized using some straightforward
169
This watermark does not appear in the registered version - http://www.clicktoconvert.com
language rules that are independent of the particular compiler you're using. The bad news
it that you have to know those language rules (e.g., base class sub-objects are initialized
first (look up the order if you have multiple and/or virtual inheritance!), then data
members defined in the class are initialized in the order in which they appear in the class
declaration). If you don't know these rules, then don't pass any data member from the this
object (regardless of whether or not you explicitly use the this keyword) to any other data
member's initializer! And if you do know the rules, please be careful.
7.Why are classes with static data members getting linker errors?
Because static data members must be explicitly defined in exactly one compilation unit.
If you didn't do this, you'll probably get an "undefined external" linker error. For
example:
// Fred.h
class Fred {
public:
...
private:
static int j_; // Declares static data member Fred::j_
...
};
1 The linker will holler at you ("Fred::j_ is not defined") unless you define (as
opposed to merely declare) Fred::j_ in (exactly) one of your source files:
// Fred.cpp
#include "Fred.h"
// Alternatively, if you wish to use the implicit 0 value for static ints:
// int Fred::j_;
The usual place to define static data members of class Fred is file Fred.cpp (or Fred.C or
whatever source file ext
No.
You can have only one destructor for a class Fred. It's always called Fred::~Fred(). It
never takes any parameters, and it never returns anything.
You can't pass parameters to the destructor anyway, since you never explicitly call a
destructor
170
This watermark does not appear in the registered version - http://www.clicktoconvert.com
10.What is a friend?
When the compiler inline-expands a function call, the function's code gets inserted into
the caller's code stream (conceptually similar to what happens with a #define macro).
This can, depending on a zillion other things, improve performance, because the
optimizer can procedurally integrate the called code - optimize the called code into the
caller.
There are several ways to designate that a function is inline, some of which involve the
inline keyword, others do not. No matter how you designate a function as inline, it is a
request that the compiler is allowed to ignore: it might inline-expand some, all, or none of
the calls to an inline function.
By overloading standard operators on a class, you can exploit the intuition of the users of
that class. This lets users program in the language of the problem domain rather than in
the language of the machine.
The ultimate goal is to reduce both the learning curve and the defect rate.
171
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof, which
is technically an operator). C++ adds a few of its own operators, most of which can be
overloaded except :: and .*.
No: at least one operand of any overloaded operator must be of some user-defined type
(most of the time that means a class).
But even if C++ allowed you to do this, which it doesn't, you wouldn't want to do it
anyway since you really should be using a std::string- like class rather than an array of
char in the first place since arrays are evil.
Yes.
Consider the following function:
int f(char a, float b);
The type of this function is different depending on whether it is an ordinary function or a
non-static member function of some class:
• Its type is "int (*)(char,float)" if an ordinary function
• Its type is "int (Fred::*)(char,float)" if a non-static member function of class Fred
19.What is a reference?
It chains these method calls, which is why this is called method chaining.
The first thing that gets executed is object.method1(). This returns some object, which
might be a reference to object (i.e., method1() might end with return *this;), or it might
be some other object. Let's call the returned object objectB. Then objectB becomes the
this object of method2().
The most common use of method chaining is in the iostream library. E.g., cout << x << y
works because cout << x is a function that returns cout.
172
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Use references when you can, and pointers when you have to.
References are usually preferred over pointers whenever you don't need "reseating". This
usually means that references are most useful in a class's public interface. References
typically appear on the skin of an object, and pointers on the inside.
The exception to the above is where a function's parameter or return value needs a
"sentinel" reference. This is usually best done by returning/taking a pointer, and giving
the NULL pointer this special significance .
A template is a cookie-cutter that specifies how to cut cookies that all look pretty much
the same (although the cookies can be made of various kinds of dough, they'll all have the
same basic shape). In the same way, a class template is a cookie cutter for a description
of how to build a family of classes that all look basically the same, and a function
template describes how to build a family of similar looking functions.
25.How can C++ achieve dynamic binding yet also static typing?
When you have a pointer to an object, the object may actually be of a class that is derived
from the class of the pointer (e.g., a Vehicle* that is actually pointing to a Car object; this
is called "polymorphism"). Thus there are two types: the (static) type of the pointer
(Vehicle, in this case), and the (dynamic) type of the pointed-to object (Car, in this case).
Static typing means that the legality of a member function invocation is checked at the
earliest possible moment: by the compiler at compile time. The compiler uses the static
type of the pointer to determine whether the member function invocation is legal. If the
type of the pointer can handle the member function, certainly the pointed-to object can
173
This watermark does not appear in the registered version - http://www.clicktoconvert.com
handle it as well. E.g., if Vehicle has a certain member function, certainly Car also has
that member function since Car is a kind-of Vehicle.
Dynamic binding means that the address of the code in a member function invocation is
determined at the last possible moment: based on the dynamic type of the object at run
time. It is called "dynamic binding" because the binding to the code that actually gets
called is accomplished dynamically (at run time). Dynamic binding is a result of virtual
functions.
overloading occurs when two or more methods use the same name (but different
parameter lists),such that both methods are available side by side in the sam
eclass;overriding occurs when a subclass method and a superclass method use yje same
name (and matching parameter lists),such that the subclass mathod blocks out the
superclass method.
The super keyword gives a class explicit access to the constructors ,methods ,and
variables of its superclass.
A final class is a classs that is declared with final keyword so that it can never be
subclassed.
using final keyword in thwe java language has the general meaning that you define an
entity once and cannot change it or derve from it later.more specifically:
>a final class cannot be subclassed.
>a final method cannot be overridden.
>a final variable cannot change from its initialized value.
29.what is an interface?
concrete class:
i)specifies the full set of methods for an object.
ii)implements all of its methods.
iii)can have instances.
iv)can have subclasses.
174
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Abstract class:
i)specifies the full set of methods for an object
ii)implements none,some ,or all of its methods.
iii)can't have instances.
iv)must have subclasses;useless without them
Interface:
i)specifies a subset of methods for an object.
ii)implements none of its methods.
iii)can't have instances
iv)can't have subclasses;must have classes that implement it;useless without them.
The instanceof keyword is a two -argument operator that tests whether the run time type
of its first argument is assignment compatible with its second argument.
A package is a collection of classes and inetrfaces that provides a high- level layer of
access protection and name space management.
The f suffix directs the compiler to create a float value from a sequence of characters
representing a floating point number (a float literal) - otherwise the compiler would by
default create either a double value or an int values.
34.Are java objects are pointers?
no:java objects are objects (typed containers for data plus associated methods ) but the
java language lets you access objects only via references.
36.what is an exception?
175
This watermark does not appear in the registered version - http://www.clicktoconvert.com
37.what is the difference between a runtime exception and a plain exception -why
don't runtime exceptions have to be declared?
The java laguage specifies that all runtime exceptions are exempted from the standard
method declarations and compiler checks.such exceptions belong more to the system as a
whole than to the method that happens to be executing when the exception is thrown.
The java virtua machine invokes the main method of java class as its starting point of
execution.
Java bytecodes encode are a language of machine instructions understood by the java
virtual machine and usually generated (compiled) from java language source code.
40.what is an applet?
An applet is a java -compatible program that you can embed in a web page. it is usually
composed of several pieces : 1.code :- the java class files that represent the executable
code of the applet. 2.other resources:-data needed by the applet,including images and
sounds.
An abstract class is a class designed with implementation gaps for subclasses to fill in.an
abstract class is deliberately incomplete. it defines a skeleton that various subclasses can
flesh out with custoomized implementation details.The different concrete subclasses
provide a family of variants.
An object reference is essentially an object pointer with strong restrictions for integrity
and safety.An object reference provides two kinds of information to be the run-time
system:
1.a pointer to the object's instance information - its data.
2.a pointer to the object's class information - its run-time type and its table of methods.
44. What is the difference between an instance variable and class variable?
176
This watermark does not appear in the registered version - http://www.clicktoconvert.com
An instance variable represents a separate data item for each instance of a class, whereas
a class variable represents a single data item shared by the class and all its instances.
Component and container are the two fundamental classes in the abstract window
toolkit(AWT).component instances represent individual user- interface elements and
container instances represent groups of components.
177
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Part – V
DATA
STRUCTURES
AND
ALGORITHM
178
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Topics Covered:-
179
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A data type is a well-defined collection of data with a well-defined set of operations on it.
A data structure is an actual implementation of a particular abstract data type. Abstraction
can be thought of as a mechanism for suppressing irrelevant details while at the same
time emphasizing relevant ones.
2. What is an algorithm?
There are several data structures that are available and the choice of an appropriate one
depends on the requirement. Some of the data structures that are commonly used include:
Ø Arrays
Ø Linked Lists
Ø Stacks
Ø Queues
Ø Trees
Ø Graphs
A static data structure has a fixed size. Arrays are static; once you define the number of
elements it can hold, the number doesn’t change. A dynamic data structure grows and
180
This watermark does not appear in the registered version - http://www.clicktoconvert.com
5. Introduction to Arrays
The simplest type of data structure is a linear array and most often it is the only data
structure that is provided in any programming language. An array can be defined as a
collection of homogenous elements, in the form of index/value pairs, stored in
consecutive memory locations. An array always has a predefined size and the elements of
an array are referenced by means of an index / subscript.
An array can be of more than one dimension. There are no restrictions to the number of
dimensions that we can have. But as the dimensions increase the memory requirements
increase drastically which can result in shortage of memory. Hence a multidimensional
array must be used with utmost care.
For example the following declaration
int a[50][50][50] will result in occupying 50 * 50 * 50 = 1,25,000 * 4 = 5,00,000 bytes of
memory.
8. Memory Organization
The memory arrangement for a multidimensional array is very similar to linear arrays.
Only the way in which we access the data varies i.e. if it is a 2 dimensional array for
example, then it can be accessed by using 2 indexes one, which represents the row and
the other representing the column. If A is a 2 dimensional array defined like int arr[3][3];
The maximum elements that this array can hold is 3 * 3 which is 9 elements and the
181
This watermark does not appear in the registered version - http://www.clicktoconvert.com
9. Advantages
Limitations
Ø A pointer is nothing but a variable, which can hold the address of another
variable.
int * p;
p = &a;
This stores the address of the variable ‘a’ in the pointer ‘p’, 1000 in our example.
A pointer is a datatype whose value is used to refer to ("points to") another value stored
elsewhere in the computer memory. Obtaining the value that a pointer refers to is called
dereferencing the pointer. In the above example the * operator is used to get the value of
the pointer p.
182
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Whenever a value is assigned to a pointer the * operator has to be used so that it gets
stored in the address pointed by p. Whenever an address is assigned do not use the * as
we need to store an address only inside p and not at where p is pointing to.
*p = 50;
Observe the results of the following printf statements
printf(“P = %u”, p);
printf(“&P = %u”, &p);
printf(“*p = %d”, *p);
printf(“a = %d”, a);
The results of the first two printf statements are exactly similar to the previous ones. But
the third printf statement prints the value 50. Surprisingly the last printf statement also
prints 50 and not 10 which was assigned earlier to a. This is because *p refers to the place
where p is pointing. In other words *p denotes that the value will be stored on the address
pointed by p which is the same as the address of the variable a. Thus with the help of the
pointer it is possible to change the value of the variable/memory location it is pointing to.
If p is a pointer and a is a variable defined as
int *p;
int a;
then the following assignments are invalid :
*p = &a; // as *p can hold only a value and not an address
p = a; // as P can hold only an address and not a value
Note: *(&a) is equal to a. [ *(&a) = a ] this means the content of the address of ‘a’ is
nothing but ’a’ itself.
If p is a pointer then,
Ø Whenever we refer the pointer as p we are referring to the address that p is
pointing to.
Ø Whenever we refer the pointer as &p we are referring to the address of the pointer
variable.
Ø Whenever we refer the pointer as *p we are referring to the value pointed by the
address that the pointer contains.
Note: When more than one value needs to be returned from a method, pointers are the
only way through which it is possible. So from the above example let us look into the
definition of Passing by value and passing by reference
Having seen how to use pointer with variables let’s see how pointers can be used with
arrays. Just like a pointer can point to a variable, it can also point to an array. It really
doesn’t matter as to what it is pointing to as long as a valid address is assigned to a
pointer.
183
This watermark does not appear in the registered version - http://www.clicktoconvert.com
As the internal representation of a multi dimensional array is also linear. A pointer can
point to an array of any dimension. Only the way in which we access the pointer varies
184
This watermark does not appear in the registered version - http://www.clicktoconvert.com
according to the dimension. For example if arr is a2 dimensional array of 3 rows and 3
cols
int arr[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
then the following assignment is valid to make
int* p = arr;
The elements can be accessed using the following loop
for(i =0; i< 9; i++)
{
printf(“Value = %d\n”, *(p+i));
}
Just like an integer pointer a character pointer is a pointer, which is capable of holding
the address of a character variable. Suppose if we have a character array declared as
char name[30] = {“Data Structures”};
and if we need to store the address of this array we need a character pointer declared as
follows
char *p = NULL;
Once the pointer is declared we need to assign the address of the array to this pointer. We
know that when an array is referenced by its name we are referring to the address of the
0th element i.e. p = name; will assign the address of the 0th element to p.
Pointers can be used interchangeably with arrays.
So far we have been discussing about a pointer pointing to another variable or array.
Can’t we directly make use of pointers? i.e.
int *p;
followed by
scanf(“%d”, p);
Note that there is no ‘&’ in the scanf for the pointer as referring a pointer by its name
actually refers to the address it points to. The above statements are treated valid by the
compiler and the code might execute properly as well.
But this is really a dangerous programming. Because p is a pointer and we have not
assigned anything to it, it might be having some value in it. Trying to store a value in that
address can cause serious damage to the system, as we are not aware of what p will be
pointing to. So it is always a better programming practice to initialize any pointer
declaration to NULL i.e. int *p = NULL;
This ensures that the pointer is not pointing to anywhere. Even after this we should not
accept values from the user because there is no valid memory location for storing this
value. In such cases before we start using the pointer we should allocate memory to it.
Malloc() is the function used for memory allocation in C. malloc() takes one argument
that is the number of bytes to allocate. Suppose P is a pointer then
int *p;
p = (int *)malloc(sizeof(int));
185
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The above assignment will allocate memory for holding an integer value. Remember
whenever malloc is used for memory allocation the system allocates memory from the
heap and not from the stack. So it is the responsibility of the user to free the memory that
is allocated. For freeing the allocated memory the function used is, free(<pointer
variable>);
Most often in real time situations the number of rows as well as columns might vary
dynamically. This being the case the above approach cannot be used. In such situations
we can make use of pointer to pointers. A pointer to pointer is nothing but a pointer,
which is capable of holding the address of another pointer variable in it. As discussed
earlier a pointer is also a variable and hence it is quite possible to hold the address of the
pointer also in another pointer. A pointer to pointer can be declared as,
int **p;
The above declaration means that p is a pointer, which can hold the address of another
integer pointer ( a pointer which can hold the address of an integer ).
As such there is no restriction imposed by the compiler as to how many levels we can go
about in using a pointer. i.e. the following declaration is perfectly valid
int *****p; However beyond 3 levels if we make use of pointers then it will make the
code highly complex and un- maintainable.
A pointer can be used with a structure just like any other data type. The only difference is
in the way we access the data members of the structure. Suppose if we have a structure as
typedef struct player{
186
This watermark does not appear in the registered version - http://www.clicktoconvert.com
char name[30];
int age;
}player;
player p1;
Then we can access the members as,
p1.name and p1.age
Suppose if we change the declaration as
Player* p1;
then for accessing the members of the structure we can follow either one of the following
approaches
p1->name or (*p1).name
p1->age (*p1).age
Just like variables have address functions also have address. This means that we can
make use of a pointer to represent the address of a function as well. If we use a pointer to
represent the address of an integer we declare it as int* p. Similarly if it is a character
pointer we declare it as char* p. But if it is a function pointer how can we declare it.
Suppose we have a function as
187
This watermark does not appear in the registered version - http://www.clicktoconvert.com
22. Advantages
Ø It gives direct control over memory and thus we can play around with memory by
all
Ø possible means. For example we can refer to any part of the hardware like
keyboard,
Ø video memory, printer, etc directly.
Ø As working with pointers is like working with memory it will provide enhanced
performance
Ø Pass by reference is possible only through the usage of pointers
Ø Useful while returning multiple values from a function
Ø Allocation and freeing of memory can be done wherever required and need not be
done in advance
23. Limitations
Ø If memory allocations are not freed properly it can cause memory leakages
Ø If not used properly can make the program difficult to understand
Back tracking algorithms are those places where we need to repeat a process going back
and forth. One famous example for back tracking is the eight-queen problem. The
problem is to place 8 queens on a chessboard without clashing each other. If we do it
188
This watermark does not appear in the registered version - http://www.clicktoconvert.com
normally on chessboard how we will go about doing it. First we can place up to 5 queens
easily. When we are about to place the 6th queen we might not be having any place for it
to be placed. In such situations we will take the 5th queen and place it on some other
place and we will try to place the 6th one again. If we still couldn’t locate a place then we
will replace the 4th queen also on a different place and then we will be trying all possible
permutation combinations. Similarly we will be trying going back and forth till we
successfully place all the queens. Such kinds of problems are called as back tracking
problems. It is on these places recursion can play its role wonderfully and make the
algorithm look compact without much of memory or performance overhead.
A stack is an ordered list in which items are inserted and removed at only one end called
the TOP. There are only 2 operations that are possible on a stack. They are the ‘Push’ and
the ‘Pop’ operations. A Push operation inserts a value into the stack and the Pop
operation retrieves the value from the stack and removes it from the stack as well.
Ø An example for a stack is a stack of plates arranged on a table. This means that
the last item to be added is the first item to be removed. Hence a stack is also
called as Last-In-First-Out List or LIFO list. To understand the usage of a stack
let us see what does the system does when a method call is executed:
Ø Whenever a method call is executed the compiler needs to know the return
address for it to resume from the place where it left off in the calling method.
189
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A push operation is for inserting an element in to a stack. Elements are always inserted in
the beginning of a stack.
190
This watermark does not appear in the registered version - http://www.clicktoconvert.com
If you had a careful look over this code this is nothing but equal to inserting an element at
the beginning of a list.
A pop operation is basically used for retrieving a value from the stack. This also removes
the element from the Stack.
int pop()
{
int iData;
node* pTempNode = NULL;
if (pTop == NULL)
{
iData = -1;
printf(“Stack Empty”);
}
else
{
pTempNode = pTop;
iData = pTop->iData;
pTop = pTop->pNext;
free(pTempNode);
}
return iData;
}
Evaluating Expressions
In normal practice any arithmetic expression is written in such a way that the operator is
placed between its operands. For example (A + B) * (C + D) Such kind of expressions is
called as infix notation. Polish notation refers to the notation in which the operator is
placed before the operands. For example the above expression can be written as
*+AB+CD The idea is, whenever we write expressions in this notation, parenthesis are
not required for determining the priority of the expressions. Let us see the steps involved
in the conversion (A+B)*(C+D) = (+AB)*(+CD) = *+AB+CD Reverse polish notation is
exactly the opposite of polish notation i.e. the operator is always placed after the
operands. For example, the above expression can be written in Reverse Polish Notation
as
(A+B) * (C+D) = (AB+) * (CD+) = AB+CD+* Whenever an expression is evaluated by
the system it usually performs it by means of 2 steps. First it converts any expression into
prefix or postfix notation and then it evaluates the expression as it makes the job much
simpler. Converting an infix expression to postfix or prefix expression makes use of
191
This watermark does not appear in the registered version - http://www.clicktoconvert.com
stacks extensively. The following is the algorithm for doing this conversion. A complete
program requires a lot more than what is described in the algorithm.
PostFixExpression ConvertToPolishNotation(InfixExpression)
{
1. Push “(“ onto the STACK and add “)” to the end of the InfixExpression
2. Scan the InfixExpression from left to right and repeat steps 3 to 6 for each element of
InfixExpression until the stack is empty
3. If an operand is encountered, add it to Postfix Expression
4. If a left parenthesis is encountered, push it to STACK
5. If an operator XX is encountered
a. Pop from STACK repeatedly and add it to Postfix expression which has the
same/ higher precedence than XX.
b. Add XX to STACK
6. If a right parenthesis is encountered, then
a. Pop from STACK repeatedly and add it to Postfix Expression until a left
parenthesis is encountered.
b. Remove the left parenthesis
7. Exit
}
A Queue is an ordered list in which all insertions can take place at one end called the rear
and all deletions take place at the other end called the front. The two operations that are
possible in a queue are Insertion and Deletion. A real time example for a queue is people
standing in a queue for billing on a shop. The first
person in the queue will be the first person to get the service. Similarly the first element
inserted in the queue will be the first one that will be retrieved and hence a queue is also
called as First In First Out or FIFO list.
192
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The node of a queue will have 2 parts. The first part contains the data and the second part
contains the address of the next node. This is pretty much similar to a linear list
representation. But in a queue insertions and deletions are going to occur on two different
ends. If we have only
one pointer called START then for every insertion we need to traverse the complete
queue as insertions are always on the end and hence will be time consuming. To avoid
this we are going to have 2 pointers to represent a queue, one pointer is called the
FRONT which will always be pointing to the first element and is used for deletions, and
the other pointer called REAR which will always be pointing to the last element in the
queue and is used in insertions.
typedef struct node
{
int iData;
struct node* pNext;
}node;
node* pFRONT = NULL, *pREAR = NULL;
When the queue is empty, both FRONT and REAR will be pointing to NULL. When
there is only one element in the queue, then both FRONT and REAR will be pointing to
the same element.
193
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The deletion is the only way through which we can retrieve values from a queue. Along
with retrieving the value this will remove the entry from the queue. Deletions always
happen in the FRONT end.
1. Store the node pointed by FRONT in a temporary pointer
2. Make Front as Front’s next
3. Delete the node pointed by temporary pointer
4. If all the nodes are deleted from the queue make the FRONT and REAR as NULL
int QDelete()
{
int iData = -1;
node* pDelNode = NULL;
if (pFRONT == NULL)
{
printf(“Queue Empty”);
}
else
{
iData = pFRONT->iData;
pDelNode = pFRONT;
pFRONT = pFRONT->pNext;
if (pFRONT == NULL)
{
pREAR = NULL;
}
free(pTempNode);
}
return iData;
}
39. Deque
194
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A Deque is a queue in which insertions and deletions can happen at both ends of a queue.
A deque, or double-ended queue is a data structure, which unites the properties of a
queue and a stack. Like the stack, items can be pushed into the deque; once inserted into
the deque the last item pushed in may be extracted from one side (popped, as in a stack),
and the first item pushed in may be pulled out of the other side (as in a queue).
The push (insert/assign) and pop operation is done at both the end that is start and end of
the deque. The following pictures show how a deque is formed based on this change in
algorithm. Initially the base and end pointer will be pointing to NULL or 0 (zero). We
define two pointers, p_base and p_end to keep track of front and back of the deque.
Initially when the deque object is created, both p_base and p_end would point to NULL.
When the first node is created, p_base assumes the position and p_end starts pointing to
p_base. The next and previous pointer of p_base assumes NULL or 0(zero). Further
insertions happen at p_end.
A priority queue is the one in which each element will have a priority associated with it.
The element with the highest priority is the one that will be processed/deleted first. If two
or more nodes have the same priority then they will be processed in the same order as
they were entered in to the queue.
In real time systems most often the number of elements will not be known in advance.
The major drawback of an array is that the number of elements must be known in
advance. Hence an alternative approach was required. This give rise to the concept called
linked lists. A linear list is a linear collection of data elements called nodes, where the
linear order is given by means of pointers. The key here is that every node will have two
parts: first part contains the information/data and the second part contains the link/address
of the next node in the list. Memory is allocated for every node when it is actually
required and will be freed when not needed.
195
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Self-referential structures contain pointers within the structs that refer to another identical
structure. Linked lists are the most basic self- referential structures. Linked lists allow you
to have a chain of structs with related data.
This means that for traversing through the list we need to know the starting point always.
This is achieved by having a START pointer always pointing to the first element in the
list.
196
This watermark does not appear in the registered version - http://www.clicktoconvert.com
{
int iData;
struct node* pNext;
}node;
node* pSTART = NULL;
The node structure contains the data and the pointer for the next node. The address of the
next node must again be of type node and hence we have a pointer to the node within
node itself. Such kind of structures which refers to itself are called as Re-Directions or
Self Referential1 Structures.
Insertion logic varies depending on where in the list the element is going to be inserted,
first, middle or at the end. In all situations it is as simple as making the pointer point to
different nodes and hence insertion at any place will be much faster.
197
This watermark does not appear in the registered version - http://www.clicktoconvert.com
The next step is deleting a node from a list. Again deletion logic varies depending on
from where the node is getting deleted, beginning, middle or at the end.
1. Store the node to be deleted in a temporary pointer
2. Make START point to next node in the list
3. Delete the node pointed by temporary pointer
198
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A linked list is used typically in computer applications for memory allocations. The
system keeps tracks of all the memory available in the system with the help of a list. This
area of memory is called as the memory pool. As and when the user requests for memory
the system allocates memory to the user from this available pool. Once allocated these
blocks will be deleted from the available list. Once the user frees the memory again the
memory will be added to the list. In general linked lists are used in almost all places
whenever a collection of elements are required and when the number of elements in the
collection is not known in advance.
Advantages
Ø The number of elements in the linked lists need not be known in advance. As and
when required elements can be added to a list
Ø Insertions and deletions are much faster in a linked list as there is no physical
movement of elements of a list.
Limitations
Ø Searching a list is always sequential and hence it is a time consuming operation
Ø Traversal is always possible in only one direction.
Circular linked lists are very similar to a linear list except that the last node will be
pointing to the first node again instead of NULL. So care should be taken while doing the
199
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Assuming that someNode is some node in the list, this code iterates through that list
starting with someNode:
Forwards
node := someNode
do
<do something with node.value>
node := node.next
while node not someNode
With the linked list traversal is possible in only one direction. This limitation is overcome
with the help of doubly linked lists. A doubly linked list is a list in which each node will
have 3 parts: one part containing the information / data, one part containing the
pointer/address of next node and one part containing the pointer / address of previous
node. In addition to the START pointer, which contains the first node there will also be a
TAIL pointer pointing to the last node in the list.
200
This watermark does not appear in the registered version - http://www.clicktoconvert.com
int iData;
struct node* pNext;
struct node* pPrev;
}node;
node* pSTART = NULL, *pTAIL = NULL;
The node of a doubly linked list will have 2 pointers apart from the data, one for pointing
to the previous element and the other for pointing to the next element in the list. There
will also be a TAIL pointer pointing to the last node in the list. It is possible for us to
traverse from the beginning of a list till the end or from the end of the list to the
beginning. The end of the list is identified with the help of a NULL value in the next /
previous parts.
Inserting an element in a doubly linked list involves just changing the pointers unlike
arrays where every element after the inserted element needs to be shifted once. Hence
inserting an element in a doubly linked list is much faster than inserting a node in an
array.
57. Steps for inserting an element in the middle of a doubly linked list
201
This watermark does not appear in the registered version - http://www.clicktoconvert.com
58. Steps for inserting an element at the end of a doubly linked list
202
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Deleting a node from a list is as simple as changing the links. Hence deleting a node from
a list is much faster when compared to arrays. Like insertion the deletion logic also varies
depending on from where in the list we are going to delete the node.
203
This watermark does not appear in the registered version - http://www.clicktoconvert.com
int iPos = 1;
if (iLoc == 1)
{
removeHead();
}
else
{
for (pTempNode = pSTART; iPos < iLoc && pTempNode->pNext != NULL;
pTempNode = pTempNode->pNext, iPos++);
if (iLoc == iPos)
{
pDelNode = pTempNode->pNext;
pTempNode->pNext = pDelNode->pNext;
if (pDelNode == pTAIL)
{
pTAIL = pTAIL->pNext;
}
else
{
pDelNode->pNext->pPrev = pTempNode;
}
free(pDelNode);
}
}
}
204
This watermark does not appear in the registered version - http://www.clicktoconvert.com
pTAIL = pTAIL->pNext;
if (pTAIL == NULL)
{
pSTART = NULL;
}
free(pDelNode);
}
}
Ø A doubly linked list can be used in all the places where we use a linear list if the
traversal happens frequently in both the directions.
Advantages
Ø The number of elements in a doubly linked list need not be known in advance. As
and when required elements can be added to a list
Ø Insertions and deletions are much faster as there is no physical movement of
elements of a list.
Ø Traversal is possible in both the directions unlike a linear list where the traversal
is possible in only one direction
Limitations
205
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Ø Takes up additional memory for storing the previous pointer in each node
Ø Makes the insertion and deletion logic a bit complex
A tree is a non- linear data structure. This structure is mainly used to represent data
containing a hierarchical relationship between elements like family tree, organization
chart etc. Some of the commonly used terms and their definitions with respect to a tree
are as follows:
67. Definitions
Degree of a node
The number of sub trees of a node is called its degree. In the diagram shown above the
degree of A is 3, B is 3, C is 0 , D is 2, ...
Siblings
The children of the same parent are called as siblings
206
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Level
The level of the root node is 1. If a node is at level L then its children are at level L + 1.
Forest
A forest is a set of n>= disjoint trees.
A binary tree T is defined as a finite set of elements, called nodes, such that:
Ø T is empty or
Ø T contains a distinguished node R, called the root of T, and the remaining nodes
of T forms an ordered pair of disjoint binary trees T1 and T2.
Ø If T does contain a root R, then the two trees T1 and T2 are called the left and
right sub trees of R
Graphical Representation
A binary tree is said to be complete if all its levels except the last level have the
maximum number of possible nodes and if all the nodes at the last level appear as far left
as possible.
207
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A binary tree T is called a binary search tree if each node of T has the property: The
value at N is greater than every value in the left sub tree of N and is less than every value
in the right sub tree of N.
Inserting an element in a binary search tree involves creating a new node and re-
organizing the parent nodes link to accommodate the new node. Typically insertions will
always be on a terminal node. We will never be inserting a node in the middle of a binary
search tree.
1. If the tree is empty, then make the root node point to this node
2. If the tree contains nodes then compare the data with node’s data and take appropriate
path till the terminal node is reached
3. If data < node’s data then take the left sub tree otherwise take the right sub tree
4. When there are no more nodes add the node to the appropriate place of the parent
node.
208
This watermark does not appear in the registered version - http://www.clicktoconvert.com
{
pRoot = pParent;
}
}
else
{
if (iData < pParant->iData)
{
insert(pParent->pLeft, iData);
}
else
{
insert(pParent->pRight, iData);
}
} } // end of function …
The logic for deleting an element from a binary tree varies depending on from where we
are going to delete the node, whether it is a leaf node, a node with a single child or a node
in the middle.
Ø If the node being deleted is a terminal node then deletion is a straightforward
procedure of just making the parent node point to NULL.
Ø If the node being deleted has only one child then the parent node will have to
point to the child node of the node being deleted.
Ø If the node being deleted has both the children then we first need to find the
inorder successor of the node being deleted and replace the node being deleted
with this node. (The inorder successor of a node can be obtained by taking the
right node of the current node and traversing in the left till we reach the left most
nodes.)
Ø If the node N has no children, then change the location of this node in the parent
node to NULL.
Ø If the node N has exactly one child, then change the location of this node, in the
parent, to child of N.
Ø If the node N has 2 children, then
a. Store N in a temporary pointer
b. Determine the inorder successor of N ( an inorder successor is obtained by
moving to the right node and finding the left most node of that node )
c. Make the left of this node point to left of N
d. Make the right of this node point to right of N
209
This watermark does not appear in the registered version - http://www.clicktoconvert.com
210
This watermark does not appear in the registered version - http://www.clicktoconvert.com
211
This watermark does not appear in the registered version - http://www.clicktoconvert.com
A tree can be used in a wide variety of applications, which includes set representations,
decisionmaking, game trees, etc. Within the context of programming language execution,
compilers utilize tree structures to obtain forms of an arithmetic expression, which can be
evaluated efficiently. The in-order traversal of the binary tree for an arithmetic expression
produces the infix form of the expression, while the pre-order and post-order traversal
lead to the prefix and postfix (reverse Polish) forms of the expression respectively. The
advantage of reverse Polish notation is that arithmetic expressions can be represented in a
way, which can be simply read from left to right without the need for parentheses. For
example, consider the expression a * (b + c). This expression can be represented by the
binary tree in the following way,
*
/\
a+
/\
bc
If we perform a post-order traversal in which we traverse the left branch of the tree, the
right branch, followed by the node, we immediately recover the reverse Polish form of
the expression, namely abc+*. This expression can then be evaluated using a stack.
Starting from the left of the expression, each time an operand (one of the numerical
values a, b or c in this example) is found, it is placed on the top of the stack. When an
212
This watermark does not appear in the registered version - http://www.clicktoconvert.com
operator (* or +) is read, the top two elements are removed form the stack and the
appropriate operator applied to them and the result placed on the stack. When the
complete expression has been evaluated, the stack will contain a single item, which is the
result of evaluating the expression.
Before getting into the details of a Graph let’s see few of the commonly used terms with
respect to graph and their definitions:
If e = [u, v] then the nodes u and v are called endpoints of e and u and v are said to be
adjacent nodes or neighbors.
81. Definitions
Degree of a node
The degree of a node u is the number of edges containing u. If deg(u) = 0, then the node
is called as an isolated node.
Path
A Path P of length n from node u to v is defined as a sequence of n + 1 nodes. P = (V0,
V1,....Vn)
Closed Path
A path P is said to be closed if V0 = Vn
Simple Path
The path P is said to be simple, if all the nodes are distinct, with the exception that v0
may equal v1, that is, P is simple if the nodes v0, v1, ... vn-1 are distinct and the nodes
v0, v1, ...vn are distinct.
Cycle
A cycle is a closed simple path.
Connected Graph
A graph G is connected if and only if there is a simple path between any two nodes in G.
Complete Graph A graph G is said to be complete if every node u in G is adjacent to
every other node v in G. A graph G is said to be labeled, if its edges are assigned data. A
213
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Multiple edges
Distinct edges e and e’ are called multiple edges if they connect the same end points. i.e.
if e = [u, v] and e’ = [u, v].
Loops
An edge e is called a loop if it has identical endpoints. i.e. e = [u, u]
Multi Graph
A graph, which contains multiple edges or Loops, is called as Multigraph M.
Directed Graphs
A directed graph G is the same as a Multigraph except that each edge e in G is assigned a
direction.
Out Degree
The number of edges beginning at a node u is the outdegree of that node and the number
of edges ending at the node e is the indegree of e. A node is called a Source if it has
positive outdegree and zero indegree. A node is called as a Sink if it has a positive
indegree and zero outdegree.
82. Memory Organization of a Graph
A graph is represented in memory with the help of a linear list of all the nodes in the
graph called as the node list. The adjacent nodes for every node are again maintained by
means of a list, 1which is called as the adjacency list. Consider the following graph:
214
This watermark does not appear in the registered version - http://www.clicktoconvert.com
First prepare an adjacency list for every node which is as shown in the table:
We can insert either a node or an edge in a graph. Inserting a node involves inserting an
element in the node list and the adjacent part has to be set NULL as this will be an
215
This watermark does not appear in the registered version - http://www.clicktoconvert.com
isolated node. Inserting an edge involves inserting an element in to the adjacency list of
all the nodes, which are adjacent to that node.
Deleting an element from a graph again involves deleting an edge in which case the
adjacency list of all the nodes adjacent to this node will have to be deleted and the node
as such will have to be deleted from the node list. Deleting an edge involves deleting an
element from the adjacency list of the node that is getting deleted.
Check the starting node A. The check all the neighbors of A. Then examine the neighbors
of neighbors of A and so on.
Check the starting node A. Then search each node N along the path P, which begins at
node A. i.e., search neighbor of A, then neighbor of neighbor of A and so on. Once we
reach the dead end then we backtrack on P until we can continue along another path P’
and so on.
Graphs are used in a wide variety of applications. A graph can be used by an airlines for
maintaining the flight information such as the various flights, their routes and the distance
between the places, etc. With the help of such a graph one will be easily able to find out
whether there is any flight for a particular destination and if there are several routes to
reach that destination which one is having the optimum distance or cost, etc.
216
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Part – VI
‘C’ CODE
SNIPPETS
217
This watermark does not appear in the registered version - http://www.clicktoconvert.com
Topics Covered:-
218
This watermark does not appear in the registered version - http://www.clicktoconvert.com
1. Counts the number of bits set. Is twice as fast as obvious shift and test method.
int bit_count(long x)
{
int n = 0;
if (x)
do {
n++;
} while ((x &= x-1));
return(n);
}
3. Reverses the bits in a 32-bit integer. Uses a few lines with logical and bit
operations but NO loops.
{
unsigned {32-bit-type} x;
219
This watermark does not appear in the registered version - http://www.clicktoconvert.com
return r;
}
while(count--)
{
/* AND the high order bit (the
* left one) If the bit is set,
* print a ONE. */
printf("%d", ( byte & MASK ) ? 1 : 0 );
printf("\n");
}
while(b){r = a % b; a = b; b = r;}
return(a);
}
if (a < 0) a = -a;
if (!b) return a;
if (b < 0) b = -b;
if (!a) return b;
t = 0;
220
This watermark does not appear in the registered version - http://www.clicktoconvert.com
int another_function(int x) {
return! ((~(~0U>>1)|x)&x -1) ;
#define swap( a, b, t ) ( g ## t = ( a ), ( a ) = ( b ), ( b ) = g ## t )
int gint;
char gchar;
float gfloat ;
main( )
{
int a = 10, b = 20 ;
char ch1 = 'a' , ch2 = 'b' ;
float f1 = 1.12, f2 = 3.14 ;
swap ( a, b, int ) ;
printf ( "\na = %d b = %d", a, b ) ;
221
This watermark does not appear in the registered version - http://www.clicktoconvert.com
( gint = ( a ), ( a ) = ( b ), ( b ) = gint )
extern "C"
{
void f( ) ;
void f1( ) ;
}
// In cfunc.c
#include <stdio.h>
void f( )
{
printf ( "in f( )" ) ;
}
#include <iostream.h>
extern "C" void f( ) ;
void main( )
{
f( ) ;
}
The # symbol can be used in front of a normal macro argument to convert the actual
argument to string.
222
This watermark does not appear in the registered version - http://www.clicktoconvert.com
int factorial(int n)
{
if(n<1)
return(1);
return(n * factorial(n-1));
head = reverseList(head,NULL)
223
This watermark does not appear in the registered version - http://www.clicktoconvert.com
return pr;
}
int a =0x1020;
char *p=(char *) a;
if(*p==20)
printf("\nLittle Endian");
else
printf("\nBig Endian");
ex. 8 1000
i) if( n & (n - 1) == 0)
printf("It is a exact power of 2");
int exact2(int n)
{
if(n==2)
return(1);
if(n%2==0)
exact2(n/2);
else
return(0);
}
224
This watermark does not appear in the registered version - http://www.clicktoconvert.com
decimal=decimal/base;
}
return str;
}
main()
{
unsigned int x=~0;
int count;
for (count=1; (x<<=1)>0 ; count++)
;
printf("%d", count);
getchar();
}
main()
{
unsigned int x=10;
int ones;
for(ones=0;x!=0;x>>=1)
if (x&01)
ones++;
printf("Number of ones :: %d\n", ones);
}
20. No. of ways are to find the size of an integer without using sizeof operator.
main()
{
int *p=0;
p++;
printf("Word Size is %d bytes\n",p);
getchar();
}
225
This watermark does not appear in the registered version - http://www.clicktoconvert.com
21. In the following for statement, you are allowed to either add or change only one
character. The objective is to print the * character 5 times.
for(i=0;i<n;i--)
printf("*");
void main()
{
int i,n=5;
clrscr();
22. How will you find if your system follows big endian or little endian order?
#include<stdio.h>
main()
{
union {
short c;
char a[sizeof(short)];
} check;
check.c=0x0102;
if ( check.a[0]==1 && check.a[1]==2 )
printf ("Big endian\n");
else if ( check.a[0]==2 && check.a[1]==1 )
printf ("little endian\n");
}
Other way…
main()
{
int x=10;
if (*((char *)x) == 0)
printf("Big Endian\n");
else
226
This watermark does not appear in the registered version - http://www.clicktoconvert.com
printf("Little Endian\n");
}
/* this is a solution as a recursive function. However it suffers with the fact that the
leading zeros are not printed */
main()
{
int num=10;
bit(num);
}
24. How many ways are available to find the complement of an integer (without
using the complement operator)?
main()
{
int a=10, b=10;
/* one way to do this. this method suffers from the fact that it assumes size of an
integer */
a=a^0xffff;
printf("Method 1::%x\n",a);
227
This watermark does not appear in the registered version - http://www.clicktoconvert.com
27. How many simple ways are there to swap two numbers?
main()
{
int a=10, b=20;
a^=b;
b^=a;
a^=b;
printf("%d..%d",a,b);
}
#include<stdio.h>
#include<math.h>
main()
{
float number;
printf("Enter a float::");
scanf("%f",&number);
printf("Actual Number::%f\n",number);
printf("Rounded Number::%f\n",(int)(number*100 +0.5)/100.0);
}
Other way…
#include <stdio.h>
#include <math.h>
void main()
{
float fvalue;
int iplace;
float fnCorrect2Decimal(float fvalue,int iplace);
printf("Correcting to Two Decimal Place\n");
printf("Enter the Number:");
scanf("%f",&fvalue);
228
This watermark does not appear in the registered version - http://www.clicktoconvert.com
30. To find the size of the integer without using sizeof opearator
int arr[5];
printf("%d", (char*)&arr[1] - (char*)&arr[0]);
Try out:-
1. Write a "Hello World" program in 'C' without using a semicolon.
2. Write a C++ program without using any loop (if, for, while etc) to print numbers from
1 to 100 and 100 to 1;
3. Exchange two numbers without using a temporary variable.
4. Find if the given number is a power of 2.
5. Multiply x by 7 without using multiplication (*) operator.
6. Write a function in different ways that will return f(7) = 4 and f(4) = 7
7. Remove duplicates in array
8. Finding if there is any loop inside linked list.
9. Remove duplicates in an no key access database without using an array
10. Convert (integer) number in binary without loops.
11. Write a program whose printed output is an exact copy of the source. Needless to say,
merely echoing the actual source file is not allowed.
229
This watermark does not appear in the registered version - http://www.clicktoconvert.com
12. From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number
and adds it to the total. Once a number is used, it must be removed from the pool. The
winner is the person whose number makes the total equal 31 exactly.
13. Swap two numbers without using a third variable.
14. Given an array (group) of numbers write all the possible sub groups of this group.
230