Latest Entries »

13-14

Instructor Inputs
Session 13 ¤NIIT  Instructor Inputs 13.3
This session covers Chapter 13.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Creating an application by using a class and its objects
„ Variable declaration and initialization in the class program
At times, a program needs to perform multiple tasks concurrently. For example, a Web
browser displaying a sports Web page runs a Java applet that spins a football in the
corner, but leaves the scrollbar active so that the Web page can be traversed at the same
time. The Web browser is multithreaded, which enables this flexibility. This session
describes how to set up multiple threads in a single program so that you can perform
multiple tasks simultaneously.
Every Java program contains at least one thread, which is the main thread. When a Java
program starts, the JVM creates the main thread and calls the main() method of the
program within that thread. More threads can be created by using the Thread constructor
or by instantiating classes that extend the Thread class.
While conducting the session, you need to explain the synchronization of threads.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 13.4 Instructor Inputs  ¤NIIT
Slide 1
Slide 1 of 24 Session 13 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Define a thread
Create separate threads in a Java technology program,
controlling the code and data that are used by that thread
Control the execution of a thread and write platform
independent code with threads
Describe the difficulties that might arise when multiple threads
share data
Use wait and notify to communicate between threads
Use synchronized to protect data from corruption
Objectives
Use Slide 1 to share the session objectives with the students.
Slide 2
Slide 2 of 24 Session 13 Ver.  1.0
Java Programming Language
Threads
Threads are a virtual CPU.
The three parts of at thread are:
CPU
Code
Data
A thread or
execution context
Use Slide 2 to introduce the concept of threads.
Threading enables multiple activities to coexist within a single process. Java is the first
mainstream programming language that explicitly includes threading within the language ¤NIIT  Instructor Inputs 13.5
itself, rather than treating threading as a feature of the underlying operating system.
Threads are sometimes referred to as lightweight processes. Like processes, threads are
independent, concurrent paths of execution that run through a program. Each thread has
its own stack, its own program counter, and its own local variables.
Slide 3
Slide 3 of 24 Session 13 Ver.  1.0
Java Programming Language
Creating the Thread
Extend the class from Thread Class. For example:
public class HelloRunner extends Thread
{
//code
}
Implement the Runnable interface. For example:
class HelloRunner implements Runnable
{
//code
}
Use Slide 3 to discuss ways to create a thread in a Java program. Every Java program
contains at least one thread, which is the main thread. Additional threads are created
through the Thread constructor or by instantiating classes that extend the Thread class.
Java threads can create other threads by instantiating a Thread object directly or an object
that extends Thread. 13.6 Instructor Inputs  ¤NIIT
Slide 4
Slide 4 of 24 Session 13 Ver.  1.0
Java Programming Language
Creating the Thread (Contd.)
Multithreaded programming has following characteristics:
Multiple threads are from one Runnable instance.
Threads share the same data and code. For example:
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
Use Slide 4 to explain that a Java program can have many threads.
Multithreading is useful even in programs running on a single-processor computer. In this
scenario, Thread 2 runs while Thread 1 is blocked, waiting for I/O. The I/O action can
take place in parallel with the CPU running the other thread. In a single-threaded case,
Thread 2 waits until Thread 1 has finished.
Slide 5
Slide 5 of 24 Session 13 Ver.  1.0
Java Programming Language
Starting the Thread
Use the start() method
Place the thread in a runnable state¤NIIT  Instructor Inputs 13.7
Use Slide 5 to explain how to start a thread.
A thread does not actually begin to execute until another thread calls the start() method on
the Thread object for the new thread. The Thread object exists before its thread actually
starts, and it continues to exist after its thread exits. This enables you to control or obtain
information about a thread you have created, even if the thread has not started yet or has
already completed. It is not advisable to start() threads from within a constructor. This
might expose partially constructed objects to the new thread. If an object owns a thread, it
should provide a start() method to start the thread instead of starting it from the
constructor.
Slide 6
Slide 6 of 24 Session 13 Ver.  1.0
Java Programming Language
Thread Scheduling
Runnable
New
Running
Blocked Dead
start() run() Completes
Scheduler
Event Blocked Unblocked
Fundamental Thread State Diagram:13.8 Instructor Inputs  ¤NIIT
Slide 7
Slide 7 of 24 Session 13 Ver.  1.0
Java Programming Language
Thread Scheduling Example:
public class Runner implements Runnable {
public void run() {
while (true) {
// do lots of interesting stuff
// Give other threads a chance
try {
Thread.sleep(10);
} catch (InterruptedException e)
{
// This thread’s sleep was interrupted by another thread
}
}
}
}
Thread Scheduling (Contd.)
One of Thread
Scheduling Method
Use Slides 6 and 7 to explain the fundamental thread state diagram and provide the
example of using sleep() method to perform scheduling.
Slide 8
Slide 8 of 24 Session 13 Ver.  1.0
Java Programming Language
Terminating a Thread
The thread comes to the end of its run() method.
The thread throws an Exception or Error that is not caught.
Another thread calls one of the deprecated stop()
methods.
Use Slide 8 to explain how to terminate a thread. ¤NIIT  Instructor Inputs 13.9
A thread can end in one of the following ways:
„ The thread comes to the end of its run() method.
„ The thread throws an exception or error that is not caught.
„ Another thread calls one of the deprecated stop() methods.
Deprecated means they still exist. You should not use them in a new code and should
strive to eliminate them in the existing code. When all the threads within a Java program
are completed, the program exits.
Slide 9
Slide 9 of 24 Session 13 Ver.  1.0
Java Programming Language
Basic Control of Threads
Test Threads:
isAlive()
Access Thread Priority:
getPriority()
setPriority()
Put Threads on Hold:
Thread.sleep() // static method
join()
Thread.yield() // static method
The Thread API includes a sleep() method, which causes the current thread to go into a
wait state until the specified amount of time has elapsed or until the thread is interrupted
by another thread by calling Thread.interrupt() on the current thread’s Thread object.
If a thread is interrupted by a call to Thread.interrupt(), the sleeping thread throws an
InterruptedException.
The Thread.yield() method is similar to Thread.sleep(), but instead of sleeping, it pauses
the current thread momentarily so that the other thread can run.
Use the code given on Slide 10 to explain the join() method. The Thread API contains a
method for waiting for another thread to complete the join() method. When you call
Thread.join(), the calling thread blocks until the target thread completes. Thread.join() is
generally used by programs that use threads to partition large problems into smaller ones,
giving each thread a piece of the problem.  13.10 Instructor Inputs  ¤NIIT
Slide 10
Slide 10 of 24 Session 13 Ver.  1.0
Java Programming Language
Use of join() method:
public static void main(String[] args) {
Thread t = new Thread(new Runner());
t.start();
// Do stuff in parallel with the other thread for a while
// Wait here for the other thread to finish
try {
t.join();
}
catch (InterruptedException e)
{
// the other thread came back early
}
// Now continue in this thread
}
Basic Control of Threads (Contd.)
Use Slides 9 and 10 to explain how to control threads.
Slide 11
Slide 11 of 24 Session 13 Ver.  1.0
Java Programming Language
The Object Lock Flag
Every object has a flag that is a type of lock flag.
The synchronized enables interaction with the lock flag.
Object this Thread before synchronized(this)
public void push (char c)
{
synchronized(this) {
data[idx] = c;
idx++;
}
}¤NIIT  Instructor Inputs 13.11
Slide 12
Slide 12 of 24 Session 13 Ver.  1.0
Java Programming Language
The Object Lock Flag (Contd.)
Object this Thread after synchronized(this)
public void push (char c)
{synchronized(this)
{
data[idx] = c;
idx++;
}
}
Slide 13
Slide 13 of 24 Session 13 Ver.  1.0
Java Programming Language
The Object Lock Flag (Contd.)
Another thread, trying to execute
synchronized(this)
public char pop(char c)
{
synchronized(this)
{
idx–;
return data[idx];
}
}
Object this
lock flag missing
Waiting for
object lock
Use Slides 11, 12, and 13 to explain the object lock flag. When multiple threads access
the same data item (such as a static field, an instance field of a globally accessible object,
or a shared collection), you need to ensure that they coordinate their access to the data so
that both see a consistent view of the data and neither steps on the other’s changes. The
Java language provides two keywords for this purpose, synchronized and volatile. When
accessing variables from more than one thread, access must be properly synchronized.  13.12 Instructor Inputs  ¤NIIT
The basic rule for synchronizing for visibility is that you must synchronize whenever you
are:
„ Reading a variable that may have been last written by another thread.
„ Writing a variable that may be read next by another thread.
Slide 14
Slide 14 of 24 Session 13 Ver.  1.0
Java Programming Language
Releasing the Lock Flag
The lock flag is released in the following events:
Released when the thread passes the end of the synchronized
code block
Released automatically when a break, return, or exception is
thrown by the synchronized code block
Use Slide 14 to explain how to release the lock that is placed by the synchronized
keyword.  ¤NIIT  Instructor Inputs 13.13
Slide 15
Slide 15 of 24 Session 13 Ver.  1.0
Java Programming Language
All access to delicate data should be synchronized.
Delicate data protected by synchronized should be private.
The following two code segments are equivalent:
public void push(char c)
{
synchronized(this) {
// The push method code
}
}
public synchronized void push(char c)
{
// The push method code
}
Using synchronized
Use Slide 15 to share information about the synchronized keyword.
Slide 16
Slide 16 of 24 Session 13 Ver.  1.0
Java Programming Language
Thread State Diagram with Synchronization:
Using synchronized (Contd.)
New
Running
Blocked Dead
start() run() Completes
Scheduler
Event Blocked
Runnable
Blocked in
Object’s Lock
Pool
Unblocked
Synchronized Lock Acquired
Use Slide 16 to explain the thread state diagram with synchronization. 13.14 Instructor Inputs  ¤NIIT
Slide 17
Slide 17 of 24 Session 13 Ver.  1.0
Java Programming Language
Deadlock
A deadlock has the following characteristics:
It is two threads, each waiting for a lock from the other.
It is not detected or avoided.
Deadlock can be avoided by:
Deciding on the order to obtain locks
Adhering to this order throughout
Releasing locks in reverse order
Use Slide 17 to explain the deadlock situation.
A deadlock usually occurs when there are multiple processes contending for exclusive
access to multiple locks. A set of processes or threads is said to be deadlocked when each
is waiting for an action that only one of the others can perform.
The most common form of deadlock is when Thread 1 holds a lock on Object A and is
waiting for the lock on Object B, and Thread 2 holds the lock on Object B and is waiting
for the lock on Object A. Neither thread will ever acquire the second lock or relinquish
the first lock. They will simply wait forever.
To avoid a deadlock, ensure that when acquiring multiple locks, you always acquire the
locks in the same order in all threads. ¤NIIT  Instructor Inputs 13.15
Slide 18
Slide 18 of 24 Session 13 Ver.  1.0
Java Programming Language
Thread Interaction
wait and notify Methods
Scenario:
Consider yourself and a cab driver as two threads.
Problem:
How do you determine when you are at your destination?
Solution:
You notify the cab driver of your destination and relax
The driver drives and notifies you upon arrival at your destination
Slide 19
Slide 19 of 24 Session 13 Ver.  1.0
Java Programming Language
Thread Interaction (Contd.)
Thread interactions include:
The wait() and notify() methods
The pools:
Wait pool
Lock pool
Use Slides 18 and 19 to explain about the wait() and notify() methods.
The Object class defines the wait(), notify(), and notifyAll() methods. To execute any of
these methods, you need to hold the lock for the associated object. Wait() causes the
calling thread to sleep until it is interrupted with Thread.interrupt(), the specified timeout
elapses, or another thread wakes it up with notify() or notifyAll(). 13.16 Instructor Inputs  ¤NIIT
When the notify() method is invoked on an object and if there are any threads waiting on
that object through wait(), one thread will be awakened. When the notifyAll() method is
invoked on an object, all threads waiting on that object are awakened.
These methods are the building blocks of more sophisticated locking, queuing, and
concurrency code. However, the use of notify() and notifyAll() is complicated. In
particular, using notify() instead of notifyAll() is risky. Use notifyAll() unless you really
know what you’re doing.
Slide 20
Slide 20 of 24 Session 13 Ver.  1.0
Java Programming Language
Thread Interaction (Contd.)
Thread State Diagram with wait() and notify() methods:
New
Running
Blocked
Dead
start() run() Completes
Scheduler
Event Blocked
Runnable
Blocked in
Object’s
Lock Pool
Blocked in
Object’s
Wait Pool
Synchronized
notify() or
interrupt()
wait()
Unblocked
Lock Acquired
Use Slide 20 to explain the thread state diagram with the wait() and notify() methods. ¤NIIT  Instructor Inputs 13.17
Slide 21
Slide 21 of 24 Session 13 Ver.  1.0
Java Programming Language
Monitor Model for Synchronization
Leave shared data in a consistent state
Ensure programs cannot deadlock
Do not put threads expecting different notifications in the
same wait pool.
Use Slide 21 to introduce the monitor model of synchronization.
Slide 22
Slide 22 of 24 Session 13 Ver.  1.0
Java Programming Language
Lets see  how to create a Java class that represents a
separate thread of control flow.
Demonstration
Give a demo to the students to show how to create a Java class that represents a separate
thread of control flow. 13.18 Instructor Inputs  ¤NIIT
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod13_threads\ DemoProject.
Slide 23
Slide 23 of 24 Session 13 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
Threads are a virtual CPU.
The three parts of at thread are CPU, Code, and Data.
Thread can be created by extend the class from Thread Class
or by implementing Runnable interface.
A Java program can have multiple threads.
Thread need to start by using start() method.
Various states of thread are runnable, running, and blocked.
sleep() method pauses the thread for given amount of time.
The thread dies when run() method completes.
sleep(), join(),and yield() methods put the thread on
hold.
Use getPriority() method to determine the current priority
of the thread.
Slide 24
Slide 24 of 24 Session 13 Ver.  1.0
Java Programming Language
Summary (Contd.)
When multiple threads are working on shared data,
synchronized keyword should be used to maintain the
consistency of the data.
Deadlock is the situation where two threads, each waiting for a
lock from the other.
wait() and notify() are methods for thread
communication.
Use Slides 23 and 24 to summarize the key points of this session. ¤NIIT  Instructor Inputs 13.19
The following section provides some extra inputs on the important topics covered in the
SG.
A few simple guidelines to be followed when writing synchronized blocks to avoid the
risks of deadlock and performance hazards are:
„ Keep blocks short. Synchronized blocks should be short, as short as possible while
still protecting the integrity of related data operations. In addition, move
thread-invariant preprocessing and postprocessing out of synchronized blocks.
„ Do not invoke methods on other objects while holding a lock. This may sound
extreme, but it eliminates the most common source of deadlock.
To maintain proper visibility across threads, use synchronized or volatile statements to
ensure that changes made by one thread are visible by another whenever a nonfinal
variable is shared among several threads.
You need to synchronize when:
„ Reading a variable that may have been last written by another thread.
„ Writing a variable that may be read next by another thread.
There are a few cases where you need not synchronize to propagate data from one thread
to another because JVM implicitly performs synchronization. These cases include:
„ When data is initialized by a static initializer, an initializer on a static field, or in a
static{} block
„ When accessing final fields
„ When an object is created before a thread is created
„ When an object is already visible to a thread that it is then joined with
Additional Inputs
Guidelines for Synchronization
Need for Synchronization 13.20 Instructor Inputs  ¤NIIT
„ How many threads can you create?
Ans: By default, on a Win32 machine, each native thread gets one MB or 1024*1024
bytes of stack space reserved for it. The memory is not actually allocated. If it were, you
would run out of memory with dozens of threads instead of hundreds. The space needs to
be reserved as a contiguous block of memory so that the stack can grow as needed. In
Win32, the maximum amount of memory is 2 GB, which corresponds to 2,000 threads,
each reserving 1MB of memory. This is the upper limit. In practice, you might run out of
other OS resources before running out of memory. Each thread has some system
resources that are used to manage the thread register storage area, thread-local storage,
state information, exception condition info, etc. You should design your programs so that
you use threads only where necessary. It is almost always a mistake to have one thread
per object. Successful programs are much more likely to have 5 threads or fewer than 500.
„ How can you create a thread and start it running?
Ans: You can create an instance of a thread or a thread subclass, and invoke start()
method on that instance.
„ How can you specify pause times in your program?
Ans: You can specify pause times by using the sleep method of the Thread class.
„ How can you stop a thread and start a new thread in its place?
Ans: To stop a thread and start a new thread in its place, use the cooperative approach
wherever possible. Set a flag to indicate that the thread should stop, but let the targeted
thread itself check for the flag and find a safe place to stop.
„ How does the stop method of a thread work? Can you restart a stopped thread?
Ans: The stop method stops a thread permanently. This thread cannot be run again.
FAQs

———————————————————————————————————————

Instructor Inputs
Session 14 ¤NIIT  Instructor Inputs 14.3
This session covers Chapters 14 and 15.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Writing programs by using exception handling
„ Implementing file I/O methods
This session covers the stream I/O mechanism. It discusses how data can be read and
written by using streams. In addition, it discusses network implementation in Java
programs.
You can start the session by explaining the I/O operations requirement. List the
differences between byte streams and character streams. Explain that networking is
required to provide services to any client through network servers. In this case, the
client/server communication needs to be established to access services provided by the
server to the client.
Slide 1
Slide 1 of 26 Session 14 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Describe Input/Output fundamentals
Construct node and processing streams, and use them
appropriately
Distinguish readers and writers from streams, and select
appropriately between them
Develop code to set up the network connection
Understand the TCP/IP Protocol
Use ServerSocket and Socket classes for implementation of
TCP/IP clients and servers
Objectives
Use Slide 1 to share the session objectives with the students.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 14.4 Instructor Inputs  ¤NIIT
Slide 2
Slide 2 of 26 Session 14 Ver.  1.0
Java Programming Language
I/O Fundamentals
A stream can be thought of as a flow of data from a source
or to a sink.
A source stream initiates the flow of data, also called an
input stream.
A sink stream terminates the flow of data, also called an
output stream.
Sources and sinks are both node streams.
Types of node streams are files, memory, and pipes
between threads or processes.
Use Slide 2 to explain I/O fundamentals.
An I/O stream represents an input source or an output destination. A stream can represent
various kinds of sources and destinations, including disk files, devices, other programs,
and memory arrays.
Streams support various kinds of data, including simple bytes, primitive data types,
localized characters, and objects. Some streams simply pass on data; others manipulate
and transform the data in useful ways. ¤NIIT  Instructor Inputs 14.5
Slide 3
Slide 3 of 26 Session 14 Ver.  1.0
Java Programming Language
I/O Fundamentals (Contd.)
Writer OutputStream Sink streams
Reader InputStream Source streams
Character Streams Byte Streams Stream
The fundamental stream classes are:
Slide 4
Slide 4 of 26 Session 14 Ver.  1.0
Java Programming Language
Data Within Streams
Java technology supports two types of streams:
character
byte
Input and output of character data is handled by readers
and writers.
Input and output of byte data is handled by input streams
and output streams.
Normally, the term stream refers to a byte stream.
The terms reader and writer refer to character streams.
Use Slides 3 and 4 to explain the fundamental stream class, byte streams, and character
streams.
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream
classes are descended from InputStream and OutputStream classes. 14.6 Instructor Inputs  ¤NIIT
All character stream classes are descended from Reader and Writer classes. As with byte
streams, there are character stream classes that specialize in file I/O. These are FileReader
and FileWriter.
Slide 5
Slide 5 of 26 Session 14 Ver.  1.0
Java Programming Language
The InputStream Methods
The three basic read methods are:
int read()
int read(byte[] buffer)
int read(byte[] buffer, int offset, int
length)
Other methods include:
void close()
int available()
long skip(long n)
boolean markSupported()
void mark(int readlimit)
void reset()
Slide 6
Slide 6 of 26 Session 14 Ver.  1.0
Java Programming Language
The OutputStream Methods
The three basic write methods are:
void write(int c)
void write(byte[] buffer)
void write(byte[] buffer, int offset, int
length)
Other methods include:
void close()
void flush()
Use Slides 5 and 6 to explain InputStream and OutputStream methods. ¤NIIT  Instructor Inputs 14.7
Slide 7
Slide 7 of 26 Session 14 Ver.  1.0
Java Programming Language
The three basic read methods are:
int read()
int read(char[] cbuf)
int read(char[] cbuf, int offset, int
length)
Other methods include:
void close()
boolean ready()
long skip(long n)
boolean markSupported()
void mark(int readAheadLimit)
void reset()
The Reader Methods
Slide 8
Slide 8 of 26 Session 14 Ver.  1.0
Java Programming Language
The basic write methods are:
void write(int c)
void write(char[] cbuf)
void write(char[] cbuf, int offset, int
length)
void write(String string)
void write(String string, int offset, int
length)
Other methods include:
void close()
void flush()
The Writer Methods
Use Slides 7 and 8 to explain Reader and Writer methods. 14.8 Instructor Inputs  ¤NIIT
Slide 9
Slide 9 of 26 Session 14 Ver.  1.0
Java Programming Language
Node Streams
PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
Pipe
N/A StringReader
StringWriter
Memory: string
ByteArrayInputStream
ByteArrayOutputStream
CharArrayReader
CharArrayWriter
Memory: array
FileInputStream
FileOutputStream
FileReader
FileWriter
File
Byte Streams Character Streams Type
Various types of Character and Byte Stream classes are:
Use Slide 9 to explain the concept of the node stream class. You can explain this concept
by giving a small example: when you need to read data from a text file and transfer this
data to another text file, you use node streams.
Node streams can be used to write to file systems or even across sockets. This means you
can easily transfer a flattened object across a network wire and have it rebuilt on the other
side. ¤NIIT  Instructor Inputs 14.9
Slide 10
Slide 10 of 26 Session 14 Ver.  1.0
Java Programming Language
I/O Stream Chaining
Input Stream Chain:
FileInputStream BufferedInputStream DataInputStream
Data Source
Program
Program Data Sink
FileOutputStream
BufferedOutputStream
DataOutputStream
Output Stream Chain:
Use Slide 10 to explain input stream chain and output stream chain.
Slide 11
Slide 11 of 26 Session 14 Ver.  1.0
Java Programming Language
Processing Streams
ObjectInputStream
ObjectOutputStream
Performing object
serialization
DataInputStream
DataOutputStream
Performing data
Conversion
LineNumberInputStream LineNumberReader Counting
InputStreamReader
OutputStreamWriter
Converting between
bytes and character
FilterInputStream
FilterOutputStream
FilterReader
FilterWriter
Filtering
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
Buffering
Byte Streams Character Streams Type
Processing Streams are Node Streams that use filters in
between while transferring the data.
Various types of Processing Streams are:
Use Slide 11 to explain the concept of processing streams. Processing streams are node
streams that use filters while transferring data. For example, when you read data from the
standard input and want to save the same data in the text file, you need to use filters,
called processing streams. 14.10 Instructor Inputs  ¤NIIT
Slide 12
Slide 12 of 26 Session 14 Ver.  1.0
Java Programming Language
InputStream
The InputStream Class Hierarchy:
Slide 13
Slide 13 of 26 Session 14 Ver.  1.0
Java Programming Language
OutputStream
The OutputStream Class Hierarchy:¤NIIT  Instructor Inputs 14.11
Slide 14
Slide 14 of 26 Session 14 Ver.  1.0
Java Programming Language
Reader Class
The Reader Class Hierarchy:
Slide 15
Slide 15 of 26 Session 14 Ver.  1.0
Java Programming Language
Writer Class
The Writer Class Hierarchy:
Slides 12, 13, 14, and 15 can be used to explain InputStream class hierarchy,
OutputStream class hierarchy, Reader class hierarchy, and Writer class hierarchy,
respectively. 14.12 Instructor Inputs  ¤NIIT
Slide 16
Slide 16 of 26 Session 14 Ver.  1.0
Java Programming Language
Networking
Basics of Networking:
Computers running on the Internet communicating to each
other using the Transmission Control Protocol (TCP) / Internet
Protocol (IP).
Server. foo.com
3000
Client.bar.com
18000
Client.baz.com
18002
Port no.
Slide 17
Slide 17 of 26 Session 14 Ver.  1.0
Java Programming Language
Networking (Contd.)
Networking with Java Technology:
Sockets:
Sockets hold two streams, an input stream and an output stream.
Each end of the socket has a pair of streams.
Setting Up the Connection:
Setup of a network connection is similar to a telephone.
One end must dial the other end, which must be listening.¤NIIT  Instructor Inputs 14.13
Slide 18
Slide 18 of 26 Session 14 Ver.  1.0
Java Programming Language
Networking (Contd.)
To address the connection, include the following:
The address or name of remote machine.
A port number to identify the purpose at the server.
Port numbers range from 0–65535
Use Slides 16, 17, and 18 to explain the basic concept of networking.
Slide 19
Slide 19 of 26 Session 14 Ver.  1.0
Java Programming Language
Networking (Contd.)
Java Networking Model:
Server
Client
Socket(host, port#)
(Attempt to connect)
SeverSocket(port#)
ServerSocket.accept()
Socket()
OutputStream
InputStream
Socket.close()
OutputStream
InputStream
Socket.close()
Register with
this service
Wait for a
connection
Use Slide 19 to explain the Java networking model. 14.14 Instructor Inputs  ¤NIIT
Slide 20
Slide 20 of 26 Session 14 Ver.  1.0
Java Programming Language
ServerSocket and Socket Classes
Code Snippet for Creating Minimal TCP/IP Server:
ServerSocket s = null;
s = new ServerSocket(5432); //Register your
service on port 5432
while (true) // Run the listen/accept loop forever
{
Socket s1 = s.accept(); // Wait here and listen
for a connection
OutputStream s1out = s1.getOutputStream();
// Get output stream associated with the socket
BufferedWriter bw = new BufferedWriter(new
OutputStreamWriter(s1out));
bw.write(“Hello Net World!\n”); // Send your
string!
Use Slide 20 to explain the code required to create a simple server program.
Slides 21
Slide 21 of 26 Session 14 Ver.  1.0
Java Programming Language
ServerSocket and Socket Classes (Contd.)
bw.close(); // Close the connection, but not the
server socket
s1.close();
}
Code Snippet for Creating Minimal TCP/IP Client:
// Open your connection to a server, at port 5432
// localhost used here
Socket s1 = new Socket(“127.0.0.1”, 5432);
// Get an input stream from the socket
InputStream is = s1.getInputStream();
// Decorate it with a “data” input stream
DataInputStream dis = new
DataInputStream(is);¤NIIT  Instructor Inputs 14.15
Slides 22
Slide 22 of 26 Session 14 Ver.  1.0
Java Programming Language
ServerSocket and Socket Classes (Contd.)
// Read the input and print it to the screen
System.out.println(dis.readUTF());
// When done, just close the steam and connection
dis.close();
s1.close();
Use Slides 21 and 22 to explain the code required to create a simple client program.
Slide 23
Slide 23 of 26 Session 14 Ver.  1.0
Java Programming Language
Lets see how to create a TCP based Java client, and use
user-provided system properties to drive a Java program.
Demonstration
Give a demo to show how to create a TCP based Java client, and use user-provided
system properties to drive a Java program. 14.16 Instructor Inputs  ¤NIIT
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod15_network\DemoProject.
Slide 24
Slide 24 of 26 Session 14 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
A stream is a flow of data from a source or to a sink.
A source stream are also called an input stream.
A sink stream terminates the flow of data, also called an output
stream.
InputStream, OutputStream, Reader, and Writer are
fundamental stream classes.
Three basic read methods of InputStream class are:
int read()
int read(byte[] buffer)
int read(byte[] buffer, int offset, int length)
Three basic write methods of OutputStream class are:
void write(int c)
void write(byte[] buffer)
void write(byte[] buffer, int offset, int length)
Slide 25
Slide 25 of 26 Session 14 Ver.  1.0
Java Programming Language
Summary (Contd.)
Three basic read methods of Reader class are:
int read()
int read(char[] cbuf)
int read(char[] cbuf, int offset, int length)
The basic write methods of Writer class are:
void write(int c)
void write(char[] cbuf)
void write(char[] cbuf, int offset, int length)
void write(String string)
void write(String string, int offset, int length)
FileReader and FileWriter are file type character
streams.
FileInputStreaam and FileOutputStream are byte
streams classes.
ServerSocket and Socket are main classes to establish the
networking in Java Programs.¤NIIT  Instructor Inputs 14.17
Slide 26
Slide 26 of 26 Session 14 Ver.  1.0
Java Programming Language
Summary (Contd.)
To setup a network connection the address or name of remote
machine and a port number is required.
accept() method of ServerSocket class is used in server
program to receive client sockets to establish connection with
the server.
close() method of Socket class is required to close the
connection.
Use Slides 24, 25, and 26 to summarize the session. 14.18 Instructor Inputs  ¤NIIT
The following section provides some extra inputs on the important topics covered in the
SG.
Computers running on the Internet communicate with each other by using either the
Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP), as shown in
the following diagram.
When you write Java programs that can communicate over the network, you are
programming at the application layer. In this case, you need not consider the TCP and
UDP layers. Instead, you can use classes in the java.net package. These classes provide
system-independent network communication. However, to decide which Java classes your
programs should use, you need to understand the difference between TCP and UDP.
TCP
TCP is a connection-based protocol that provides a reliable flow of data between two
computers.
When two applications need to communicate with each other, a connection is established
to send data back and forth over that connection. TCP guarantees that data sent from one
end of the connection actually reaches the other end in the same order it was sent.
Otherwise, an error is reported.
Additional Inputs
Basics of Networking ¤NIIT  Instructor Inputs 14.19
UDP
UDP is a protocol that sends independent packets of data, called datagrams, from one
computer to another with no guarantee of arrival.
The UDP protocol provides for communication that is not guaranteed between two
applications on the network. UDP is not a connection-based protocol. It sends
independent packets of data, called datagrams, from one application to another. Sending
datagrams is very similar to sending a letter through the postal service: The order of
delivery is not important but not guaranteed. Each message is independent of any other
message.
Ports
The TCP and UDP protocols use ports to map incoming data to a particular process
running on a computer. In general, a computer has a single physical connection to the
network. All data destined for a particular computer arrives through that connection.
However, the data may be intended for different applications running on the computer.
So, how does the computer identify the application to forward the data? The answer is by
using ports.
Data transmitted over the Internet is accompanied by addressing information that
identifies the computer and the port for which it is destined. The computer is identified by
its 32-bit IP address, which the IP uses to deliver data to the right computer on the
network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the
data to the right application.
In a connection-based communication such as TCP, a server application binds a socket to
a specific port number. This registers the server with the system to receive all data
destined for that port. A client can then rendezvous with the server at the server’s port, as
shown in the following diagram.
Socket
A socket is one endpoint of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer can
identify the destination application of the data.  14.20 Instructor Inputs  ¤NIIT
Normally, a server runs on a specific computer and has a socket that is bound to a specific
port number. The server just waits, listening to the socket for a client to make a
connection request.
The client knows the hostname of the machine on which the server is running and the port
number on which the server is listening. To request for a connection request, the client
tries to rendezvous with the server on the machine and port of the server. The client also
needs to identify itself to the server, so it binds to a local port number that it will use
during this connection. This is usually assigned by the system.
„ How can you read a line of input at a time?
Ans: To read a line of input at a time, use the readLine method of the BufferedReader
class.
„ How do you get the IP address of a machine from its hostname?
Ans: The InetAddress class can resolve IP addresses for you. You can obtain an instance
of InetAddress for the machine and call the getHostAddress() method. This returns a
string in the xxx.xxx.xxx.xxx address form.
InetAddress inet = InetAddress.getByName(“www.davidreilly.com”);
System.out.println (“IP : ” + inet.getHostAddress());
FAQs

————————————————————————————————-

8-10-11

Instructor Inputs
Session 8 [¤NIIT  Instructor Inputs 8.3
This session covers Chapter 9.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Creation of a class
„ Use of looping constructs
„ Exception handling
Consider a situation where it is not desirable to hard-code certain elements of a program
in Java, such as file names or database names. Ask the students how the program should
be coded to supply these elements at run time. Then, using the code given in the book,
demonstrate how to specify the parameters of a program by using command-line
arguments.
In this session, the students will learn to write a Java program that can be read from the
standard input. They will learn to write programs to create, read, and write files. They will
also understand the basic hierarchy of collections in Java 2 SDK. In addition, they will
learn to write a program that uses sets and lists, and to iterate over a collection.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 8.4 Instructor Inputs  ¤NIIT
Slide 1
Slide 1 of 19 Session 8 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Write a program that uses command-line arguments and
system properties
Write a program that reads from standard input
Describe the C-type formatted input and output
Write a program that can create, read, and write files
Describe the basic hierarchy of collections
Write a program that uses sets and lists
Write a program to iterate over a collection
Write a program that uses generic collections
Objectives
Use Slide 1 to introduce the objectives of the session.
Slide 2
Slide 2 of 19 Session 8 Ver.  1.0
Java Programming Language
Command-Line Arguments
Command-line arguments are the parameters passed to a
Java application at run time.
Each command-line argument is placed in the args array
that is passed to the static main method. For example:
public static void main(String[] args)
Use Slide 2 to explain the command-line arguments.
The session 1 of CG explains how command-line arguments are passed to a Java
application program by using NetBeans IDE. ¤NIIT  Instructor Inputs 8.5
The command-line arguments are stored in an array of string objects. If an application
needs to support a numeric command-line argument, it must convert a string argument,
which represents a number such as “23”, to a numeric value. For this, you need to parse
numeric command-line arguments. For more information on this, refer to the Additional
Inputs section.
Slide 3
Slide 3 of 19 Session 8 Ver.  1.0
Java Programming Language
System Properties
System properties are a feature that replaces the concept of
environment variables (which are platform-specific).
System properties include information about the current
user, the current version of the Java runtime, and the
character used to separate components of a file path name.
The System.getProperties() method returns a
Properties object.
The System.getProperty(String) method returns a
String representing the value of the named property.
The System.getProperty(String, String) method
enables you to supply a default string value (second
parameter), which is returned if the named property does not
exist.
Use Slide 3 to explain system properties.
The System class maintains a Properties object that describes the configuration of the
current working environment. System properties include information about the current
user, the current version of the Java runtime, and the character used to separate the
components of a file path name. 8.6 Instructor Inputs  ¤NIIT
Slide 4
Slide 4 of 19 Session 8 Ver.  1.0
Java Programming Language
Console I/O
Applications interact with the user using console I/O.
Java 2 SDK supports console I/O with three public
variables in the java.lang.System class:
The variable System.out enables you to write to standard
output. It is an object of type PrintStream.
The variable System.in enables you to read from standard
input. It is an object of type InputStream.
The variable System.err enables you to write to standard
error. It is an object of type PrintStream.
Use Slide 4 to explain console I/O.
Slide 5
Slide 5 of 19 Session 8 Ver.  1.0
Java Programming Language
Writing to Standard Output
The println() method print the argument and a newline
character (\n).
The print() method print the argument without a newline
character.
The print() and println() methods are overloaded for
most primitive types (boolean, char, int, long,
float, and double) and for char[], Object, and
String.
The print(Object) and println(Object) methods
call the toString() method on the argument.¤NIIT  Instructor Inputs 8.7
Slide 6
Slide 6 of 20 Session 8 Ver.  1.0
Java Programming Language
The application program can use the following methods of
the java.io package to read from the standard input:
Read characters from the keyboard and convert the raw bytes
into Unicode characters:
InputStreamReader ir=new
InputStreamReader(system.in);
Create a buffered reader to read each line from the keyboard:
BufferedReader in = new BufferedReader(ir);
The BufferedReader(in) provides a readLine() method
to read from standard input one line at a time:
s=in.readLine();
The Scanner class of java.util package provides
formatted input functionality.
Reading from Standard Input
Use Slides 5 and 6 to read from the standard input and write on to standard output.
Explain the need for buffered streams. If you use unbuffered streams, each read or write
request is handled directly by the underlying operating system. This might decrease the
efficiency of the program because each such request often triggers operations such as disk
access or network activity.
To reduce this kind of overhead, the Java platform implements buffered input/output
streams. Buffered input streams read data from a memory area known as a buffer; the
native input API is called only when the buffer is empty. Similarly, buffered output
streams write data to a buffer, and the native output API is called only when the buffer is
full.  8.8 Instructor Inputs  ¤NIIT
Slide 7
Slide 7 of 19 Session 8 Ver.  1.0
Java Programming Language
Files and File I/O
The java.io package enables you to do the following:
Create File objects
Manipulate File objects
Read and write to file streams
Slide 8
Slide 8 of 19 Session 8 Ver.  1.0
Java Programming Language
Files and File I/O (Contd.)
Creating a new File Object:
File myFile;
The File class provides several utilities:
myFile = new File(“myfile.txt”);
myFile = new File(“MyDocs”, “myfile.txt”);
Directories are treated just like files in Java; the File class
supports methods for retrieving an array of files in the
directory, as follows:
File myDir = new File(“MyDocs”);
myFile = new File(myDir, “myfile.txt”);¤NIIT  Instructor Inputs 8.9
Slide 9
Slide 9 of 19 Session 8 Ver.  1.0
Java Programming Language
Files and File I/O (Contd.)
For file input:
Use the FileReader class to read characters.
Use the BufferedReader class to use the readLine()
method.
For file output:
Use the FileWriter class to write characters.
Use the PrintWriter class to use the print() and
println() methods.
Use Slides 7, 8, and 9 to explain file I/O.
The File class helps write platform-independent code that examines and manipulates files.
If a File object names an actual file, a program can use it to perform a number of useful
operations on the file. These operations include passing the object to the constructor for a
stream to open the file for reading or writing.
The delete method deletes the file immediately, while the deleteOnExit method deletes
the file when the virtual machine terminates. The setLastModified sets the modification
date/time for the file. The renameTo() method renames the file. Note that the file name
string behind the File object remains unchanged. Therefore, the File object will not refer
to the renamed file.  8.10 Instructor Inputs  ¤NIIT
Slide 10
Slide 10 of 19 Session 8 Ver.  1.0
Java Programming Language
Files and File I/O (Contd.)
The application program can use the following methods of
the java.io package to read input lines from the keyboard
and write each line to a file:
Create file
File file = new File(args[0]);
Create a buffered reader to read each line from the keyboard
InputStreamReader isr=new
InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
Create a print writer on this file
PrintWriter out = new PrintWriter(new
FileWriter(file));
Slide 11
Slide 11 of 19 Session 8 Ver.  1.0
Java Programming Language
Files and File I/O (Contd.)
Read each line from the input stream and print to a file one line
at a time
s = in.readLine();
out.println(s);
The application program can use the following methods of
the java.io package to read from a text file and display
each line on the standard output
Create file
File file = new File(args[0]);
Create a buffered reader to read each line from the keyboard
BufferedReader in = new BufferedReader(new
FileReader(file));
Read each line from the file and displays it on the standard
output
s = in.readLine();
System.out.println(s);¤NIIT  Instructor Inputs 8.11
Slide 12
Slide 12 of 20 Session 8 Ver.  1.0
Java Programming Language
Files and File I/O (Contd.)
Read each line from the file and displays it on the standard
output:
s = in.readLine();
System.out.println(s);
Use Slides 10, 11, and 12 to explain the methods that are used to read from a text file and
display the output on the standard output. In addition, you can discuss the methods used to
read input lines from the keyboard and write onto a file.
Although random access files have not been covered in the course, you can refer to the
Additional Inputs section if the student has a query.
Slide 13
Slide 13 of 20 Session 8 Ver.  1.0
Java Programming Language
Demonstration
Lets see how to read data from a file and display the output on
the standard output device. This demo also shows how to run a
program with user provided command line arguments.8.12 Instructor Inputs  ¤NIIT
Give a demo of reading data from a file and displaying the output on the standard output
device. This demo also shows how to run a program with user provided command line
arguments.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod09_textapps\exercise1\DemoProject.
Slide 14
Slide 14 of 20 Session 8 Ver.  1.0
Java Programming Language
The Collections API
A collection is a single object representing a group of
objects known as its elements.
The Collections API contains interfaces that group objects
as one of the following:
Collection: A group of objects called elements; any specific
ordering (or lack of) and allowance of duplicates is specified by
each implementation.
Set: An unordered collection; no duplicates are permitted.
List:  An ordered collection; duplicates are permitted.
Use Slide 14 to explain Collections API. ¤NIIT  Instructor Inputs 8.13
Slide 15
Slide 15 of 20 Session 8 Ver.  1.0
Java Programming Language
Generics
Generics are described as follows:
Provides compile-time type safety
Eliminates the need for casts
Example of before Generics code:
ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total =
((Integer)list.get(0)).intValue();
Example of after Generics code:
ArrayList<Integer> list = new
ArrayList<Integer>();
list.add(0, new Integer(42));
int total = list.get(0).intValue();
Use Slide 15 to explain the generics.
For more inputs on the set and list collection, you can refer to the Additional Inputs
section.
Slide 16
Slide 16 of 20 Session 8 Ver.  1.0
Java Programming Language
Lets see how to use the Collection API and generics in a Java
program.
Demonstration
Give a demo to the students how to use the Collection API and generics in a Java
program. 8.14 Instructor Inputs  ¤NIIT
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod09_textapps\exercise2\DemoProject.
Slide 17
Slide 17 of 20 Session 8 Ver.  1.0
Java Programming Language
Iterators
Iteration is the process of retrieving every element in a
collection.
An iterator of a set is unordered.
A ListIterator of a List can be scanned forwards
(using the next method) or backwards (using the previous
method).
List list = new ArrayList();
// add some elements
Iterator elements = list.iterator();
while ( elements.hasNext() ) {
System.out.println(elements.next());
}
Slide 18
Slide 18 of 20 Session 8 Ver.  1.0
Java Programming Language
Enhanced for Loop
The enhanced for loop has the following characteristics:
Simplified iteration over collections
Much shorter, clearer, and safer
Effective for arrays
Simpler when using nested loops
Iterator disadvantages removed
Iterators are error prone:
Iterator variables occur three times per loop.
This provides the opportunity for code to go wrong.
Use Slides 17 and 18 to explain iterators and enhanced for loop. ¤NIIT  Instructor Inputs 8.15
Slide 19
Slide 19 of 20 Session 8 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
A program can be parameterized by command-line arguments
and system properties.
Applications interaction with the user is accomplished using
text input and output to the console.
The Scanner class provides formatted input functionality. It is
a part of the java.util package.
Java.io package enables you to create file objects, manipulate
them, and read and write to the file streams.
The J2SE platform supports file input in two forms:
The FileReader class to read characters.
The BufferedReader class to use the readLine method.
The J2SE platform supports file output in two forms:
The FileWriter class to write characters.
The PrintWriter class to use the print and println methods.
Slide 20
Slide 20 of 20 Session 8 Ver.  1.0
Java Programming Language
Summary (Contd.)
A collection is a single object representing a group of objects.
These objects are known as elements. There are two types of
collections:
Set: It is an unordered collection, where no duplicates are
permitted.
List: It is an ordered collection, where duplicates are permitted.
The Iterator interface enables you to scan forward through
any collection. The enhanced for loop can be used to iterate
through a collection.
Generics provide compile-time type safety and eliminate the
need for casts.
Use Slides 19 and 20 to summarize the session. 8.16 Instructor Inputs  ¤NIIT
The following code snippet converts a command-line argument to an int:
int int1;
if (args.length > 0) {
try {
int1 = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println(“Argument must be an integer”);
System.exit(1);
}
}
parseInt throws a NumberFormatException if the format of args[0] is not valid. All the
number classes, such as Integer, Float, and Double use parseXXX methods that convert a
string representing a number to an object of their type.
A set is a collection that cannot contain duplicate elements. It models the mathematical set
abstraction. The set interface contains only methods inherited from the collection and
adds the restriction that duplicate elements are prohibited. Set also adds a stronger
contract on the behavior of the equals and hashCode operations, allowing Set instances to
be compared meaningfully even if their implementation types differ. Two set instances
are equal if they contain the same elements.
A list is an ordered c, sometimes called a sequence. Lists may contain duplicate elements.
In addition to the operations inherited from a collection, the list interface includes
operations for the following:
„ Positional access: Manipulates elements based on their numerical position in the list
„ Search: Searches for a specified object in the list and returns its numerical position
„ Iteration: Extends iterator semantics to take advantage of the list’s sequential nature
„ Range-view: Performs arbitrary range operations on the list
Additional Inputs
Parsing Numeric Command-Line Arguments
Collection API ¤NIIT  Instructor Inputs 8.17
A random access file behaves like a large array of bytes stored in the file system. There is
a kind of cursor, or index into the implied array, called the file pointer. Input operations
read bytes starting at the file pointer and advance the file pointer past the bytes read. If the
random access file is created in read/write mode, output operations are also available.
Output operations write bytes starting at the file pointer and advance the file pointer past
the bytes written.
Output operations that write past the current end of the implied array cause the array to be
extended. The file pointer can be read by the getFilePointer method and set by the seek
method. If end-of-file is reached before the desired number of bytes has been read, an
EOFException, which is a kind of IOException, is thrown. If any byte cannot be read for
any reason other than end-of-file, an IOException other than EOFException is thrown. In
particular, an IOException may be thrown if the stream has been closed.
„ Can a scanner use delimiters other than white space?
Ans: The scanner can also use delimiters other than white space. This example reads
several items from a string, as shown:
String input = “1 ha 2 ha red ha blue ha”;
Scanner s = new Scanner(input).useDelimiter(“\\s*ha\\s*”);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
It prints the following output:
1
2
red
blue
„ How can you append an existing file in Java?
Ans: You can use the following FileOutputStream constructor to append data:
public FileOutputStream(String name, boolean append)
throws FileNotFoundException
Random Access File
FAQs 8.18 Instructor Inputs  ¤NIIT
Parameters:
„ name: This is the system-dependent file name.
„ append: If true, bytes will be written at the end of the file rather than in the
beginning.
For example, to append the file autoexec.bat for adding a new path statement on a Wintel
machine, you can use the following statement:
FileOutputStream appendedFile = new FileOutputStream
(“c:\\autoexec.bat”, true);
„ How can you write primitive data types to the disk? In C/C++, the printf statement
can write integers, floats, as well as other types.
Ans: You can write primitive data types by using the DataOutputStream class.
DataOutputStream provides simple methods to write primitive data types on any output
stream, such as a user console, a network connection, or a file.
Data Type Method
Boolean writeBoolean(boolean v);
Byte writeByte(int v);
writeBytes(String s);

Char, String writeChar(int v);
writeChars(String s);

Double writeDouble(double v);
Float writeFloat(float v);
Int writeInt(int v);
Long writeLong(long v);
Short writeShort(int v);
String writeUTF(String str);¤NIIT  Instructor Inputs 8.19
„ How do you detect empty command-line arguments?
Ans: When you write Java applications, you need to check the command-line arguments
before using them. Not all users remember to put in the correct number of parameters. An
application might terminate with an ArrayIndexOutOfBoundsException.
For example, the following program checks that at least one parameter exists:
public class argsdemo
{
public static void main(String args[])
{
if (args.length == 0)
{
System.err.println (“No arguments!”);
System.exit(0);
}
}
}8.20 Instructor Inputs  ¤NIIT

—————————————————————————————————-

Instructor Inputs
Session 10 ¤NIIT  Instructor Inputs 10.3
This session covers Chapter 10.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Create an application by using a class and its objects.
„ Variable declaration and initialization in class programs.
This session introduces containers like windows, frames, and panels. It explains how
GUIs are put together and formatted, and describes some of the components from which
GUIs are built. You need to relate these concepts to real-life examples. Encourage the
students to come up with examples of things around them.
Slide 1
Slide 1 of 25 Session 10 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Describe the Abstract Window Toolkit (AWT) package and  its
components
Define the terms containers, components, and layout
managers, and describe how they work together to build a GUI
Use the Frame and Panel containers appropriately
Add components to a container
Use various layout managers to achieve a desired dynamic
layout
Objectives
Use Slide 1 to share the session objectives with the students.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 10.4 Instructor Inputs  ¤NIIT
Slide 2
Slide 2 of 25 Session 10 Ver.  1.0
Java Programming Language
Provides GUI components that are used in all Java applets
and applications.
Contains classes that can be composed or extended.
Ensures that every GUI component that is displayed on the
screen is a subclass of  class Component or
MenuComponent.
Has Container, which is an abstract subclass of
Component and includes two subclasses:
Panel
Window
Abstract Window Toolkit
Use Slide 2 to explain the characteristics of abstract window toolkit.
Introduce the Abstract Window Toolkit (AWT) package to the students and discuss its
importance in the Java programming language. Most of the interactive user input and
output is done through GUIs. The Java platform provides a number of classes in the AWT
package to make programming and setup of GUIs easy. The AWT package contains
classes of components from which GUIs are pieced together. In addition, it also contains
classes that handle other aspects, such as color, font, and layout of components.   ¤NIIT  Instructor Inputs 10.5
Slide 3
Slide 3 of 25 Session 10 Ver.  1.0
Java Programming Language
The java.awt Package
Basic overview of AWT package:
Java.lang.object
Applet
Button
Canvas
Container
Label
List
TextComponent
MenuBar
MenuItem
Menu
CheckboxMenuItem
Panel
Window
ScrollPane
Dialog
Frame
TextArea
TextField
BorderLayout
FlowLayout
CardLayout
CheckboxGroup
Event
Color
Font
Graphics
MenuComponent
GridLayout
GridBagLayout
Image
Rectangle
Component
Use slide 3 to explain the hierarchy of the AWT package. Explain that buttons, labels, and
lists are subclasses of the Component class. The Dialog and Frame classes belong to the
Window class.
Slide 4
Slide 4 of 25 Session 10 Ver.  1.0
Java Programming Language
Containers
The two main types of containers are:
Window
Panel
A Window is a free floating window on the display.
A Panel is a container of GUI components that must exist
in the context of some other container, such as a Window or
Applet.
Add components with the add() method.10.6 Instructor Inputs  ¤NIIT
Slide 5
Slide 5 of 25 Session 10 Ver.  1.0
Java Programming Language
Components
Java programming language supports various components:
Button
Choice
Label
List
Scrollbar
TextComponent, etc.
The position and size of a component in a container is
determined by a layout manager.
You must use setLocation(), setSize(), or
setBounds() on components to locate them in the
container.
Use Slides 4 and 5 to explain components and containers.
In addition to static components like the label, Java AWT provides dynamic components
that allow user interaction/input, such as the Choice component. Choices are components
that allow the user to select from a drop-down menu of items. A good example of this is
the Location box, which is located at the top of the browser window. It probably has a
history attached to it, and gives you the option of selecting the previously entered
locations.
Choices are always created with the zero-argument constructor because they do not
include any other constructor. The menu of items is then populated by calling the Choice’s
add() method. Then, the Choice component can be added to a container by using the
Container’s add() method, as done in the Label component.  ¤NIIT  Instructor Inputs 10.7
Slide 6
Slide 6 of 25 Session 10 Ver.  1.0
Java Programming Language
Frames have the following characteristics:
Are a subclass of Window
Have title and resizing corners
Are invisible initially; use setVisible(true) to expose the
frame
Have BorderLayout as the default layout manager
Use the setLayout() method to change the default layout
manager
Frames
Slide 7
Slide 7 of 25 Session 10 Ver.  1.0
Java Programming Language
Frames (Contd.)
An example to create a frame:
import java.awt.*;
public class FrameExample {
private Frame f;
public FrameExample() {
f = new Frame(“Hello Out There!”);}
public void launchFrame() {
f.setSize(170,170);
f.setBackground(Color.blue);
f.setVisible(true); }
public static void main(String args[]) {
FrameExample guiWindow = new
FrameExample();
guiWindow.launchFrame(); }
}
Declaration of Frame Object
Initialization
of Frame
Object
Setting the size of Frame
Making Frame visible
Use Slides 6 and 7 to explain the characteristics of a frame. Slide 7 uses an example to
explain how to create a frame. Explain each line of the code. A frame is a powerful
feature of the AWT. You can create a window for an application by using the Frame
class. It is derived from java.awt.Container.
Frames can also be created by extending the class from the Frame class. 10.8 Instructor Inputs  ¤NIIT
Slide 8
Slide 8 of 25 Session 10 Ver.  1.0
Java Programming Language
Panels
Panel provide a space for components.
This enables subpanels to have their own layout manager.
After creating Panel, it must be added to a Window or
Frame.
Use Slide 8 to explain the characteristics about panels. Explain that panels are invisible
containers. You can set a panel’s layout manager and position different components onto
it. However, panels need to be placed in a window or a subclass of the window.
Slide 9
Slide 9 of 25 Session 10 Ver.  1.0
Java Programming Language
Panels (Contd.)
The following code snippet helps in creating a small yellow
panel and adds it to a frame:
public Panel pan;
public Frame f;
f=new Frame( “I’m with panel”);
pan = new Panel();
public void launchFrame()
{
f.setSize(200,200);
f.setLayout(null); // Use default layout
pan.setSize(100,100);
pan.setBackground(Color.yellow);
f.add(pan);
f.setVisible(true);
}
Declaring Panel Object
Initializing Panel Object
Setting the size of Panel
Giving the yellow
color to the Panel
Adding Panel to the Frame¤NIIT  Instructor Inputs 10.9
Using the code given in the Slide 9, explain how to create a panel with a colored
background and then how to add a panel to the frame. You can set the size of the frame as
well as the panel. A panel is the common container. It also happens to be the simplest.
Panels are created by calling the Panel() constructor with a Layout Manager as the only
argument. You can then add components to the panel, and then add the panel to another
container.
Slide 10
Slide 10 of 25 Session 10 Ver.  1.0
Java Programming Language
Layout Managers
Layout managers are used to place the components on
required positions.
The following layout managers are included with the Java
programming language:
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
Use Slide 10 to explain the various Layout Managers. Before explaining about the various
Layout Managers, identify the need of the Layout Manager. You need Layout Managers
because each component has a preferred size and you need to place the components
according to your requirement in the Java program.
The Layout Manager gives first preference to the layout policy. If honoring a
component’s preferred size means violating the layout policy, the Layout Manager
overrules the component’s preferred size.
Several AWT and Swing classes provide the following layout managers for general use:
„ BorderLayout
„ BoxLayout
„ CardLayout
„ FlowLayout
„ GridBagLayout
„ GridLayout
„ SpringLayout 10.10 Instructor Inputs  ¤NIIT
Slide 11
Slide 11 of 25 Session 10 Ver.  1.0
Java Programming Language
The Default layout manager for Window, Frame, and
Dialog class is BorderLayout.
In the same way for Panel and Applet, FlowLayout is
default layout manager.
Layout Managers (Contd.)
Use Slide 11 to explain the default layout for a frame, a panel, and an applet.
Slide 12
Slide 12 of 25 Session 10 Ver.  1.0
Java Programming Language
The FlowLayout manager has the following
characteristics:
Forms the default layout for the Panel class
Adds components from left to right
Alignment default is centered
Uses components preferred sizes
Uses the constructor to tune behavior
Layout Managers (Contd.)
Use Slide 12 to explain the characteristics of the FlowLayout Manager. FlowLayout is the
default layout manager for every panel. It simply lays out components in a single row,
starting a new row if its container is not sufficiently wide.  ¤NIIT  Instructor Inputs 10.11
Slide 13
Slide 13 of 25 Session 10 Ver.  1.0
Java Programming Language
A simple example of FlowLayout:
public class LayoutExample
{
private Frame f;
private Button b1;
private Button b2;
public LayoutExample()
{
f = new Frame(“GUI example”);
b1 = new Button(“Press Me”);
b2 = new Button(“Don’t press Me”);
}
Layout Managers (Contd.)
Initializing the
components
Declaring the components
Slide 14
Slide 14 of 25 Session 10 Ver.  1.0
Java Programming Language
public void launchFrame()
{
f.setLayout(new FlowLayout());
f.add(b1);
f.add(b2);
f.pack();
f.setVisible(true);
}
public static void main(String args[])
{
LayoutExample guiWindow = new
LayoutExample();
guiWindow.launchFrame();
}
}
Layout Managers (Contd.)
Adding components on the Frame
Setting FlowLayout
Use Slides 13 and 14 to show the example code for the FlowLayout Manager. 10.12 Instructor Inputs  ¤NIIT
Slide 15
Slide 15 of 25 Session 10 Ver.  1.0
Java Programming Language
The preceding code will show the following output:
Layout Managers (Contd.)
Slide 15 shows the output of the code given on Slides 13 and 14.
Slide 16
Slide 16 of 25 Session 10 Ver.  1.0
Java Programming Language
The BorderLayout manager has following characteristics:
Default layout for the Frame class
Components are added to specific regions
The resizing behavior is as follows:
North, South, and Center regions adjust horizontally
East, West, and Center regions adjust vertically
Layout Managers (Contd.)¤NIIT  Instructor Inputs 10.13
Slide 17
Slide 17 of 25 Session 10 Ver.  1.0
Java Programming Language
Using the constructor without any parameters constructs and
installs a new BorderLayout with no gaps between the
components:
setLayout(new BorderLayout());
BorderLayout constructor specifiying hgap and vgap can be
used to indicate the gaps between components:
BorderLayout(int hgap,int vgap);
Components must be added to the named regions in
BorderLayout manager:
f.add(button1,BorderLayout.NORTH);
Layout Managers (Contd.)
Use Slides 16 and 17 to explain the characteristics of the BorderLayout Manager.
BorderLayout places components in five areas: top, bottom, left, right, and center. All
extra space is placed in the center area.
While declaring the BorderLayout regions, predefined constants are preferred to avoid
runtime exceptions such as borderlayout.NORTH.
Slide 18
Slide 18 of 25 Session 10 Ver.  1.0
Java Programming Language
The characteristics of GridLayout manager are:
Components are added from left to right, and from top to
bottom.
All regions are sized equally.
The constructor specifies the rows and columns. For example:
f.setLayout (new GridLayout(3, 2));
This statement using in Java Program will help to get the
following output:
Layout Managers (Contd.)10.14 Instructor Inputs  ¤NIIT
Use Slide 18 to explain the characteristics of the GridLayout Manager. GridLayout simply
makes a bunch of components equal in size and displays them in the requested number of
rows and columns.
Slide 19
Slide 19 of 25 Session 10 Ver.  1.0
Java Programming Language
Lets see how to create a Java class that uses the AWT API
to create a simple GUI front end.
Layout Managers (Contd.)
Give a demo to the students to show how to create a Java class that uses the AWT API to
create a simple GUI front end.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod10_gui\exercise1\DemoProject. ¤NIIT  Instructor Inputs 10.15
Slide 20
Slide 20 of 25 Session 10 Ver.  1.0
Java Programming Language
Drawing in AWT
Graphics class is an abstract class, which is used for
drawing graphical figures.
Every component has a Graphics object.
The Graphics class implements many drawing methods.
You can draw in any Component (although AWT provides
the Canvas and Panel classes just for this purpose).
Create a subclass of Canvas or Panel and override the
paint() method.
The paint() method is called every time the component is
shown (for example, if another window overlapped the
component and was then removed).
Use Slide 20 to explain that you can draw images by using the AWT. The Graphics class
provides many methods for drawing various shapes, such as rectangles, circles, ovals,
arches, lines, and strings.
Slide 21
Slide 21 of 25 Session 10 Ver.  1.0
Java Programming Language
Example of paint() method:
public void paint( Graphics g )
{
//display word “today” centred at x,y
positions
FontMetrics fm = getFontMetrics(
g.getFont() );
String wording = “today”;
int xadj = fm.stringWidth( wording ) / 2;
//position bottom left corner of the text
g.drawString( wording, x-xadj, y );
//draw a red line from x1,y1 to x2,y2
Drawing in AWT (Contd.)10.16 Instructor Inputs  ¤NIIT
Slide 22
Slide 22 of 25 Session 10 Ver.  1.0
Java Programming Language
g.setColor(Color.red );
g.drawLine(x1, y1, x2, y2);
//draw an pre-existing Image.imX, imY is
top left corner of the Image.
g.drawImage (
image,imX,imY,imWidth,imHeight,this);
} // end paint
Drawing in AWT (Contd.)
Use Slides 21 and 22 to discuss how to use the paint method with the Graphics class
parameter passed into it, draw various objects, and then paint them in different colors.
Slide 23
Slide 23 of 25 Session 10 Ver.  1.0
Java Programming Language
Various Shapes Drawn by the Graphics Object:
Drawing in AWT (Contd.)
Use Slide 23 to show the various figures that can be drawn by using the AWT. ¤NIIT  Instructor Inputs 10.17
Slide 24
Slide 24 of 25 Session 10 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
Abstract Window Toolkit provides GUI components that are
used in all Java applets and applications.
Window and Panel are subclasses of container.
Button, Choice, Label, List, Scrollbar,
TextComponent are various components supported by Java
programming language.
Frame is subclass of Window and they are invisible until
setVisible(true)method is not used to expose them.
Panel provides space for components and then panel need to
be added to a Frame or Window.
Layout Managers are provided by Java language to place the
components at any required positions.
Slide 25
Slide 25 of 25 Session 10 Ver.  1.0
Java Programming Language
Summary (Contd.)
Java programming Language supports following Layout
Managers:
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
FlowLayout manager adds the components from left to right
and it is default layout for Panel.
BorderLayout manager adds the components to specific
regions i.e North, South, East, West, and Centre.
GridLayout manager adds components from left to right, and
from top to bottom. The regions are sized equally as the
specified number of rows and columns in the constructor.
Graphical figures can be drawn by using Graphics class
object.
Use Slides 24 and 25 to summarize the key points of this session. 10.18 Instructor Inputs  ¤NIIT
The following section provides some extra inputs on the important topics covered in the
SG.
To start with GUI applications, create the window that it will be active. In the Java AWT,
top-level windows are represented by the Frame class. The most common way of creating
a frame is by using its single-argument constructor that takes a single string, which
represents the window’s title. The frame is initially invisible. Therefore, after creating it,
the code needs to call the Frame’s show() method, which it inherits from the Window
class.
Various Layout Managers
Several AWT and Swing classes provide the following layout managers for general use.
BoxLayout
The BoxLayout class arranges components in a single row or column. It respects the
component’s requested maximum sizes and enables you to align components.
CardLayout
Additional Inputs
Creating the Window¤NIIT  Instructor Inputs 10.19
The CardLayout class enables you to implement an area that contains different
components at different times. CardLayout is often controlled by a combo box. The state
of the combo box determines the panel or group of components that will display the
CardLayout. An alternative to using CardLayout is using a tabbed pane, which provides a
similar functionality with a predefined GUI.
GridBagLayout
The GridBagLayout class is one of the most flexible and complex layout managers in the
Java language. GridBagLayout arranges components in a grid of rows and columns. It
allows specified components to span in multiple rows or columns where all rows not
necessarily have the same height, and similarly, not all rows and columns necessarily
have the same width. Essentially, GridBagLayout places components in cells in a grid,
and then uses the components’ preferred sizes to determine how big the cells should be.
The program specifies the size and position characteristics of its components by
specifying constraints for each component. To specify constraints, you set instance
variables in a GridBagConstraints object and inform the GridBagLayout, with the
setConstraints method, to associate the constraints with the component.
The following sections explain the constraints you can set with examples.
Specifying Constraints
The following code shows the contents of a container that uses GridBagLayout.
Panel pane = new Panel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//For each component to be added to this container:
//…Create the component…
//…Set instance variables in the GridBagConstraints instance…
pane.add(theComponent, c); 10.20 Instructor Inputs  ¤NIIT
Note
Note
You can reuse the same GridBagConstraints instance for multiple components, even if the
components have different constraints. GridBagLayout extracts the constraint values and
does not use the GridBagConstraints again. You must be careful, however, to reset the
GridBagConstraints instance variables to their default values, when necessary.
The following discussion assumes that GridBagLayout controls a container that has a
left-to-right component orientation.
You can set the following GridBagConstraints instance variables.
gridx, gridy
Specify the row and column in the upper-left corner of the component screen. The
leftmost column has address gridx=0 and the top row has address gridy=0.
Use GridBagConstraints.RELATIVE, the default value, to specify that the component
should be placed just to the right of (for gridx) or just below (for gridy) the component
that was added to the container just before this component was added.
gridwidth, gridheight
For gridwidth, specify the number of columns, and for gridheight, specify the number of
rows in the component’s display area. These constraints specify the number of cells that
the component uses, not the number of pixels it uses. The default value is 1.
Use GridBagConstraints.REMAINDER to specify that the component should be the last
one in its row for gridwidth and should be the last one in its column for gridheight.
Use GridBagConstraints.RELATIVE to specify that the component should be the next to
last one in its row for gridwidth or next to the last one in its column for gridheight.
GridBagLayout does not allow components to span multiple rows unless the component
is in the leftmost column or unless you have specified positive gridx and gridy values
for the component. ¤NIIT  Instructor Inputs 10.21
fill
This variable is used when the component’s display area is larger than the component’s
requested size to determine how to resize the component. Valid values, defined as
GridBagConstraints constants, are:
„ NONE: Is the default value
„ HORIZONTAL: Makes the component wide enough to fill its display area
horizontally but does not change its height
„ VERTICAL: Makes the component tall enough to fill its display area vertically but
does not change its width
„ BOTH: Makes the component fill its display area entirely
ipadx, ipady
These variables specify the internal padding, that is, how much to add to the minimum
size of the component. The default value is zero. The width of the component will be at
least its minimum width plus ipadx*2 pixels because the padding applies to both the sides
of the component. Similarly, the height of the component will be at least its minimum
height plus ipady*2 pixels.
insets
It specifies the external padding of the component, which refers to the minimum amount
of space between the component and the edges of its display area. The value is specified
as an Insets object. By default, the component has no external padding.
anchor
This variable is used when the component is smaller than its display area to determine
where to place the component within the area. Valid values defined as
GridBagConstraints constants are CENTER (which is the default value), PAGE_START,
PAGE_END, LINE_START, LINE_END, FIRST_LINE_START, FIRST_LINE_END,
LAST_LINE_END, and LAST_LINE_START.
weightx, weighty
Weights are used to determine how to distribute space among columns (weightx) and
among rows (weighty). 10.22 Instructor Inputs  ¤NIIT
„ As a platform-independent programming language, how is Java used to make GUIs
platform independent?
Ans: The Java technology provides the Abstract Window Toolkit (AWT) as a solution to
make GUI platform independent. It gives a library of GUI components that can be used in
a Java application and applet.
„ What is GridBagLayout?
Ans: GridBagLayout is a standard layout manager provided with all Java
implementations. Layout Managers help you arrange GUIs that dynamically rearrange
their components due to window size changes as well as changes in fonts or other
attributes of components, such as the displayed text.
FAQs

———————————————————————-

Instructor Inputs
Session 10 ¤NIIT  Instructor Inputs 10.3
This session covers Chapter 10.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Create an application by using a class and its objects.
„ Variable declaration and initialization in class programs.
This session introduces containers like windows, frames, and panels. It explains how
GUIs are put together and formatted, and describes some of the components from which
GUIs are built. You need to relate these concepts to real-life examples. Encourage the
students to come up with examples of things around them.
Slide 1
Slide 1 of 25 Session 10 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Describe the Abstract Window Toolkit (AWT) package and  its
components
Define the terms containers, components, and layout
managers, and describe how they work together to build a GUI
Use the Frame and Panel containers appropriately
Add components to a container
Use various layout managers to achieve a desired dynamic
layout
Objectives
Use Slide 1 to share the session objectives with the students.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 10.4 Instructor Inputs  ¤NIIT
Slide 2
Slide 2 of 25 Session 10 Ver.  1.0
Java Programming Language
Provides GUI components that are used in all Java applets
and applications.
Contains classes that can be composed or extended.
Ensures that every GUI component that is displayed on the
screen is a subclass of  class Component or
MenuComponent.
Has Container, which is an abstract subclass of
Component and includes two subclasses:
Panel
Window
Abstract Window Toolkit
Use Slide 2 to explain the characteristics of abstract window toolkit.
Introduce the Abstract Window Toolkit (AWT) package to the students and discuss its
importance in the Java programming language. Most of the interactive user input and
output is done through GUIs. The Java platform provides a number of classes in the AWT
package to make programming and setup of GUIs easy. The AWT package contains
classes of components from which GUIs are pieced together. In addition, it also contains
classes that handle other aspects, such as color, font, and layout of components.   ¤NIIT  Instructor Inputs 10.5
Slide 3
Slide 3 of 25 Session 10 Ver.  1.0
Java Programming Language
The java.awt Package
Basic overview of AWT package:
Java.lang.object
Applet
Button
Canvas
Container
Label
List
TextComponent
MenuBar
MenuItem
Menu
CheckboxMenuItem
Panel
Window
ScrollPane
Dialog
Frame
TextArea
TextField
BorderLayout
FlowLayout
CardLayout
CheckboxGroup
Event
Color
Font
Graphics
MenuComponent
GridLayout
GridBagLayout
Image
Rectangle
Component
Use slide 3 to explain the hierarchy of the AWT package. Explain that buttons, labels, and
lists are subclasses of the Component class. The Dialog and Frame classes belong to the
Window class.
Slide 4
Slide 4 of 25 Session 10 Ver.  1.0
Java Programming Language
Containers
The two main types of containers are:
Window
Panel
A Window is a free floating window on the display.
A Panel is a container of GUI components that must exist
in the context of some other container, such as a Window or
Applet.
Add components with the add() method.10.6 Instructor Inputs  ¤NIIT
Slide 5
Slide 5 of 25 Session 10 Ver.  1.0
Java Programming Language
Components
Java programming language supports various components:
Button
Choice
Label
List
Scrollbar
TextComponent, etc.
The position and size of a component in a container is
determined by a layout manager.
You must use setLocation(), setSize(), or
setBounds() on components to locate them in the
container.
Use Slides 4 and 5 to explain components and containers.
In addition to static components like the label, Java AWT provides dynamic components
that allow user interaction/input, such as the Choice component. Choices are components
that allow the user to select from a drop-down menu of items. A good example of this is
the Location box, which is located at the top of the browser window. It probably has a
history attached to it, and gives you the option of selecting the previously entered
locations.
Choices are always created with the zero-argument constructor because they do not
include any other constructor. The menu of items is then populated by calling the Choice’s
add() method. Then, the Choice component can be added to a container by using the
Container’s add() method, as done in the Label component.  ¤NIIT  Instructor Inputs 10.7
Slide 6
Slide 6 of 25 Session 10 Ver.  1.0
Java Programming Language
Frames have the following characteristics:
Are a subclass of Window
Have title and resizing corners
Are invisible initially; use setVisible(true) to expose the
frame
Have BorderLayout as the default layout manager
Use the setLayout() method to change the default layout
manager
Frames
Slide 7
Slide 7 of 25 Session 10 Ver.  1.0
Java Programming Language
Frames (Contd.)
An example to create a frame:
import java.awt.*;
public class FrameExample {
private Frame f;
public FrameExample() {
f = new Frame(“Hello Out There!”);}
public void launchFrame() {
f.setSize(170,170);
f.setBackground(Color.blue);
f.setVisible(true); }
public static void main(String args[]) {
FrameExample guiWindow = new
FrameExample();
guiWindow.launchFrame(); }
}
Declaration of Frame Object
Initialization
of Frame
Object
Setting the size of Frame
Making Frame visible
Use Slides 6 and 7 to explain the characteristics of a frame. Slide 7 uses an example to
explain how to create a frame. Explain each line of the code. A frame is a powerful
feature of the AWT. You can create a window for an application by using the Frame
class. It is derived from java.awt.Container.
Frames can also be created by extending the class from the Frame class. 10.8 Instructor Inputs  ¤NIIT
Slide 8
Slide 8 of 25 Session 10 Ver.  1.0
Java Programming Language
Panels
Panel provide a space for components.
This enables subpanels to have their own layout manager.
After creating Panel, it must be added to a Window or
Frame.
Use Slide 8 to explain the characteristics about panels. Explain that panels are invisible
containers. You can set a panel’s layout manager and position different components onto
it. However, panels need to be placed in a window or a subclass of the window.
Slide 9
Slide 9 of 25 Session 10 Ver.  1.0
Java Programming Language
Panels (Contd.)
The following code snippet helps in creating a small yellow
panel and adds it to a frame:
public Panel pan;
public Frame f;
f=new Frame( “I’m with panel”);
pan = new Panel();
public void launchFrame()
{
f.setSize(200,200);
f.setLayout(null); // Use default layout
pan.setSize(100,100);
pan.setBackground(Color.yellow);
f.add(pan);
f.setVisible(true);
}
Declaring Panel Object
Initializing Panel Object
Setting the size of Panel
Giving the yellow
color to the Panel
Adding Panel to the Frame¤NIIT  Instructor Inputs 10.9
Using the code given in the Slide 9, explain how to create a panel with a colored
background and then how to add a panel to the frame. You can set the size of the frame as
well as the panel. A panel is the common container. It also happens to be the simplest.
Panels are created by calling the Panel() constructor with a Layout Manager as the only
argument. You can then add components to the panel, and then add the panel to another
container.
Slide 10
Slide 10 of 25 Session 10 Ver.  1.0
Java Programming Language
Layout Managers
Layout managers are used to place the components on
required positions.
The following layout managers are included with the Java
programming language:
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
Use Slide 10 to explain the various Layout Managers. Before explaining about the various
Layout Managers, identify the need of the Layout Manager. You need Layout Managers
because each component has a preferred size and you need to place the components
according to your requirement in the Java program.
The Layout Manager gives first preference to the layout policy. If honoring a
component’s preferred size means violating the layout policy, the Layout Manager
overrules the component’s preferred size.
Several AWT and Swing classes provide the following layout managers for general use:
„ BorderLayout
„ BoxLayout
„ CardLayout
„ FlowLayout
„ GridBagLayout
„ GridLayout
„ SpringLayout 10.10 Instructor Inputs  ¤NIIT
Slide 11
Slide 11 of 25 Session 10 Ver.  1.0
Java Programming Language
The Default layout manager for Window, Frame, and
Dialog class is BorderLayout.
In the same way for Panel and Applet, FlowLayout is
default layout manager.
Layout Managers (Contd.)
Use Slide 11 to explain the default layout for a frame, a panel, and an applet.
Slide 12
Slide 12 of 25 Session 10 Ver.  1.0
Java Programming Language
The FlowLayout manager has the following
characteristics:
Forms the default layout for the Panel class
Adds components from left to right
Alignment default is centered
Uses components preferred sizes
Uses the constructor to tune behavior
Layout Managers (Contd.)
Use Slide 12 to explain the characteristics of the FlowLayout Manager. FlowLayout is the
default layout manager for every panel. It simply lays out components in a single row,
starting a new row if its container is not sufficiently wide.  ¤NIIT  Instructor Inputs 10.11
Slide 13
Slide 13 of 25 Session 10 Ver.  1.0
Java Programming Language
A simple example of FlowLayout:
public class LayoutExample
{
private Frame f;
private Button b1;
private Button b2;
public LayoutExample()
{
f = new Frame(“GUI example”);
b1 = new Button(“Press Me”);
b2 = new Button(“Don’t press Me”);
}
Layout Managers (Contd.)
Initializing the
components
Declaring the components
Slide 14
Slide 14 of 25 Session 10 Ver.  1.0
Java Programming Language
public void launchFrame()
{
f.setLayout(new FlowLayout());
f.add(b1);
f.add(b2);
f.pack();
f.setVisible(true);
}
public static void main(String args[])
{
LayoutExample guiWindow = new
LayoutExample();
guiWindow.launchFrame();
}
}
Layout Managers (Contd.)
Adding components on the Frame
Setting FlowLayout
Use Slides 13 and 14 to show the example code for the FlowLayout Manager. 10.12 Instructor Inputs  ¤NIIT
Slide 15
Slide 15 of 25 Session 10 Ver.  1.0
Java Programming Language
The preceding code will show the following output:
Layout Managers (Contd.)
Slide 15 shows the output of the code given on Slides 13 and 14.
Slide 16
Slide 16 of 25 Session 10 Ver.  1.0
Java Programming Language
The BorderLayout manager has following characteristics:
Default layout for the Frame class
Components are added to specific regions
The resizing behavior is as follows:
North, South, and Center regions adjust horizontally
East, West, and Center regions adjust vertically
Layout Managers (Contd.)¤NIIT  Instructor Inputs 10.13
Slide 17
Slide 17 of 25 Session 10 Ver.  1.0
Java Programming Language
Using the constructor without any parameters constructs and
installs a new BorderLayout with no gaps between the
components:
setLayout(new BorderLayout());
BorderLayout constructor specifiying hgap and vgap can be
used to indicate the gaps between components:
BorderLayout(int hgap,int vgap);
Components must be added to the named regions in
BorderLayout manager:
f.add(button1,BorderLayout.NORTH);
Layout Managers (Contd.)
Use Slides 16 and 17 to explain the characteristics of the BorderLayout Manager.
BorderLayout places components in five areas: top, bottom, left, right, and center. All
extra space is placed in the center area.
While declaring the BorderLayout regions, predefined constants are preferred to avoid
runtime exceptions such as borderlayout.NORTH.
Slide 18
Slide 18 of 25 Session 10 Ver.  1.0
Java Programming Language
The characteristics of GridLayout manager are:
Components are added from left to right, and from top to
bottom.
All regions are sized equally.
The constructor specifies the rows and columns. For example:
f.setLayout (new GridLayout(3, 2));
This statement using in Java Program will help to get the
following output:
Layout Managers (Contd.)10.14 Instructor Inputs  ¤NIIT
Use Slide 18 to explain the characteristics of the GridLayout Manager. GridLayout simply
makes a bunch of components equal in size and displays them in the requested number of
rows and columns.
Slide 19
Slide 19 of 25 Session 10 Ver.  1.0
Java Programming Language
Lets see how to create a Java class that uses the AWT API
to create a simple GUI front end.
Layout Managers (Contd.)
Give a demo to the students to show how to create a Java class that uses the AWT API to
create a simple GUI front end.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod10_gui\exercise1\DemoProject. ¤NIIT  Instructor Inputs 10.15
Slide 20
Slide 20 of 25 Session 10 Ver.  1.0
Java Programming Language
Drawing in AWT
Graphics class is an abstract class, which is used for
drawing graphical figures.
Every component has a Graphics object.
The Graphics class implements many drawing methods.
You can draw in any Component (although AWT provides
the Canvas and Panel classes just for this purpose).
Create a subclass of Canvas or Panel and override the
paint() method.
The paint() method is called every time the component is
shown (for example, if another window overlapped the
component and was then removed).
Use Slide 20 to explain that you can draw images by using the AWT. The Graphics class
provides many methods for drawing various shapes, such as rectangles, circles, ovals,
arches, lines, and strings.
Slide 21
Slide 21 of 25 Session 10 Ver.  1.0
Java Programming Language
Example of paint() method:
public void paint( Graphics g )
{
//display word “today” centred at x,y
positions
FontMetrics fm = getFontMetrics(
g.getFont() );
String wording = “today”;
int xadj = fm.stringWidth( wording ) / 2;
//position bottom left corner of the text
g.drawString( wording, x-xadj, y );
//draw a red line from x1,y1 to x2,y2
Drawing in AWT (Contd.)10.16 Instructor Inputs  ¤NIIT
Slide 22
Slide 22 of 25 Session 10 Ver.  1.0
Java Programming Language
g.setColor(Color.red );
g.drawLine(x1, y1, x2, y2);
//draw an pre-existing Image.imX, imY is
top left corner of the Image.
g.drawImage (
image,imX,imY,imWidth,imHeight,this);
} // end paint
Drawing in AWT (Contd.)
Use Slides 21 and 22 to discuss how to use the paint method with the Graphics class
parameter passed into it, draw various objects, and then paint them in different colors.
Slide 23
Slide 23 of 25 Session 10 Ver.  1.0
Java Programming Language
Various Shapes Drawn by the Graphics Object:
Drawing in AWT (Contd.)
Use Slide 23 to show the various figures that can be drawn by using the AWT. ¤NIIT  Instructor Inputs 10.17
Slide 24
Slide 24 of 25 Session 10 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
Abstract Window Toolkit provides GUI components that are
used in all Java applets and applications.
Window and Panel are subclasses of container.
Button, Choice, Label, List, Scrollbar,
TextComponent are various components supported by Java
programming language.
Frame is subclass of Window and they are invisible until
setVisible(true)method is not used to expose them.
Panel provides space for components and then panel need to
be added to a Frame or Window.
Layout Managers are provided by Java language to place the
components at any required positions.
Slide 25
Slide 25 of 25 Session 10 Ver.  1.0
Java Programming Language
Summary (Contd.)
Java programming Language supports following Layout
Managers:
FlowLayout
BorderLayout
GridLayout
CardLayout
GridBagLayout
FlowLayout manager adds the components from left to right
and it is default layout for Panel.
BorderLayout manager adds the components to specific
regions i.e North, South, East, West, and Centre.
GridLayout manager adds components from left to right, and
from top to bottom. The regions are sized equally as the
specified number of rows and columns in the constructor.
Graphical figures can be drawn by using Graphics class
object.
Use Slides 24 and 25 to summarize the key points of this session. 10.18 Instructor Inputs  ¤NIIT
The following section provides some extra inputs on the important topics covered in the
SG.
To start with GUI applications, create the window that it will be active. In the Java AWT,
top-level windows are represented by the Frame class. The most common way of creating
a frame is by using its single-argument constructor that takes a single string, which
represents the window’s title. The frame is initially invisible. Therefore, after creating it,
the code needs to call the Frame’s show() method, which it inherits from the Window
class.
Various Layout Managers
Several AWT and Swing classes provide the following layout managers for general use.
BoxLayout
The BoxLayout class arranges components in a single row or column. It respects the
component’s requested maximum sizes and enables you to align components.
CardLayout
Additional Inputs
Creating the Window¤NIIT  Instructor Inputs 10.19
The CardLayout class enables you to implement an area that contains different
components at different times. CardLayout is often controlled by a combo box. The state
of the combo box determines the panel or group of components that will display the
CardLayout. An alternative to using CardLayout is using a tabbed pane, which provides a
similar functionality with a predefined GUI.
GridBagLayout
The GridBagLayout class is one of the most flexible and complex layout managers in the
Java language. GridBagLayout arranges components in a grid of rows and columns. It
allows specified components to span in multiple rows or columns where all rows not
necessarily have the same height, and similarly, not all rows and columns necessarily
have the same width. Essentially, GridBagLayout places components in cells in a grid,
and then uses the components’ preferred sizes to determine how big the cells should be.
The program specifies the size and position characteristics of its components by
specifying constraints for each component. To specify constraints, you set instance
variables in a GridBagConstraints object and inform the GridBagLayout, with the
setConstraints method, to associate the constraints with the component.
The following sections explain the constraints you can set with examples.
Specifying Constraints
The following code shows the contents of a container that uses GridBagLayout.
Panel pane = new Panel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//For each component to be added to this container:
//…Create the component…
//…Set instance variables in the GridBagConstraints instance…
pane.add(theComponent, c); 10.20 Instructor Inputs  ¤NIIT
Note
Note
You can reuse the same GridBagConstraints instance for multiple components, even if the
components have different constraints. GridBagLayout extracts the constraint values and
does not use the GridBagConstraints again. You must be careful, however, to reset the
GridBagConstraints instance variables to their default values, when necessary.
The following discussion assumes that GridBagLayout controls a container that has a
left-to-right component orientation.
You can set the following GridBagConstraints instance variables.
gridx, gridy
Specify the row and column in the upper-left corner of the component screen. The
leftmost column has address gridx=0 and the top row has address gridy=0.
Use GridBagConstraints.RELATIVE, the default value, to specify that the component
should be placed just to the right of (for gridx) or just below (for gridy) the component
that was added to the container just before this component was added.
gridwidth, gridheight
For gridwidth, specify the number of columns, and for gridheight, specify the number of
rows in the component’s display area. These constraints specify the number of cells that
the component uses, not the number of pixels it uses. The default value is 1.
Use GridBagConstraints.REMAINDER to specify that the component should be the last
one in its row for gridwidth and should be the last one in its column for gridheight.
Use GridBagConstraints.RELATIVE to specify that the component should be the next to
last one in its row for gridwidth or next to the last one in its column for gridheight.
GridBagLayout does not allow components to span multiple rows unless the component
is in the leftmost column or unless you have specified positive gridx and gridy values
for the component. ¤NIIT  Instructor Inputs 10.21
fill
This variable is used when the component’s display area is larger than the component’s
requested size to determine how to resize the component. Valid values, defined as
GridBagConstraints constants, are:
„ NONE: Is the default value
„ HORIZONTAL: Makes the component wide enough to fill its display area
horizontally but does not change its height
„ VERTICAL: Makes the component tall enough to fill its display area vertically but
does not change its width
„ BOTH: Makes the component fill its display area entirely
ipadx, ipady
These variables specify the internal padding, that is, how much to add to the minimum
size of the component. The default value is zero. The width of the component will be at
least its minimum width plus ipadx*2 pixels because the padding applies to both the sides
of the component. Similarly, the height of the component will be at least its minimum
height plus ipady*2 pixels.
insets
It specifies the external padding of the component, which refers to the minimum amount
of space between the component and the edges of its display area. The value is specified
as an Insets object. By default, the component has no external padding.
anchor
This variable is used when the component is smaller than its display area to determine
where to place the component within the area. Valid values defined as
GridBagConstraints constants are CENTER (which is the default value), PAGE_START,
PAGE_END, LINE_START, LINE_END, FIRST_LINE_START, FIRST_LINE_END,
LAST_LINE_END, and LAST_LINE_START.
weightx, weighty
Weights are used to determine how to distribute space among columns (weightx) and
among rows (weighty). 10.22 Instructor Inputs  ¤NIIT
„ As a platform-independent programming language, how is Java used to make GUIs
platform independent?
Ans: The Java technology provides the Abstract Window Toolkit (AWT) as a solution to
make GUI platform independent. It gives a library of GUI components that can be used in
a Java application and applet.
„ What is GridBagLayout?
Ans: GridBagLayout is a standard layout manager provided with all Java
implementations. Layout Managers help you arrange GUIs that dynamically rearrange
their components due to window size changes as well as changes in fonts or other
attributes of components, such as the displayed text.
FAQs

————————————————————————————–

2-4-7

Instructor Inputs
Session 2 ¤NIIT  Instructor Inputs 2.3
This session covers Chapter 2 and Chapter 3.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Writing a simple Java application program
„ Basic OOP concepts
Begin the session by explaining the significance of programming language keywords to
the students. In this session, they will understand the class type and primitive type data. In
addition, explain the significance of the reference variables. The students will learn about
operator usage and expressions in a Java application program. The session describes
operators, arithmetic expressions, and the layout of various control structures governing
the path of program execution.
The students are already familiar with flow control structures and the various
programming constructs; therefore, these need to be quickly brushed up by using the Java
programming syntax. Inform the students that Java is case-sensitive. This means that
the variable name employeeAge is not the same as the variable name
EmployeeAge. Explain “pass-by-value”. Please refer to the Additional Inputs
section for an example to explain the pass-by-value concept.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 2.4 Instructor Inputs  ¤NIIT
Slide 1
Slide 1 of 26 Session 2 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Distinguish between valid and invalid identifiers
List the eight primitive types
Define literal values for numeric and textual types
Define the terms primitive variable and reference variable
Declare variables of class type
Construct an object using new
Describe default initialization
Distinguish between instance and local variables
Objectives
Slide 2
Slide 2 of 26 Session 2 Ver.  1.0
Java Programming Language
Objectives (Contd.)
Describe how to initialize instance variables
Identify boolean expressions and their requirements in control
constructs
Recognize assignment compatibility and required casts in
fundamental types
Use if, switch, for, while, and do constructions and the labeled
forms of break and continue as flow control structures in a
program
Use Slides 1 and 2 to share the session objectives with the students. ¤NIIT  Instructor Inputs 2.5
Slide 3
Slide 3 of 26 Session 2 Ver.  1.0
Java Programming Language
Identifier
An identifier is a name given to a variable, class, or method.
Identifiers have the following characteristics:
Can start with a Unicode letter, underscore (_), or dollar sign
($)
Are case-sensitive and have no maximum length
Examples of valid identifiers:
identifier
userName
user_name
_sys_var1
$change
The variables in Java can be assigned constant values. The values assigned must match
the data type of the variables. Literals are values that can be assigned to primitive or string
type variables and constants. You can refer to the Additional Inputs section for more
inputs on literals.
Slide 4
Slide 4 of 26 Session 2 Ver.  1.0
Java Programming Language
Basic Data Types in Java
Java programming language supports two basic data types:
Primitive types
Class types
Use Slides 3 and 4 to explain identifiers and basic data types. 2.6 Instructor Inputs  ¤NIIT
Slide 5
Slide 5 of 26 Session 2 Ver.  1.0
Java Programming Language
Primitive data types are simple values, not objects.
The Java programming language defines eight primitive
data types, which can be considered in four categories:
Logical – boolean
Textual – char
Integral – byte, short, int, and long
Floating – double and float
Primitive Data Types
Slide 6
Slide 6 of 26 Session 2 Ver.  1.0
Java Programming Language
Class Data Type
Class types are used for more complex types, including all
the types that you declare yourself.
They are used to create objects.
Use Slides 5 and 6 to explain the difference between the primitive type and the class data
type. ¤NIIT  Instructor Inputs 2.7
Slide 7
Slide 7 of 26 Session 2 Ver.  1.0
Java Programming Language
Variables, Declarations, and Assignments
Possible ways to declare and assign variables in Java are
as follows:
public class Assign
{ public static void main (String args[])
{
// declare and assign values to int
integer variables int x=6, y=1000;
// declare and assign floating point
float z = 3.414f;
// declare and assign boolean
boolean truth = true;
// declare and assign String variable
String str1 = “bye”;
// declare and assign value to char variable
char c = ‘A’; }}
Use Slide 7 to explain the possible ways to declare and assign variables in Java.
Slide 8
Slide 8 of 26 Session 2 Ver.  1.0
Java Programming Language
Java Reference Type
In Java technology, beyond primitive types all other data
types are reference types.
A reference variable contains a handle to an object.
For example:
public class MyDate
{ private int day = 1;
private int month = 1;
private int year = 2000;
public MyDate(int day, int month, int
year) { ………. }
public String toString() { ………. }
}2.8 Instructor Inputs  ¤NIIT
Slide 9
Slide 9 of 26 Session 2 Ver.  1.0
Java Programming Language
Java Reference Type (Contd.)
public class TestMyDate {
public static void main(String[] args)
{  MyDate today = new MyDate(22, 7,
1964);
}
}
Variable today is a reference variable holding one object of
MyDate class.
Use Slides 8 and 9 to explain the reference data type in Java.
Slide 10
Slide 10 of 26 Session 2 Ver.  1.0
Java Programming Language
Constructing and Initializing Objects
Calling new xyz() performs the following actions:
Memory is allocated for the object
Explicit attribute initialization is performed
A constructor is executed
The object reference is returned by the new operator
The reference to the object is assigned to a variable
For example:
MyDate my_birth = new MyDate(22, 7, 1964);
Use Slide 10 to explain object construction and initialization. ¤NIIT  Instructor Inputs 2.9
Slide 11
Slide 11 of 26 Session 2 Ver.  1.0
Java Programming Language
Pass-By-Value
In a single Java Virtual Machine, the Java programming
language only passes arguments by value.
When an object instance is passed as an argument to a
method, the value of the argument is a reference to the
object.
The contents of the object can be changed in the called
method, but the original object reference is never changed.
Slide 12
Slide 12 of 26 Session 2 Ver.  1.0
Java Programming Language
The this Reference
Two uses of the this keyword are:
To resolve ambiguity between instance variables and
parameters
To pass the current object as a parameter to another method
or constructor
Use Slides 11 and 12 to explain pass-by-value and the this keyword.
Please refer to the Additional Inputs section for more inputs on the this. 2.10 Instructor Inputs  ¤NIIT
Slide 13
Slide 13 of 26 Session 2 Ver.  1.0
Java Programming Language
Lets see how to define a reference type instance variable in a
Java class, and manipulate the object referenced by this
variable.
Demonstration
You should give a demo to the students to explain how to define a reference type instance
variable in a Java class, and manipulate the object referenced by this variable.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod03_types\exercise2\DemoProject.
Slide 14
Slide 14 of 26 Session 2 Ver.  1.0
Java Programming Language
Java Programming Language Coding Conventions
Examples of coding conventions are:
Packages:
com.example.domain;
Classes, interfaces, and enum types:
SavingsAccount
Methods:
getAccount()
Variables:
CurrentCustomer
Constants:
HEAD_COUNT¤NIIT  Instructor Inputs 2.11
Use Slide 14 to explain Java Programming Language Coding Conventions.
Slide 15
Slide 15 of 26 Session 2 Ver.  1.0
Java Programming Language
Variables and Scope
Variables defined inside a method are called local variables,
also referred to as automatic, temporary, or stack variables.
Local variables must be initialized before the first use.
Variables defined outside a method are created when the
object is constructed using the new xxx() call. They are of
two types:
Static variables: They are created when the class is loaded
and continue to exist for as long as the class is loaded.
Instance variables: They are declared without using the
static keyword. They continue to exist for as long as the
object exists.
Use Slide 15 to explain the scope of variables.
Local variables are created and initialized every time a method is invoked or the program
control enters the block. The variables are destroyed when the method or the block
completes execution. Parameters of a method are also local to the method.
The variables declared outside methods have a class scope. The variable and its value are
retained as long as an object of the particular class exists, and can be used in all the
methods of the class. If a variable is declared public, it can be accessed from the objects
of all classes. 2.12 Instructor Inputs  ¤NIIT
Slide 16
Slide 16 of 26 Session 2 Ver.  1.0
Java Programming Language
Logical Operators
The boolean operators are:
! NOT &  AND
| OR ^  XOR
The short-circuit boolean operators are:
&&  AND || OR
You can use these operators as follows:
MyDate d = reservation.getDepartureDate();
if ( (d != null) && (d.day > 31) {
// do something with d
}
Slide 17
Slide 17 of 26 Session 2 Ver.  1.0
Java Programming Language
Right-Shift Operators >> and >>>
The operator >> performs an arithmetic or signed right shift.
The result of this shift is that the first operand is divided by 2
raised to the number of times specified by the second
operand.
The sign bit is copied during the shift.
This operator is used for bit patterns.
The sign bit is not copied during the shift.
Examples are:
128 >> 1 returns 128/21 = 64
256 >> 4 returns 256/24 = 16
-256 >> 4 returns -256/24 = -16¤NIIT  Instructor Inputs 2.13
Slide 18
Slide 18 of 26 Session 2 Ver.  1.0
Java Programming Language
Left-Shift Operator <<
The operator << performs a left shift. The result of this shift
is that the first operand is multiplied by 2 raised to the
number specified by the second operand.
For Example:
128 << 1 returns 128 * 21 = 256
16 << 2 returns 16 * 22 = 64
Use Slides 16, 17, and 18 to explain operator precedence and bitwise logical operators.
Slide 19
Slide 19 of 26 Session 2 Ver.  1.0
Java Programming Language
Casting
Casting means assigning a value of one type to a variable of
another type.
If information might be lost in an assignment, the
programmer must confirm the assignment with a cast.
The assignment between long and int requires an explicit
cast.
Examples of casting are:
long bigValue = 99L;
int squashed = bigValue; // Wrong, needs a cast
int squashed = (int) bigValue; // OK
int squashed = 99L; // Wrong, needs a cast2.14 Instructor Inputs  ¤NIIT
Slide 20
Slide 20 of 26 Session 2 Ver.  1.0
Java Programming Language
Promotion and Casting of Expressions
Variables are promoted automatically to a longer form (such
as int to long).
Expression is assignment-compatible if the variable type is
at least as large (the same number of bits) as the
expression type.
For Example:
long bigval = 6; // 6 is an int type, OK
int smallval = 99L; // 99L is a long, illegal
double z = 12.414F; // 12.414F is float, OK
float z1 = 12.414; // 12.414 is double, illegal
Use Slides 19 and 20 to explain the concept of casting.
To prevent any loss of information, Java automatically promotes values to a higher data
type.
Consider the following statement:
int x = 5.5/2;
The expression on the right evaluates to a decimal value and the expression on the left is
an integer, and therefore, cannot hold a fraction. When you compile this code, the
compiler will give the following error:
“Incompatible type for declaration. Explicit cast needed to convert double to int.”
This is because data can be lost when it is converted from a higher data type to a lower
data type. The compiler requires you to typecast the assignment. To accomplish this, use
the following statement:
int x = (int)5.5 / 2;
This is known as Explicit Typecasting. This type of typecasting is performed when there
is a possibility of loss of data during conversion. Rules for typecasting are mentioned in
the Additional Inputs section. ¤NIIT  Instructor Inputs 2.15
Slide 21
Slide 21 of 26 Session 2 Ver.  1.0
Java Programming Language
Branching Statement
Conditional statements enable the selective execution of
portions of the program according to the value of some
expressions.
Simple if, else Statements:
The syntax is:
if ( <boolean_expression> )
<statement_or_block>
Complex if, else Statements:
The syntax is:
if ( <boolean_expression> )
<statement_or_block>
else
<statement_or_block>
Slide 22
Slide 22 of 26 Session 2 Ver.  1.0
Java Programming Language
The switch Statement
The switch statement:
The syntax is:
switch ( <expression> ) {
case <constant1>:
<statement_or_block>*
[break;]
case <constant2>:
<statement_or_block>*
[break;]
default:
<statement_or_block>*
[break;]}
In the switch (<expression>) statement,
<expression> must be expression compatible with an
int type.2.16 Instructor Inputs  ¤NIIT
Slide 23
Slide 23 of 26 Session 2 Ver.  1.0
Java Programming Language
Looping Statement
Looping Statements enable you to execute block of
statements repeatedly.
Java programming language supports three types of loop
constructs:
The for loop
The while loop
The do/while loop
Slide 24
Slide 24 of 26 Session 2 Ver.  1.0
Java Programming Language
Special Loop Flow Control
The following statements can be used to further control loop
statements:
The break [<label>]; command
The continue [<label>]; command
The <label> : <statement> command, where
<statement> should be a loop
Use Slides 21, 22, 23, and 24 to explain the branching statements and the flow control
statements. ¤NIIT  Instructor Inputs 2.17
Slide 25
Slide 25 of 26 Session 2 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
An identifier is a name given to a variable, class, or method. An
identifier can not be a keyword.
Java technology keywords identify a data type name or program
construct name.
The Java programming language provides class and
primitive data types.
An object can be constructed using the keyword new.
The Java programming language passes arguments only by
value.
The this keyword is used to resolve ambiguity between
instance variables and parameters.
There are two types of variables, primitive type and reference
type.
Slide 26
Slide 26 of 26 Session 2 Ver.  1.0
Java Programming Language
Summary (Contd.)
Casting means assigning a value of one type to a variable of
another type.
Conditional statements enable the selective execution of
portions of the program according to the value of some
expressions:
If and switch statements help to perform two-way and
multiple-way branching.
The for and while loops test the loop condition before
executing the loop body.
The do loops check the loop condition after executing the loop
body.
The labeled forms of break and continue help to further
control the loop statements.
Use Slides 25 and 26 to summarize the session.  2.18 Instructor Inputs  ¤NIIT
The following section provides some extra inputs on the important topics covered in the
SG.
Pass by Value
Consider the following example:
Cat A = new Cat();
Cat B = A;
The reference A is copied. Note the object it refers to. There is still just one Cat object.
But now there are two different references or remote controls, controlling the same Cat
object.
Values are passed to methods as follows.
In Java, values are passed to the methods by “pass-by-value”.
That means “copy the value, and pass the copy.”
For primitives:
int x = 5;
doStuff(x); // pass a COPY of x (the value 5) to the doStuff method
The doStuff method looks like this:
void doStuff(int y) {
// use y in some way
}
A copy of the value in x, which is 5, is passed into the doStuff() method.
The doStuff() method has its own new cup, called y, waiting.
The y cup is a new, different cup with a copy of what was in x at the time it was passed.
Additional Inputs ¤NIIT  Instructor Inputs 2.19
From this point on, y and x have no affect on each other. If you change y, you do not
touch x.
void doStuff(int y) {
y = 27; // this does NOT affect x
}
Its reverse also holds true, that is, if you change x, you do not change y.
The only function of the variable x is to simply copy its value and send that copy to the
doStuff() method.
How does pass-by-value work with references?
With primitives, you get a copy of the contents. With references, you get a copy of the
contents.
What is the content of a reference?
It is the remote control, the means to control or access the object.
When you pass an object reference into a method, you are passing a COPY of the
REFERENCE, a clone of the remote control. The object is still waiting for someone to
use a remote.
Rules for Literals
„ The Boolean literals are true and false.
„ The integer literals are numeric data. They can be represented as octal, which means,
the number is prefixed with a zero, or hexadecimal, which means, the number is
prefixed with 0x.
„ Floating-point literals are numbers that have a decimal fraction.
„ Character literals are enclosed in single quotes.
„ String literals are enclosed in double quotes.
Creating an instance of a class
A class provides the blueprint for objects. You create an object from a class. Each of the
following statements taken from the CreateObjectDemo program creates an object and
assigns it to a variable:
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200); 2.20 Instructor Inputs  ¤NIIT
Rectangle rectTwo = new Rectangle(50, 100);
The first statement creates an object of the Point class, and the second and third
statements each create an object of the Rectangle class.
Each of these statements has three parts:
1. Declaration: The lines of code set in bold are variable declarations that associate a
variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which
initializes the new object.
Declaring a Variable to Refer to an Object
There are eight primitive Java types. All other types refer to objects rather than primitives.
Variables that refer to objects are called reference variables. For example:
Point originOne;
If you declare originOne in this manner, its value will be undetermined until an object is
actually created and assigned to it. Simply declaring a reference variable does not create
an object. For that, you need to use the new operator. You need to assign an object to
originOne before you use it in your code. Otherwise, you will get a compiler error.
A variable in this state, which currently references no object, can be illustrated as follows,
the variable name, originOne, plus a reference pointing to nothing:
Rules for Typecasting
„ A Boolean variable cannot be typecast.
„ If the conversion increases the range of data that can be stored, there is an implicit
conversion of non-Boolean data.
„ If the range is narrowed, an explicit typecast is required.
„ An implicit cast occurs in the following order:
byte Î short Î int Î long Î float Î double
charÎ int Î long Î float Î double
Any other conversion needs to be typecast because it narrows the range of values that can
be stored. ¤NIIT  Instructor Inputs 2.21
Note
The this Reference
The this keyword allows you to specify the current object. It eliminates the need to store a
separate copy of every variable and method for each instantiation of a class. The this
reference always refers to the current object. In other words, when you write this.name,
this refers to the current object’s copy of the name.
When you invoke a new object method from the same object, there is no need to prefix a
this reference. The this reference is included implicitly by Java as follows:
public class Test {
void someMethod() {
anotherMethod();
}
void anotherMethod() {
// method definition here…
}
}
In the above code, anotherMethod is invoked without an object reference. This code will
compile because when the compiler encounters an unreferenced method, it first looks in
the local class for one that matches it. If it finds a matching method, the keyword this is
prefixed to the method call implicitly.
So, the above code is actually the equivalent to writing the following:
public class Test {
void someMethod() {
this.anotherMethod();
}
void anotherMethod() {
// method definition here…
}
}
You need not write it in this manner. Java does it for you in such cases.
You can only use the object reference this inside a non static method. This is because a
static method is a class-level method; that is, it is associated with the type and not a
specific object. It does not make any sense to refer to this when there is no object. 2.22 Instructor Inputs  ¤NIIT
„ What is the difference between an identifier, a literal, and a keyword?
Ans: An identifier is the name given to a variable, a class, or a method. A literal is the
value that may be assigned to a primitive or a string type variable and constant. A
keyword is a special word that is of significance to the Java compiler. You cannot use
keywords to name classes or variables.
„ If Java uses the pass-by reference, why will a swap function not work?
Ans: Java manipulates objects by reference, and all object variables are references.
However, Java does not pass method arguments by reference; it passes them by value.
„ Can multiple classes have variables with the same name, and if so, what is their
scope?
Ans: Yes, multiple classes can have variables with the same name. The scope of such
variables is the class scope.
FAQs

—————————————————————————————————————————————————————-

Instructor Inputs
Session 4 ¤NIIT  Instructor Inputs 4.3
This session covers Chapter 5 and upto the Polymorphic Arguments section in Chapter 6.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Writing a Java application program with expressions and flow control statements
„ Scope of variables
This session explains the Java programming language implementation of arrays or
groupings of similar elements. It discusses the cover declaration and initialization of
arrays as well as their use. In addition, it lists the most important aspects of inheritance,
code reuse, polymorphism, and virtual method invocation.
After explaining how to create an array, you can explain how to create reference arrays.
While teaching the students about overriding methods, reiterate how overriding is
different from overloading. Java does not support operator overloading as in C#. You
need to explain the implementation of polymorphism in Java. You also need to reiterate
the concept of dynamic binding, which the students studied in C#.
Slide 1
Slide 1 of 26 Session 4 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Declare and create arrays of primitive, class, or array types
Explain how to initialize the elements of an array
Determine the number of elements in an array
Create a multidimensional array
Write code to copy array values from one array to another
Define inheritance, polymorphism, overloading, overriding, and
virtual method invocation
Define heterogeneous collections
Objectives
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 4.4 Instructor Inputs  ¤NIIT
Use Slide 1 to share the session objectives with the students.
Slide 2
Slide 2 of 26 Session 4 Ver.  1.0
Java Programming Language
Arrays
Declaring Arrays:
Group data objects of the same type.
An array is an object.
Declare arrays of primitive or class types:
char s[ ];
Point p[ ];
char[ ] s;
Point[ ] p;
The declaration of an array creates space for a reference.
Actual memory allocation is done dynamically either by a new
statement or by an array initializer.
Use Slide 2 to explain array declaration.
An array is a representation of data in contiguous spaces in the memory of the computer.
All variables of the array have the same name. Each element in the array is distinguished
by the index. All the elements in the array should be of the same data type. For example,
you cannot have one element of the int data type and another of the boolean data type in
the same array. An array is a collection of elements of the same type that are referenced
by a common name. Each element of an array can be referred to by an array name and a
subscript or index. To create and use an array in Java, you first need to declare the array
and then initialize it.  ¤NIIT  Instructor Inputs 4.5
Slide 3
Slide 3 of 26 Session 4 Ver.  1.0
Java Programming Language
Creating Arrays
In order to create an array object:
Use the new keyword
An example to create and initialize a primitive (char) array:
public char[] createArray()
{
char[] s;
s = new char[26];
for ( int i=0; i<26; i++ )
{
s[i] = (char) (’A’ + i);
}
return s;
}
This code generates an array in the heap memory with the upper case letters of the
English alphabet.
Slide 4
Slide 4 of 26 Session 4 Ver.  1.0
Java Programming Language
Creating Arrays (Contd.)
Creating an Array of Character Primitives:
Use Slides 3 and 4 to explain creation of arrays.
Discuss stack and heap memory again. 4.6 Instructor Inputs  ¤NIIT
Slide 5
Slide 5 of 26 Session 4 Ver.  1.0
Java Programming Language
Creating Reference Arrays
The following code snippet creates an array of 10
references of type Point:
public Point[] createArray()
{
Point[] p;
p = new Point[10];
for ( int i=0; i<10; i++ )
{
p[i] = new Point(i, i+1);
}
return p;
}
Slide 6
Slide 6 of 26 Session 4 Ver.  1.0
Java Programming Language
Creating Reference Arrays (Contd.)
Creating an Array of Character Primitives with Point
Objects:
Use Slides 5 and 6 to explain how to create reference arrays.
After declaring an array variable, you can allocate memory to it. This is done by using the
new operator, which allocates memory to objects. The new operator is followed by the
type, and finally, the number of elements to allocate. The number of elements to allocate
is placed within the [] operator. ¤NIIT  Instructor Inputs 4.7
Slide 7
Slide 7 of 26 Session 4 Ver.  1.0
Java Programming Language
Lets see how to declare, create, and manipulate an array of
reference type elements.
Demonstration
You should demonstrate to the students how to declare, create and manipulate an array of
reference type elements.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod05_arrays\exercise2\DemoProject.
Slide 8
Slide 8 of 26 Session 4 Ver.  1.0
Java Programming Language
Multidimensional Arrays
A Multidimensional array is an array of arrays.
For example:
int [] [] twoDim = new int [4] [];
twoDim[0] = new int [5];
twoDim[1] = new int[5];
The first call to new creates an object, an array that contains
four elements. Each element is a null reference to an element
of type array of int.
Each element must be initialized separately so that each
element points to its array.4.8 Instructor Inputs  ¤NIIT
Use Slide 8 to explain multidimensional arrays.
Slide 9
Slide 9 of 26 Session 4 Ver.  1.0
Java Programming Language
Array Bounds
All array subscripts begin at 0.
The number of elements in an array is stored as part of the
array object in the length attribute.
The following code uses the length attribute to iterate on
an array:
public void printElements(int[] list)
{
for (int i = 0; i < list.length; i++)
{
System.out.println(list[i]);
}
}
Use Slide 9 to explain array bounds.
Arrays help store values of the same type that are logically related to one another, such as
lists of invoices, lists of names, and lists of Web page hits. However, being fixed-length,
if the number of values that you are storing is unknown or changes, there are better data
structures available in the Java Collections API. These include ArrayList and HashSet.
The Java Collections classes will be covered extensively in the course in the coming
sessions.
In Java, arrays cannot be resized dynamically. One approach is to use java.util.ArrayList
or java.util.Vector instead of a native array. Another approach is to reallocate the array
with a different size and to copy the contents of the old array to the new array. The latter
approach is faster. The generic function resizeArray can be used to do that, as shown in
the following lines:
public static void main (String[] args) {
int[] a = {1,2,3};
a = (int[])resizeArray(a,5);
a[3] = 4;
a[4] = 5;
for (int i=0; i<a.length; i++)
System.out.println (a[i]); ¤NIIT  Instructor Inputs 4.9
Slide 10
Slide 10 of 26 Session 4 Ver.  1.0
Java Programming Language
The Enhanced for Loop
Java 2 Platform, Standard Edition (J2SE™) version 5.0 has
introduced an enhanced for loop for iterating over arrays:
public void printElements(int[] list)
{
for ( int element : list )
{
System.out.println(element);
}
}
The for loop can be read as for each element in list do.
Use Slide 10 to explain the enhanced for loop.
Slide 11
Slide 11 of 26 Session 4 Ver.  1.0
Java Programming Language
Array Resizing
You cannot resize an array.
You can use the same reference variable to refer to an
entirely new array, such as:
int[] myArray = new int[6];
myArray = new int[10];
In the preceding case, the first array is effectively lost unless
another reference to it is retained elsewhere.4.10 Instructor Inputs  ¤NIIT
Slide 12
Slide 12 of 26 Session 4 Ver.  1.0
Java Programming Language
Copying Arrays
The Java programming language provides a special method
in the System class, arraycopy(), to copy arrays.
For example:
int myarray[] = {1,2,3,4,5,6}; // original array
Int hold[] = {10,9,8,7,6,5,4,3,2,1}; // new
larger array
System.arraycopy(myarray,0,hold,0,
myarray.length); // copy all of the myarray array to
the hold array, starting with the 0th index
The contents of the array hold will be : 1,2,3,4,5,6,4,3,2,1.
The System.arraycopy() method copies references, not
objects, when dealing with array of objects.
Use Slides 11 and 12 to explain array resizing and copying of arrays.
Slide 13
Slide 13 of 26 Session 4 Ver.  1.0
Java Programming Language
Inheritance
Inheritance means that a class derives a set of attributes
and related behavior from a parent class.
Benefits of Inheritance:
Reduces redundancy in code
Code can be easily maintained
Extends the functionality of an existing class¤NIIT  Instructor Inputs 4.11
Slide 14
Slide 14 of 26 Session 4 Ver.  1.0
Java Programming Language
Single Inheritance
The subclasses are derived from one super class.
An example of single inheritance is as follows:
Inheritance (Contd.)
Slide 15
Slide 15 of 26 Session 4 Ver.  1.0
Java Programming Language
Java does not support multiple inheritance.
Interfaces provide the benefits of multiple inheritance
without drawbacks.
Syntax of a Java class in order to implement inheritance is
as follows:
<modifier> class <name> [extends
superclass>]
{   <declaration>*   }
Inheritance (Contd.)
Use Slides 13, 14, and 15 to explain the concept of inheritance. 4.12 Instructor Inputs  ¤NIIT
Slide 16
Slide 16 of 26 Session 4 Ver.  1.0
Java Programming Language
Access Control
Variables and methods can be at one of the following four
access levels:
public
protected
default
private
Classes can be at the public or default levels.
The default accessibility (if not specified explicitly), is
package-friendly or package-private.
Use Slide 16 to explain the various access specifiers.
You can use the Additional Inputs section for more input on the access specifiers.
Slide 17
Slide 17 of 26 Session 4 Ver.  1.0
Java Programming Language
Overriding Methods
A subclass can modify behavior inherited from a parent
class.
Overridden methods cannot be less accessible.
A subclass can create a method with different functionality
than the parent’s method but with the same:
Name
Return type
Argument list
In addition to inheriting data members and methods, subclasses can modify the
functionality of the superclass. If a method defined in the subclass has the same signature ¤NIIT  Instructor Inputs 4.13
as that in the superclass, the subclass method overrides, that is, hides or supersedes the
definition of the superclass method.
For example, the WheelChair class is derived from the Chair class. Both the classes have
a method called adjustHeight(). However, a wheelchair is adjusted in a different way than
the other chairs are adjusted. Therefore, the WheelChair class overrides the superclass
method adjustHeight().
You can access data members and methods of a superclass through an instance of its
subclass. When you call a method from the subclass, Java first searches for the definition
of the method in the current class. If the method is not declared in the current class, it
searches for the definition of the method in the superclass.
Rules for Overriding Methods
„ The order of arguments and the name of the overriding method should be identical to
that of the superclass method.
„ The return type of both the overridden and overriding methods should be the same.
„ The overriding method cannot be less accessible than the method it overrides. For
example, if the method that overrides is declared as public in the superclass, you
cannot override it with the private keyword in the subclass.
„ An overriding method cannot raise more exceptions than those raised by the method
of the superclass. Exceptions are errors that are raised at run time.
Slide 18
Slide 18 of 26 Session 4 Ver.  1.0
Java Programming Language
Overriding Methods (Contd.)
A subclass method may invoke a superclass method using
the super keyword:
The keyword super is used in a class to refer to its
superclass.
The keyword super is used to refer to the members of
superclass, both data attributes and methods.
Behavior invoked does not have to be in the superclass; it can
be further up in the hierarchy.4.14 Instructor Inputs  ¤NIIT
Slide 19
Slide 19 of 26 Session 4 Ver.  1.0
Java Programming Language
Overriding Methods (Contd.)
Invoking Overridden Methods using super keyword:
public class Employee
{
private String name;
private double salary;
private Date birthDate;
public String getDetails()
{
return “Name: ” + name +
“\nSalary: “ + salary;
}
}
Slide 20
Slide 20 of 26 Session 4 Ver.  1.0
Java Programming Language
Overriding Methods (Contd.)
public class Manager extends Employee
{
private String department;
public String getDetails() {
// call parent method
return super.getDetails()
+ “\nDepartment: ” + department;
}
}
Use Slides 17, 18, 19, and 20 to explain overriding methods. ¤NIIT  Instructor Inputs 4.15
Slide 21
Slide 21 of 26 Session 4 Ver.  1.0
Java Programming Language
Lets see how to create subclasses and call the constructor of
the base class.
Demonstration
You should give a demo to the student how to create subclasses and call the constructor of
the base class.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod06_class1\exercise2\DemoProject.
Slide 22
Slide 22 of 26 Session 4 Ver.  1.0
Java Programming Language
Polymorphism
Polymorphism is the ability to have many different forms;
for example, the Manager class has access to methods
from Employee class.
An object has only one form.
A reference variable can refer to objects of different forms.
Java programming language permits you to refer to an object
with a variable of one of the parent class types.
For example:
Employee e = new Manager(); // legal4.16 Instructor Inputs  ¤NIIT
Use Slide 22 to explain polymorphism.
Slide 23
Slide 23 of 26 Session 4 Ver.  1.0
Java Programming Language
Virtual Method Invocation
Virtual method invocation is performed as follows:
Employee e = new Manager();
e.getDetails();
Compile-time type and runtime type invocations have the
following characteristics:
The method name must be a member of the declared variable
type; in this case Employee has a method called getDetails.
The method implementation used is based on the runtime object’s
type; in this case the Manager class has an implementation of the
getDetails method.
Use Slide 23 to explain virtual method invocation.
Slide 24
Slide 24 of 26 Session 4 Ver.  1.0
Java Programming Language
Heterogeneous Collections
Heterogeneous Collections:
Collections of objects with the same class type are called
homogeneous collections. For example:
MyDate[] dates = new MyDate[2];
dates[0] = new MyDate(22, 12, 1964);
dates[1] = new MyDate(22, 7, 1964);
Collections of objects with different class types are called
heterogeneous collections. For example:
Employee [] staff = new Employee[1024];
staff[0] = new Manager();
staff[1] = new Employee();
staff[2] = new Engineer();
Use Slide 24 to explain collections. ¤NIIT  Instructor Inputs 4.17
A collection, sometimes called a container, is an object that groups multiple elements into
a single unit. Collections are used to store, retrieve, manipulate, and communicate the
aggregate data. Typically, they represent data items that form a natural group, such as a
poker hand (which is a collection of cards), a mail folder (which is a collection of letters),
or a telephone directory (which is a mapping of names to phone numbers).
You can refer to the Additional Inputs section for more information on collections.
Slide 25
Slide 25 of 26 Session 4 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
Arrays are objects used to group data objects of the same
type. Arrays can be of primitive or class type.
Arrays can be created by using the keyword new.
A multidimensional array is an array of arrays.
All array indices begin at 0. The number of elements in an
array is stored as part of the array object in the length
attribute.
An array once created can not be resized. However the same
reference variable can be used to refer to an entirely new
array.
The Java programming language permits a class to extend
one other class i.e, single inheritance.
Slide 26
Slide 26 of 26 Session 4 Ver.  1.0
Java Programming Language
Summary (Contd.)
Variables and methods can be at one of the four access levels:
public, protected, default, or private.
Classes can be at the public or default level.
The existing behavior of a base class can be modified by
overriding the methods of the base class.
A subclass method may invoke a superclass method using the
super keyword.
Polymorphism is the ability to have many different forms; for
example, the Manager class (derived) has the access to
methods from Employee class (base).
Collections of objects with different class types are called
heterogeneous collections.
Use Slides 25 and 26 to summarize the session. 4.18 Instructor Inputs  ¤NIIT
The following section provides some extra inputs on the important topics covered in the
SG.
Access Specifier
An access specifier determines the features of a class, such as the class itself, the data
members, and the methods, which may be used by other classes. Java supports three
access specifiers, also known as access modifiers.
„ The public access specifier
„ The private access specifier
„ The protected access specifier
The public Access Specifier
All classes except inner classes, which are classes within other classes, can have the
public access specifier. You can use a public class, a data member, or a method from any
object in any Java program.
Example
public class PublicClass
{
public  int publicVariable;
public void publicMethod()
{
…
}
}
The private Access Specifier
Only objects of the same class can access a private variable or method. You can declare
only variables, methods, and inner classes as private.
Example
private int privateVariable;
Additional Inputs ¤NIIT  Instructor Inputs 4.19
The protected Access Specifier
Variables, methods, and inner classes that are declared protected are accessible to the
subclasses of the class in which they are declared.
Example
protected int protectedVariable;
Default Access
If you do not specify any of these access specifiers, the scope is friendly. A class,
variable, or method that has friendly access is accessible to all the classes of a package. A
package is a collection of classes.
In Java, friendly is not a keyword. It is a term that is used for the access level when no
access specifier has been specified. You cannot declare a class, variable, or method with
the friendly specifier.
Consider the following set of classes. Classes Y and Z inherit from class X. Class Z
belongs to the package P1 and classes X and Y belong to the package P2.
A method accessMe() has been declared in class X. The following table shows the
accessibility of the method accessMe() from classes Y and Z.
Access Specifier Class Y Class Z
accessMe() is declared as
protected
Accessible, because Y is a
subclass
Accessible, because Z is a
subclass although it is in
another package
accessMe() is declared
without an access specifier
(friendly)
Accessible, because it is in
the same package
Not accessible, because it is
not in the same package
Class X
Class Y
Class Z
Package P1  Package P2 4.20 Instructor Inputs  ¤NIIT
A variable that you declare inside a method cannot have access specifiers because the
variable can only be used within the method.
A public method in a nonpublic class or a friendly method that can be accessed only
inside the same package unless it has a public super class.
Collections Framework
A collections framework is a unified architecture for representing and manipulating
collections. All collections frameworks contain the following:
„ Interfaces: They are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation.
„ Implementations: They are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
„ Algorithms: They are methods that perform useful computations, such as searching
and sorting, on objects that implement collection interfaces.
„ Explain the different forms of polymorphism.
Ans: Polymorphism exists in three distinct forms in Java:
„ Method overloading
„ Method overriding through inheritance
„ Method overriding through the Java interface
„ What are the advantages of the collections framework?
Ans: The Java collections framework:
„ Reduces programming effort: By providing useful data structures and algorithms,
the collections framework enables you to concentrate on the important parts of your
program rather than on the low-level “plumbing” required to make it work.
„ Increases program speed and quality: This framework provides high-performance,
high-quality implementations of useful data structures and algorithms. You can
devote more time to improve programs’ quality and performance because you do not
need to write your own data structures.
„ Allows interoperability among unrelated APIs: The collection interfaces are the
vernacular by which APIs pass collections back and forth.
FAQs ¤NIIT  Instructor Inputs 4.21
„ Reduces effort to learn and use new APIs: Many APIs naturally take collections
on input and furnish them as output. In the past, each such API had a little sub-API
devoted to manipulating its collections. There was little consistency among these ad
hoc collections sub-APIs. Therefore, you had to learn each one from scratch, and it
was easy to make mistakes when using them. With the advent of standard collection
interfaces, the problem was solved.
„ Reduces effort to design new APIs: This is the flip side of the previous advantage.
Designers and implementers need not reinvent the wheel each time they create an
API that relies on collections; instead, they can use standard collection interfaces.
„ Fosters software reuse: New data structures that conform to the standard collection
interfaces are reusable by nature. The same is true for new algorithms that operate on
objects that implement these interfaces.
„ What is the default access specifier?
Ans: The default access specifier is friendly. 4.22 Instructor Inputs  ¤NIIT

—————————————————————————————————-

Instructor Inputs
Session 7 ¤NIIT  Instructor Inputs 7.3
This session covers Chapter 7 from the Final Keyword section onwards and the whole of
Chapter 8.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Multiple inheritance
„ Method overriding
„ Basic error handling
[
You can begin the session by providing a recap of the various modifiers. Then, explain
the use of the final keyword. The session will cover the enumerated types in detail. In
addition, it will cover the use of abstract classes and interfaces. The students will learn to
develop programs in Java to handle their own exceptions. In addition, they will also learn
to use assertions.
Slide 1
Slide 1 of 24 Session 7 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Create final classes, methods, and variables
Create and use enumerated types
Use the static import statement
Create abstract classes and methods
Create and use an interface
Define exceptions
Use try, catch, and finally statements
Describe exception categories
Identify common exceptions
Develop programs to handle your own exceptions
Use assertions
Distinguish appropriate and inappropriate uses of assertions
Enable assertions at runtime
Objectives
Use Slide 1 to introduce the objectives of the session.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 7.4 Instructor Inputs  ¤NIIT
Slide 2
Slide 2 of 24 Session 7 Ver.  1.0
Java Programming Language
The final Keyword
The final keyword is used for security reasons.
It is used to create classes that serve as a standard.
It implements the following restrictions:
You cannot subclass a final class.
You cannot override a final method.
A final variable is a constant.
All methods and data members in a final class are implicitly
final.
You can set a final variable once only, but that
assignment can occur independently of the declaration;
this is called a blank final variable.
Slide 3
Slide 3 of 24 Session 7 Ver.  1.0
Java Programming Language
Blank Final Variables
A final variable that is not initialized in its declaration; its
initialization is delayed:
A blank final instance variable must be assigned in a
constructor.
A blank final local variable can be set at any time in the body of
the method.
It can be set once only.
Use Slides 2 and 3 to explain the final modifier to the students. ¤NIIT  Instructor Inputs 7.5
Slide 4
Slide 4 of 24 Session 7 Ver.  1.0
Java Programming Language
Enumerated Types
An enum type field consist of a fixed set of constants.
You can define an enum type by using the enum keyword.
For example, you would specify a days-of-the-week enum
type as:
public enum Day { SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
The enum class body can include methods and other fields.
The compiler automatically adds some special methods
when it creates an enum.
All enums implicitly extend from java.lang.Enum. Since
Java does not support multiple inheritance, an enum cannot
extend anything else.
Use Slide 4 to explain enumerated types.
The enum type is a type whose fields consist of a fixed set of constants. Common
examples include compass directions; values of NORTH, SOUTH, EAST, and WEST;
and the days of the week.
The field names of an enum type are in uppercase letters because they are constants.
For more inputs on enumerated types, refer to the Additional Inputs section. 7.6 Instructor Inputs  ¤NIIT
Slide 5
Slide 5 of 24 Session 7 Ver.  1.0
Java Programming Language
Static Imports
Imports the static members from a class:
import static
<pkg_list>.<class_name>.<member_name>;
OR
import static <pkg_list>.<class_name>.*;
Imports members individually or collectively:
import static cards.domain.Suit.SPADES;
OR
import static cards.domain.Suit.*;
There is no need to qualify the static constants:
PlayingCard card1 = new PlayingCard(SPADES,
2);
Use Slide 5 to explain static imports to the students.
You can tell the students that static imports should be used when you require frequent
access to static members from one or two classes. If you overuse the static import feature,
it can make your program unreadable and unmaintainable, polluting its namespace with
all the static members that you import.
Slide 6
Slide 6 of 24 Session 7 Ver.  1.0
Java Programming Language
Abstract Classes
An abstract class is declared with abstract access
specifier and it may or may not include abstract methods.
Abstract classes cannot be instantiated, but they can be
subclassed. For Example:
Shape
Circle Rectangle Hexagon¤NIIT  Instructor Inputs 7.7
Slide 7
Slide 7 of 24 Session 7 Ver.  1.0
Java Programming Language
Abstract Classes (Contd.)
An abstract class defines the common properties and
behaviors of other classes.
It is used as a base class to derive specific classes of the
same type. For Example:
abstract class Shape
{
public abstract float calculateArea();
}
The preceding abstract method, calculateArea, is inherited
by the subclasses of the Shape class. The subclasses
Rectangle, Circle, and Hexagon implement this method in
different ways.
Slide 8
Slide 8 of 24 Session 7 Ver.  1.0
Java Programming Language
Abstract Classes (Contd.)
A simple example of implementation of Abstract Method:
public class Circle extends Shape
{
float radius;
public float calculateArea()
{
return ((radius * radius)* (22/7));
}
}
In the preceding example, the calculateArea() method has
been overridden in the Circle class.
Use Slides 6, 7, and 8 to explain the concept of abstract classes.
Abstract classes allow you to implement a behavior in different ways. The classes and
methods declared by using the abstract modifier are incomplete. They are deliberately left
incomplete. The implementation is done in subclasses. Only abstract classes can have
abstract methods. All abstract classes are public by default and cannot be instantiated.
Constructors and static methods cannot be declared as abstract. 7.8 Instructor Inputs  ¤NIIT
You can use the following example to explain an abstract class.
If you were asked to describe a rectangle, you would describe the number of sides it has,
its length, width, and area. You would have a similar description for a hexagon and a
circle. How would you describe a shape? Does it exist? A shape is abstract. You will
come across many abstract classes. For example, automobiles and mammals are abstract
classes.
An abstract class defines the common properties and behaviors of other classes. It is used
as a base class to derive specific classes of the same kind. It defines properties common to
the classes derived from it. The abstract keyword is used to declare such classes.
However, the classes declared by using the abstract keyword cannot be instantiated.
// Creating abstract base class Shape
abstract class Shape
{
…
}
You can also declare abstract methods. They have public scope. The following
code declares an abstract method for the Shape class:
abstract class Shape
{
public abstract float calculateArea();
)
The abstract method calculateArea, given in the previous code, is inherited by the
subclasses of the Shape class. The subclasses Rectangle, Circle, and Hexagon implement
this method in the following ways:
public class Circle extends Shape
{
float radius;
…
public float calculateArea ()
{
return ((radius * radius)* (22/7));
}
In this example, the calculateArea() method has been overridden in the Circle class. If the
Circle class does not override the method, the class will inherit the abstract method from
the parent class. Any class that has an abstract method is abstract and therefore, you will
not be unable to create an object of the Circle class. Therefore, it is necessary to override
the calculateArea() method in the Circle class. ¤NIIT  Instructor Inputs 7.9
Slide 9
Slide 9 of 24 Session 7 Ver.  1.0
Java Programming Language
Interfaces
A public interface is a contract between client code and the
class that implements that interface.
A Java interface is a formal declaration of such a contract in
which all methods contain no implementation.
Many unrelated classes can implement the same interface.
A class can implement many unrelated interfaces.
Syntax of a Java class declaration with interface
implementation is as follows:
<modifier> class <name> [extends
<superclass>]
[implements <interface> [,<interface>]* ]
{ <member_declaration>*
}
Slide 10
Slide 10 of 24 Session 7 Ver.  1.0
Java Programming Language
Interfaces (Contd.)
Interfaces are used to define a behavior protocol (standard
behavior) that can be implemented by any class anywhere
in the class hierarchy. For example:
Consider the devices TV and VDU. Both of them require a
common functionality as far as brightness control is
concerned. This functionality can be provided by
implementing an interface called BrightnessControl which is
applicable for both the devices.
Interfaces can be implemented by classes that are not
related to one another.
Abstract classes are used only when there is a kind-of
relationship between the classes.7.10 Instructor Inputs  ¤NIIT
Slide 11
Slide 11 of 24 Session 7 Ver.  1.0
Java Programming Language
Uses of Interfaces:
Declaring methods that one or more classes are expected to
implement
Determining an object’s programming interface without
revealing the actual body of the class
Capturing similarities between unrelated classes without
forcing a class relationship
Simulating multiple inheritance by declaring a class that
implements several interfaces
Interfaces (Contd.)
Use Slides 9, 10, and 11 to explain the concept of interface.
Interfaces are used to define a behavior protocol or standard behavior that can be
implemented by any class anywhere in the class hierarchy. You can use the following
example to explain interfaces.
Consider the devices TV and VDU. Both require a common functionality as far as
brightness control is concerned. This functionality can be provided by implementing an
interface called BrightnessControl,which is applicable for both the devices. The following
code illustrates the explanation of the interface:
// Interface definition of BrightnessControl
public interface BrightnessControl
{
void increaseBrightness();
void decreaseBrightness();
}
// TV Class implementing the interface
public class TV implements BrightnessControl
{
void increaseBrightness()
{
…  // Implementation code
}
void decreaseBrightness()
{
…  // Implementation code
} ¤NIIT  Instructor Inputs 7.11
}
// VDU class implementing the interface
public class VDU implements BrightnessControl
{
void increaseBrightness()
{
…  // Implementation code
}
void decreaseBrightness()
{
…  // Implementation code
}
}
Slide 12
Slide 12 of 24 Session 7 Ver.  1.0
Java Programming Language
Exceptions and Assertions
Exceptions are a mechanism used to describe what to do
when something unexpected happens. For example:
When a method is invoked with unacceptable arguments
A network connection fails
The user asks to open a non-existent file
Assertions are a way to test certain assumptions about the
logic of a program. For example:
To test that the value of a variable of a variable at a particular
point is always positive7.12 Instructor Inputs  ¤NIIT
Slide 13
Slide 13 of 24 Session 7 Ver.  1.0
Java Programming Language
Exceptions
Conditions that can readily occur in a correct program are
checked exceptions.
These are represented by the Exception class.
Severe problems that normally are treated as fatal or
situations that probably reflect program bugs are unchecked
exceptions.
Fatal situations are represented by the Error class.
Probable bugs are represented by the RuntimeException
class.
The API documentation shows checked exceptions that can
be thrown from a method.
Slide 14
Slide 14 of 24 Session 7 Ver.  1.0
Java Programming Language
Exceptions (Contd.)
Consider the following code snippet:
public void myMethod(int num1 , int num2)
{
int result;
result = num2 / num1;
System.out.println(“Result:” + result);
}
In the above piece of code an exception
java.lang.ArithmeticException is thrown when the
value of num1 is equal to zero. The error message
displayed is:
Exception in thread “main”
java.lang.ArithmeticException: / by zero at
<classname>.main(<filename>)
Use Slides 12, 13, and 14 to explain exception handling and assertion to the students. ¤NIIT  Instructor Inputs 7.13
Slide 15
Slide 15 of 24 Session 7 Ver.  1.0
Java Programming Language
The try-catch Statement
The try-catch block:
The try block governs the statements that are enclosed within
it and defines the scope of the exception-handlers associated
with it.
A try block must have at least one catch block that follows it
immediately.
The catch statement takes the object of the exception class
that refers to the exception caught, as a parameter.
Once the exception is caught, the statements within the catch
block are executed.
The scope of the catch block is restricted to the statements in
the preceding try block only.
Slide 16
Slide 16 of 24 Session 7 Ver.  1.0
Java Programming Language
The try-catch Statement (Contd.)
An example of try-catch block:
public void myMethod(int num1 , int num2)
{
int result;
try{
result = num2 / num1;
}
catch(ArithmeticException e)
{
System.out.println(“Error…division by
zero”);
}
System.out.println(“Result:” + result);
}
Use Slides 15 and 16 to explain try-catch statement. 7.14 Instructor Inputs  ¤NIIT
Slide 17
Slide 17 of 24 Session 7 Ver.  1.0
Java Programming Language
Call Stack Mechanism
If an exception is not handled in the current try-catch block,
it is thrown to the caller of the method.
If the exception gets back to the main method and is not
handled there, the program is terminated abnormally.
Use Slide 17 to explain call stack mechanism.
Slide 18
Slide 18 of 24 Session 7 Ver.  1.0
Java Programming Language
The finally Clause
The characteristics of the finally clause:
Defines a block of code that always executes, regardless of
whether an exception is thrown.
The finally block follows the catch blocks.
It is not mandatory to have a finally block.
Use Slide 18 to explain the finally clause. ¤NIIT  Instructor Inputs 7.15
Slide 19
Slide 19 of 24 Session 7 Ver.  1.0
Java Programming Language
Creating Your Own Exceptions
Characteristics of user-defined exceptions:
Created by extending the Exception class.
The extended class contains constructors, data members and
methods.
The throw and throws keywords are used while
implementing user-defined exceptions.
Use Slide 19 to explain how to create user-defined exceptions.
Mechanism of Exception Handling
In Java, the exception-handling facility handles abnormal and unexpected situations in a
structured manner. When an exception occurs, the Java runtime system searches for an
exception handler, or a try-catch block, in the method that caused the exception. If a
handler is not found in the current method, the system searches the calling method, which
is the method that called the current method. The search continues until the runtime
system finds an appropriate exception handler, that is, when the type of exception caught
by the handler is the same as the type of the exception thrown.
You can use the following example to explain the exception handling mechanism:
//DerivedClass.java
class BaseClass
{
public int divide(int num1, int num2)
{
return num1 / num2;
}
}
public class DerivedClass extends BaseClass
{
public int divide(int a, int b)
{
return super.divide(a, b);
}7.16 Instructor Inputs  ¤NIIT
public static void main(String args[])
{
int result = 0;
DerivedClass d1 = new DerivedClass();
try
{
result = d1.divide(100, 0);
}
catch(ArithmeticException e)
{
System.out.println(“Error… Division by zero”);
}
System.out.println(“The result is: “ + result);
}
}
The output of the preceding code is:
Error…Division by zero.
The result is 0.
In this code, the main() method invokes the overridden method, divide(), of the
derived class. The derived class method, in turn, calls the divide() method of the base
class with the parameters it receives. An exception occurs in the base class method. The
Java runtime system first looks for an exception handler in the base class method, which
is the called method. Then, it looks for an exception handler in the method of the derived
class, which is the calling method. When it does not find the handler there, it shifts to the
main() method and executes the statements in the catch block of the method. ¤NIIT  Instructor Inputs 7.17
Slide 20
Slide 20 of 24 Session 7 Ver.  1.0
Java Programming Language
Let see how to create a custom Exception class, and use it
in a Java program.
Demonstration
Demonstrate to the students how to create a custom Exception class, and use it in a Java
program.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod08_except\exercise1\DemoProject.
Slide 21
Slide 21 of 24 Session 7 Ver.  1.0
Java Programming Language
Syntax of an assertion is:
assert <boolean_expression> ;
assert <boolean_expression> :
<detail_expression> ;
If <boolean_expression> evaluates false, then an
AssertionError is thrown.
The second argument is converted to a string and used as
descriptive text in the AssertionError message.
Assertions7.18 Instructor Inputs  ¤NIIT
Slide 22
Slide 22 of 24 Session 7 Ver.  1.0
Java Programming Language
Assertions (Contd.)
Recommended Uses of Assertions:
Use assertions to document and verify the assumptions and
internal logic of a single method:
Internal invariants
Control flow invariants
Postconditions and class invariants
Inappropriate Uses of Assertions:
Do not use assertions to check the parameters of a public
method.
Do not use methods in the assertion check that can cause
side-effects.
Use Slides 21 and 22 to explain assertions. You can refer to the Additional Inputs section
for more inputs on assertions.
Slide 23
Slide 23 of 24 Session 7 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
final classes cannot be subclassed,final methods cannot
be overriden, and final variables are constant.
An enum type is a type whose fields consist of a fixed set of
constants.
An abstract class defines the common properties and
behaviors of other classes. It is used as a base class to derive
specific classes of the same type:
Abstract classes allow implementation of a behavior in different
ways. The implementation  is done in subclasses.
An abstract class cannot be instantiated.
Subclasses must override the abstract methods of the super
class.
Interfaces are used to define a behavior protocol that can be
implemented by any class anywhere in the class hierarchy.¤NIIT  Instructor Inputs 7.19
Slide 24
Slide 24 of 24 Session 7 Ver.  1.0
Java Programming Language
Summary (Contd.)
An exception is an abnormal event that occurs during the
program execution and disrupts the normal flow of instructions.
You can implement exception handling in your program by
using the following keywords:
try
catch
throws/throw
finally
Assertions can be used  to document and verify the
assumptions and internal logic of a single method:
Internal invariants
Control flow invariants
Postconditions and class invariants
Use Slides 23 and 24 to summarize the session.  7.20 Instructor Inputs  ¤NIIT
The Java programming language enum types are much more powerful than their
counterparts in other languages. The enum declaration defines a class called an enum
type. The enum class body can include methods and other fields. The compiler
automatically adds some special methods when it creates an enum. For example, they
have a static values method that returns an array containing all the values of the enum in
the order they are declared. This method is commonly used in combination with the
for-each construct to iterate over the values of an enum type.
All enums implicitly extend java.lang.Enum. An enum cannot extend anything else
because Java does not support multiple inheritance.
An assertion is a statement in the Java programming language that enables you to test
your assumptions about a program. For example, if you write a method that calculates the
speed of a particle, you might assert that the calculated speed is less than the speed of
light.
Each assertion contains a Boolean expression that you believe will be true when the
assertion executes. If it is not true, the system gives an error. By verifying that the
Boolean expression is indeed true, the assertion confirms your assumptions about the
behavior of the program, increasing your confidence that the program is free from errors.
Writing assertions while programming is one of the quickest and most effective ways to
detect and correct bugs. As an added benefit, assertions serve to document the inner
workings of your program, enhancing the maintainability.
„ What is the difference between an abstract class and an interface?
Ans: An abstract class is used only when there is a kind-of relationship between the
classes. Interfaces can be implemented by classes that are not related to one another. You
can implement more than one interface. The interface imposes method overriding in the
classes that implement it. The interface sets a behavior protocol.
Additional Inputs
Enumerated Types
Assertions
FAQs ¤NIIT  Instructor Inputs 7.21
The methods in an interface cannot be final because they have to be overridden in the
classes that implement them. The methods of an interface are public, by default, because
they have to be overridden by the classes that are not related to the interface.
„ Can there be multiple catch statements for a try statement?
Ans: Yes, it is possible to have multiple catch statements for a try statement.
„ When should you use assertions?
Ans: Assertions are used to verify the internal logic of a single method or a small group of
tightly coupled methods. You should not use assertions to verify that the code is being
used correctly. 7.22 Instructor Inputs  ¤NIIT

1

Instructor Inputs
Session 1 ¤NIIT  Instructor Inputs 1.3
The student guide of this module has two parts:
1. Java Programming Language (SL-275) from Sun Microsystems
2. JDBC from NIIT
SL-275 further has been divided in two parts:
1. The course material
2. The Workbook
SL-275 course material is mapping to the SCJP 5.0 certification i.e. Sun Certified
Developer for Java 2 Platform (SCJP 5.0, exam number CX-310-355).
Workbook contains the Machine Room exercises. Each exercise has been given in three
levels. Level – 1 problem statement give very few hints to solve the problem but level – 3
of the same problem give the entire solution. You should ask students to solve the
problems from level – 1 only. Machine Room exercises solutions will be available in the
TIRM CD in the following folder:
DATAFILES_FOR_FACULTY\JAVA and JDBC\SOLUTIONS
First two cycles execution will be done on Linux to make the students understand that
Java is Platform Independent Language. Rest of the cycles execution will be on windows
using NetBeans IDE, which helps to develop the Java Applications in faster mode using
GUI effectively. We even can drag and drop the controls over the frame using the
NetBeans IDE. The NetBeans IDE will automatically do the coding.
For first two MR exercises part code need to be provided from Data Files for Student
folder of TIRM cd to the students to finish the exercises on time as they will be working
on vi editor for the first time.
Students are learning this module after learning OOP concepts very well in C++ and C#
module. So you can relate the examples with these languages. It is very important to
conduct the sessions with the help of learning plan because in one session (2 hrs) you may
have to deliver two chapters or one and half chapter.
Try discussing the additional inputs given in CG with students in the class to make them
understand the module better.
For cycle 1 and cycle 2 Demo and MR exercises execution will take place on Linux
Server. JDK 5.0 need to be installed on Linux. To write, compile, and execute the
program perform the following steps:
1. .java file will be created using vi editor.
2. Students need to be explained about basic features of vi Editor.
Tips for Handling the Module 1.4 Instructor Inputs  ¤NIIT
Note
3. .java file will be compiled by giving the following command:
javac test.java
4. The execution of java file will be done by giving the following command:
java test
In order to pass command line arguments to a Java application program in NetBeans IDE,
perform the following steps:
1. Select FileÆ”<Project name>” PropertiesÆ Run to open Project Properties
<Project name> dialog box.
2. Type the command line arguments in the Arguments text box.
If there are more than one argument then put space after every argument. ¤NIIT  Instructor Inputs 1.5
This session covers Chapter 1 and Chapter 2.
To understand the concepts covered in the session, the students should be aware of the
following concepts/skills:
„ Creating an application by using a class and its objects
„ Variable declaration and initialization in class programs
In this session, the students will learn about the key features of the Java technology. They
will learn how to write, compile, and run a simple Java technology application. They will
also learn about the software engineering concepts. The session can start with a quick
recap of the basic OOP concepts because the students are already familiar with these
concepts. You can give a brief history of Java. Although the Java programming language
is usually associated with the World Wide Web, its origin predates the Web. Java was
initially known as the programming language Oak.
Oak was developed by the members of the Green Project, a group formed in 1991, to
create products for the smart electronics market. The team decided that the existing
programming languages were not suitable for consumer electronics. The chief
programmer of Sun Microsystems, James Gosling, was assigned the task of creating the
software for controlling consumer electronic devices. The team wanted a fundamentally
new way of computing, based on the power of networks, and wanted the same software to
run on different kinds of computers, consumer gadgets, and other devices. Patenting
issues gave a new name to Oak – Java.
The Java software works on all types of devices, from the smallest devices to
supercomputers. Java technology components (programs) do not depend on the kind of
computer, telephone, television, or operating system they run on. They can work on any
kind of compatible device that supports the Java platform.
Then, you can discuss the Java technology and compare it with other technologies that the
students are familiar with. Explain the function of JVM and the meaning of JRE. It is very
important to make the students understand that Java is platform independent.
Session Overview
Prerequisite Knowledge for the Session
Tips for Handling the Session 1.6 Instructor Inputs  ¤NIIT
Slide 1
Slide 1 of 31 Session 1 Ver.  1.0
Java Programming Language
In this session, you will learn to:
Describe the key features of Java technology
Write, compile, and run a simple Java technology application
Describe the function of the Java Virtual Machine
Define garbage collection
List the three tasks performed by the Java platform that handle
code security
Define modeling concepts: abstraction, encapsulation, and
packages
Discuss why you can reuse Java technology application code
Define class, member, attribute, method, constructor, and
package
Use the access modifiers private and public as appropriate for
the guidelines of encapsulation
Objectives
Slide 2
Slide 2 of 31 Session 1 Ver.  1.0
Java Programming Language
Objectives (Contd.)
Invoke a method on a particular object
Use the Java technology Application Programming Interface
online documentation
Use Slides 1 and 2 to share the session objectives with the students. ¤NIIT  Instructor Inputs 1.7
Slide 3
Slide 3 of 28 Session 1 Ver.  1.0
Java Programming Language
Key Features of Java technology
A programming language
A development environment
An application environment
A deployment environment
Java Technology is used for developing both applets and
applications.
Use Slide 3 to explain the key features of Java technology.
Explain the basic difference between a Java application and an applet by using the
following inputs.
An application is a program that you can execute from the MS-DOS or UNIX prompt.
Stand-alone applications can be either Windows-based or console applications.
Windows-based applications have a graphical user interface (GUI). They use the features
supported by platforms like Microsoft Windows, Macintosh, Motif, and OS/2. Console
applications are character-based applications that do not have a GUI. A stand-alone
application uses the resources of a single computer. Networked applications can use
resources that are available over a network. Distributed applications can access objects
that execute across many computers over a network.
A stand-alone application resides on the local hard disk of your computer. When it needs
to be executed, it is fetched from the hard disk, moved to the internal memory, and then
executed.
Applets are Java programs that execute inside a Web page. Therefore, unlike applications,
applets require a Java-enabled browser. An applet is loaded and executed when a user
loads a Web page through a Web browser. When users view the Web page in which the
applet is embedded, they interact with the applet.  1.8 Instructor Inputs  ¤NIIT
An applet is simple to use. To start the applet, the user only needs to access a Web page.
An application, on the other hand, must be downloaded before it can be executed. An
applet can only access the resources of the host computer; it cannot access the files on the
local computer.
Slide 4
Slide 4 of 31 Session 1 Ver.  1.0
Java Programming Language
Primary Goals of the Java Technology
Provides an easy-to-use language by:
Avoiding many pitfalls of other languages
Being object-oriented
Enables code streamlining
Provides an interpreted environment for:
Improved speed of development
Code portability
Loads classes dynamically, i.e., at the time they are actually
needed
Supports changing programs dynamically during runtime by
loading classes from distinct sources
Furnishes better security
Enable users to run more than one thread of an activity
Slide 5
Slide 5 of 31 Session 1 Ver.  1.0
Java Programming Language
The Java Virtual Machine (JVM™)
Garbage collection
The Java Runtime Environment (JRE)
JVM tool interface
Primary Features of the Java Technology
Use Slides 4 and 5 to explain the primary features of the Java technology. ¤NIIT  Instructor Inputs 1.9
The JVM Tool Interface is a programming interface that is used to inspect the state and to
control the execution of applications running in the Java virtual machine.
Slide 6
Slide 6 of 31 Session 1 Ver.  1.0
Java Programming Language
The Java Virtual Machine
JVM provides definitions for the:
Instruction set (Central Processing Unit [CPU])
Register set
Class file format
Runtime stack
Garbage-collected heap
Memory area
Fatal error reporting mechanism
High-precision timing support
Slide 7
Slide 7 of 31 Session 1 Ver.  1.0
Java Programming Language
Garbage Collection
Garbage collection has the following characteristics:
Checks for and frees memory no longer needed, automatically.
Provides a system-level thread to track memory allocation.
Use Slides 6 and 7 to explain The Java Virtual Machine and the Garbage Collection
feature of Java. 1.10 Instructor Inputs  ¤NIIT
When the program stops referencing an object, the object is not required any more and
becomes garbage. The space used by the object can be released and used for another
object. Garbage collection frees a programmer from the burden of freeing allocated
memory. The garbage collector determines the objects that are no more referenced in the
program and releases the memory allocated to them.
Slide 8
Slide 8 of 31 Session 1 Ver.  1.0
Java Programming Language
The Java Runtime Environment
The Java application environment performs as follows:
Use Slide 8 to explain the Java runtime environment.
Java is both interpreted and compiled. The code is compiled to a bytecode, that is, binary
and platform independent. When the program needs to be executed, the code is copied
onto the memory and interpreted on the user’s computer. As an interpreted language, Java
has a simple syntax.
When you compile a piece of code, all the errors are listed together. You can execute a
program only when all the errors have been rectified. An interpreter, on the other hand,
verifies the code and executes it line by line. Only when the execution encounters the
statement with an error, the error is reported. This makes it easy for a programmer to
debug the code.
A bytecode is the result of compiling a Java program. You can execute this code on any
platform. In other words, Java programs can be executed on a variety of hardware and
operating systems because of the bytecode compilation process and interpretation by a
browser. ¤NIIT  Instructor Inputs 1.11
Slide 9
Slide 9 of 31 Session 1 Ver.  1.0
Java Programming Language
JVM™ Tasks
The JVM performs three main tasks:
Loads code – Performed by the class loader.
Verifies code – Performed by the bytecode verifier.
Executes code – Performed by the runtime interpreter.
Slide 10
Slide 10 of 31 Session 1 Ver.  1.0
Java Programming Language
The Class Loader
Loads all classes necessary for the execution of a program.
Maintains classes of the local file system in separate
namespaces.
Avoids execution of the program whose bytecode has been
changed illegally.
Use Slides 9 and 10 to explain JVM and the class loader. 1.12 Instructor Inputs  ¤NIIT
Slide 11
Slide 11 of 31 Session 1 Ver.  1.0
Java Programming Language
The Bytecode Verifier
All class files imported across the network pass through the
bytecode verifier, which ensures that:
The code adheres to the JVM specification.
The code does not violate system integrity.
The code causes no operand stack overflows or underflows.
The parameter types for all operational code are correct.
No illegal data conversions (the conversion of integers to
pointers) have occurred.
Slide 12
Slide 12 of 31 Session 1 Ver.  1.0
Java Programming Language
Java Technology Runtime Environment
Use Slides 11 and 12 to explain JRE and the bytecode verifier. ¤NIIT  Instructor Inputs 1.13
Slide 13
Slide 13 of 31 Session 1 Ver.  1.0
Java Programming Language
A simple Java Application
Let see how to create a simple Java Application.
Give a demo to the students to create a simple Java application program.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod01_intro\exercise2\DemoProject.
Slide 14
Slide 14 of 31 Session 1 Ver.  1.0
Java Programming Language
The Analysis and Design Phase
Analysis describes what the system needs to do:
Modeling the real-world, including actors and activities,
objects, and behaviors.
Design describes how the system does it:
Modeling the relationships and interactions between objects
and actors in the system.
Finding useful abstractions to help simplify the problem or
solution.
Use Slide 14 to explain the analysis and design phase. 1.14 Instructor Inputs  ¤NIIT
Slide 15
Slide 15 of 31 Session 1 Ver.  1.0
Java Programming Language
Declaring Java Technology Classes
Basic syntax of a Java class:
<modifier>* class <class_name>
{ <attribute_declaration>*
<constructor_declaration>*
<method_declaration>*
}
Example:
public class MyFirstClass
{ private int age;
public void setAge(int value)
{ age = value;
}
}
Use Slide 15 to explain the basic declaration of a java technology class.
Slide 16
Slide 16 of 31 Session 1 Ver.  1.0
Java Programming Language
Declaring Attributes
Basic syntax of an attribute:
<modifier>* <type> <name> [ =
<initial_value>];
Example:
public class MyFirstClass
{
private int x;
private float y = 10000.0F;
private String name = “NIIT”;
}¤NIIT  Instructor Inputs 1.15
Slide 17
Slide 17 of 31 Session 1 Ver.  1.0
Java Programming Language
Basic syntax of a method:
<modifier>* <return_type> <name> (
<argument>* ){   <statement>*   }
Example:
public class Dog
{ private int weight;
public int getWeight()
{  return weight;
}
public void setWeight(int newWeight)
{  if ( newWeight > 0 )
{ weight = newWeight;
} } }
Declaring Methods
Use Slides 16 and 17 to explain declaration of attributes and methods.
Slide 18
Slide 18 of 31 Session 1 Ver.  1.0
Java Programming Language
Accessing Object Members
To access object members, including attributes and
methods, dot notation is used
The dot notation is: <object>.<member>
Examples:
d.setWeight(42);
d.weight = 42; // only permissible if weight is public1.16 Instructor Inputs  ¤NIIT
Slide 19
Slide 19 of 31 Session 1 Ver.  1.0
Java Programming Language
+getDay()
+getMonth()
+getYear()
+setDay(int) : boolean
+setMonth(int) : boolean
+setYear(int) : boolean
-day : int
-month : int
-year : int
MyDate Class name
Attributes
Methods
Class Representation Using UML
Class representation of MyDate class:
Use Slide 18 to explain the way to access object members.
Explain how UML can be used as a modeling tool. You can use Appendix B of the
courseware to provide inputs for the same.
Slide 20
Slide 20 of 31 Session 1 Ver.  1.0
Java Programming Language
Abstraction
Abstraction means ignoring the non-essential details of an
object and concentrating on its essential details.¤NIIT  Instructor Inputs 1.17
Slide 21
Slide 21 of 31 Session 1 Ver.  1.0
Java Programming Language
Encapsulation
Encapsulation provides data representation flexibility by:
Hiding the implementation details of a class.
Forcing the user to use an interface to access data.
Making the code more maintainable.
Use Slides 20 and 21 to explain encapsulation and abstraction.
Slide 22
Slide 22 of 31 Session 1 Ver.  1.0
Java Programming Language
Declaring Constructors
A constructor is a set of instructions designed to initialize an
instance.
Basic syntax of a constructor:
[<modifier>] <class_name> ( <argument>* )
{ <statement>* }
Example:
public class Dog
{ private int weight;
public Dog()
{  weight = 42;
}
}
A constructor has the same name as that of the class for which it is declared because it is
called automatically when an object is created. A constructor does not have a return type. 1.18 Instructor Inputs  ¤NIIT
Slide 23
Slide 23 of 31 Session 1 Ver.  1.0
Java Programming Language
The Default Constructor
There is always at least one constructor in every class.
If the programmer does not supply any constructor, the
default constructor is present automatically.
The characteristics of default constructor:
The default constructor takes no arguments.
The default constructor body is empty.
The default constructor enables you to create object instances
with new xyz() without having to write a constructor.
Use Slides 22 and 23 to explain constructors, including the default constructor.
Slide 24
Slide 24 of 31 Session 1 Ver.  1.0
Java Programming Language
Source File Layout
Basic syntax of a Java source file:
[<package_declaration>]
<import_declaration>*
<class_declaration>+
For example, the VehicleCapacityReport.java file can be
written as:
package shipping.reports;
import shipping.domain.*;
import java.util.List;
import java.io.*;
public class VehicleCapacityReport
{ private List vehicles;
public void generateReport(Writer output)
{…} }
Use Slide 24 to explain the layout of a Java source file. ¤NIIT  Instructor Inputs 1.19
Slide 25
Slide 25 of 31 Session 1 Ver.  1.0
Java Programming Language
Software Packages
Packages help manage large software systems.
Packages can contain classes and sub-packages.
Slide 26
Slide 26 of 31 Session 1 Ver.  1.0
Java Programming Language
Software Packages (Contd.)
Basic syntax of the import statement:
import
<pkg_name>[.<sub_pkg_name>]*.<class_name>;
or
import <pkg_name>[.<sub_pkg_name>]*.*;
Examples:
import java.util.List;
import java.io.*;
import shipping.gui.reportscreens.*;
The import statement does the following:
Precedes all class declarations
Tells the compiler where to find classes
Use Slides 25 and 26 to explain software packages.
You can give a demo to show to the students how to create a source package in a project.
The path for the datafiles:
TIRM\Data Files For Faculty\demos\ mod02_OOP\exercise4\DemoProject. 1.20 Instructor Inputs  ¤NIIT
You can refer to the Additional Inputs section for more information on packages.
Slide 27
Slide 27 of 31 Session 1 Ver.  1.0
Java Programming Language
Deployment
In order to deploy an application without manipulating the
user’s CLASSPATH environment variable, create an
executable Java Archive (JAR) File.
To deploy library code in a JAR file, copy the JAR file into
the ext subdirectory of the lib directory in the main directory
of the JRE.
Slide 28
Slide 28 of 31 Session 1 Ver.  1.0
Java Programming Language
Using the Java Technology API Documentation
The main sections of a class document include the
following:
The class hierarchy
A description of the class and its general purpose
A list of attributes
A list of constructors
A list of methods
A detailed list of attributes with descriptions
A detailed list of constructors with descriptions and formal
parameter lists
A detailed list of methods with descriptions and formal
parameter lists
Use the Slides 27 and 28 to explain deployment of an application and using Java
technology API documentation. ¤NIIT  Instructor Inputs 1.21
Slide 29
Slide 29 of 31 Session 1 Ver.  1.0
Java Programming Language
Summary
In this session, you learned that:
The key features of Java technology include:
A programming language
A development environment
An application environment
A deployment environment
JVM can be defined as an imaginary machine that is
implemented by emulating it in software on a real machine.
Java source files are compiled, get converted into a bytecode
file. At runtime, the bytecodes are loaded, checked, and run in
an interpreter.
Garbage collector checks for and frees memory no longer
needed, automatically.
Slide 30
Slide 30 of 31 Session 1 Ver.  1.0
Java Programming Language
Summary (Contd.)
The three main tasks performed by the JVM include:
Loads code
Verifies code
Executes code
There are five primary workflows in a software development
project: Requirement capture, Analysis, Design,
Implementation, and Test.
Abstraction means ignoring the non-essential details of an
object and concentrating on its essential details.
Encapsulation provides data representation flexibility by hiding
the implementation details of a class.
The Java technology class can be declared by using the
declaration:
<modifier> * class <class name>
The declaration of a Java object attribute can be done as:
<modifier> * <type> <name>1.22 Instructor Inputs  ¤NIIT
Slide 31
Slide 31 of 31 Session 1 Ver.  1.0
Java Programming Language
Summary (Contd.)
The definition of methods can be done as:
<modifier> * <return type> <name> (<argument>
*)
The dot operator enables you to access non-private attribute
and method members of a class.
A constructor is a set of instructions designed to initialize an
instance of a class.
The Java technology programming language provides the
package statement as a way to group related classes.
The import statement tells the compiler where to find the
classes which are grouped in packages.
The Java technology API consists of a set of HTML files. This
documentation has a hierarchical layout, where the home page
lists all the packages as hyperlinks.
Use Slides 29, 30, and 31 to summarize the session. ¤NIIT  Instructor Inputs 1.23
How to use vi Editor
To create the java file you need to type the file name with vi on command line, for
example:
vi test.java
It will open the vi Editor to write the statements. Use the following key combination to
work in vi editor efficiently:
Esc+i Æ To insert the characters.
Esc+x Æ To delete one character.
Esc+dd Æ To delete the complete line.
Esc+k Æ To navigate above in the editor.
Esc+j Æ To navigate down in the editor.
Esc+l Æ To navigate in right direction in the editor.
Esc+h Æ To navigate in the left direction in the editor.
Esc :q! Æ Quit without saving the file.
Esc :wq Æ Save the file and quit from editor.
Package
A package is a grouping of related types that provides access protection and name space
management. The word types refer to classes, interfaces, enumerations, and annotation
types. Uses of a package:
„ A package provides a unique namespace for the types it contains.
„ A package facilitates access protection.
„ A package can contain the following kinds of types:
z Classes
z Interfaces
z Enumerated types
z Annotations
Additional Inputs 1.24 Instructor Inputs  ¤NIIT
„ Is the Java programming language a complete language or is it useful only for
writing programs for the Web?
Ans: There might be a misconception that the Java programming language is only for
Web programs. Features such as better security make this language ideal for the Web.
However, it is a complete object-oriented programming language useful for mainstream
applications as well.
„ What is Java Runtime Environment?
Ans: A runtime environment is a virtual machine state that provides software services for
processes or programs while a computer is running. It may pertain to the operating system
itself or the software that runs beneath it.
The Java Runtime Environment, or JRE, is a software bundle from Sun Microsystems that
allows a computer system to run a Java application. This bundle includes a Java Virtual
Machine (JVM) and a set of standard class libraries.
„ What makes Java platform independent?
Ans: Java is both compiled and interpreted. The code is compiled to a bytecode that is
binary and platform independent. When the program needs to be executed, the code is
fetched into the memory and interpreted on the user’s computer. Java programs can be
executed on a variety of hardware and operating systems because of bytecode compilation
process and interpretation by a browser. The only requirement is that the system should
have a Java-enabled Internet browser. The Java compiler is written in Java and the
run-time environment, the interpreter, is written in C.
„ What is a default constructor?
Ans: Every class has one constructor. If a constructor is not written, the Java
programming language provides a default constructor. This constructor takes no
arguments and has an empty body. If any constructor declaration is added to a class that
previously had no explicit constructors, the default constructor is lost.
FAQs ¤NIIT  Instructor Inputs 1.25
„ What is the difference between the import statement in Java and the # include
statement in C++?
Ans: In C++, when you write #include <header file>, it adds the header file to the object
file when you compile the source file. On the other hand, in Java, the import statement
makes the bytecode include pointers to the specified packages and classes when you
compile the Java program. 1.26 Instructor Inputs  ¤NIIT

 

 

Solving
Programming
Problems Using
Graphs
Chapter 11
Many programming problems require you to
represent a non-hierarchical relationship between
pairs of items. Such problems can be solved by
using a data structure called graph.
This chapter discusses the concept and
implementation of graphs. In addition, it discusses
the various applications of graphs.
In this chapter, you will learn to:
 Store data in a graph
 Implement a graph
 Apply graphs to solve programming problems
Objectives ¤NIIT Solving Programming Problems Using Graphs 11.3
Consider a situation where you have to visit a set of cities and return back to the original
city in the end. For this, you need to find the shortest or the least expensive route that
starts from the current city, visits each of the desired cities, and then returns back to the
original city.
To solve this kind of a problem, you need to first determine a way of representing the
information pertaining to the various cities and the relationships between the cities. The
relationships between the various cities are essentially pair-wise relationships, where the
distance between the pairs of cities needs to be represented. You can represent these
relationships in the form of a graph. After representing the cities and the distances
between them in the form of a graph, you can use an appropriate algorithm to determine
the shortest or the least expensive path connecting the cities.
A graph is defined as a data structure that consists of a set of vertices (nodes) and edges
(arcs). It is also said to be a collection of data items that are interconnected to form a
network. The following figure depicts a graph.
Sample Graph
An edge is a path between a pair of vertices. If the two edges of a graph share a common
vertex, the edges are said to be adjacent to each other. In the preceding graph, edges (v1,
v2) and (v2, v3) are adjacent because they share a common vertex, v2. Similarly, if two
vertices in a graph share a common edge, the vertices are said to be adjacent to each other.
In the preceding graph, vertices v1 and v2 are adjacent to each other because they share a
common edge (v1, v2).
There are two types of graphs:
„ Directed graph: A graph that has an ordered pair of vertices, (x, y). Here, x is the
tail and y is the head of the edge. This means that there is a path from vertex x to
vertex y. However, a path from y to x may or may not exist. A path from y to x will
be represented by e = (y, x). Therefore, e = (x, y) and e = (y, x) are two separate
edges for a directed graph.
Storing Data in a Graph
Defining Graph 11.4 Solving Programming Problems Using Graphs  ¤NIIT
Note
A path is defined as a sequence of distinct vertices, each adjacent to the next vertex.
The following figure illustrates a directed graph.
Directed Graph
The preceding graph contains five vertices, namely, v1, v2, v3, v4, and v5. The
graph contains four directed edges, namely, (v1, v2), (v2, v3), (v4, v3), (v4, v1), (v4,
v5), and (v5, v1).
„ Undirected graph: A graph that has an unordered pair of vertices representing an
edge. This means that if e = (v, w), then (v, w) and (w, v) are considered as the same
edge.
The following diagram illustrates an undirected graph.
Undirected Graph
There are certain terminologies that are associated with graphs. They are:
„ Cycle: A cycle is defined as a closed path in which the first and the last node is the
same. For example, in a directed graph, a path is called as a cycle if it has one or
more nodes and the start node is connected to the last node to form a closed path.
„ Cyclic graph: A graph that contains a cycle is said to be a cyclic graph.
„ Acyclic graph: A graph with no cycles is said to be an acyclic graph.
„ Degree: The degree of a node in an undirected graph is referred to as the number of
edges connected to that node. However, in a directed graph, there are two types of
degrees for each node. They are, indegree and outdegree.  ¤NIIT Solving Programming Problems Using Graphs 11.5
Just a minute:
„ Indegree: The indegree of a node is the number of edges pointing to that node.
„ Outdegree: The outdegree of a node is the number of edges emanating from that
node.
„ Weighted graph: A weighted graph is a graph in which each edge has a weight
attached to it. This weight represents a value such as cost, distance, or profit
associated with that edge.
„ Complete graph: A graph is said to be a complete graph, if every node in the graph
is adjacent to all the other nodes in the graph.
„ Connected graph: An undirected graph is said to be a connected graph, if there is a
path from one node in the graph to all the other nodes of the graph.
„ Tree: A tree is a connected, acyclic graph.
„ Subgraph: If G and H are two graphs with vertex sets V(G), V(H), and edge sets
E(G), E(H) respectively such that V(H) is a subset of V(G) and E(H) is a subset of
E(G), then H is called a subgraph of G. Also G is called a supergraph of H.
„ Spanning subgraph of a graph: A spanning subgraph of a graph G is a subgraph of
G that contains all the vertices of the graph.
„ Spanning Tree: A spanning tree of a graph G is a spanning subgraph of G that is
also a tree.
„ Successor: In a directed graph, if there is a directed path from node X to node Y,
then Y is the successor of X.
„ Predecessor: In a directed graph, if there is a directed path from node X to node Y,
then X is the predecessor of Y.
A graph in which any node in a graph is adjacent to all the other nodes in the graph is
called a __________.
1. Undirected graph
2. Directed graph
3. Complete graph
4. Cyclic graph
Answer:
3.     Complete graph 11.6 Solving Programming Problems Using Graphs  ¤NIIT
Just a minute:
Consider the given graph.
Identify the type of graph.
Answer:
The given graph is a directed graph. ¤NIIT Solving Programming Problems Using Graphs 11.7
To solve a particular problem by using graphs, you first need to represent the given
information in the form of a graph. Once the information is stored in the form of a graph,
you can perform various operations on the graph to solve the problem.
To implement a graph, you need to first represent the given information in the form of a
graph. You can represent a graph in the computer’s memory in many ways. The two most
commonly used ways of representing a graph are:
„ Adjacency matrix
„ Adjacency list
Adjacency Matrix
An adjacency matrix uses a two-dimensional array to represent a graph. If there are n
vertices in a graph, you need a two-dimensional array of size n × n to represent the graph.
Consider the graph shown in the following figure.
Graph Representation
To represent the graph shown in the preceding figure, you need a 4 × 4 matrix. Each row
in the matrix represents a vertex in the graph. Similarly, each column in the matrix
represents a vertex in the graph.
Suppose,
Row 1 and column 1 correspond to vertex v1
Row 2 and column 2 correspond to vertex v2
Row 3 and column 3 correspond to vertex v3
Row 4 and column 4 correspond to vertex v4
Implementing a Graph
Representing a Graph 11.8 Solving Programming Problems Using Graphs  ¤NIIT
Note
Therefore, vertices v1, v2, v3, and v4 correspond to indexes 0, 1, 2, and 3 of the array
respectively.
Let A be the adjacency matrix for the preceding graph. Now, information pertaining to the
edges is stored in the adjacency matrix in the following manner:
„ A[i, j] = 1, if there is an edge from vertex with index i to vertex with index j
„ A[i, j] = 0, if there is no edge from vertex with index i to vertex with index j
The following diagram depicts the adjacency matrix representation of the preceding
graph.
v1    v2     v3     v4
v1 0     1       0       0
Adjacency Matrix A =   v2 0      0       1       0
v3 0      0       0       0
v4 1      0       1       0
Adjacency Matrix Representation
Representing a graph in an array is simple to implement. However, if there are not many
edges in the graph, it leads to wastage of memory space. For example, while creating a
graph with 100 nodes and 150 edges by using an adjacency matrix, you will end up with
an array of 10,000 elements.
Therefore, 10,000 positions are allocated for storing the details of only 150 edges. In this
case, the adjacency matrix will become a sparse matrix, in which most of the entries
contain the value 0. This leads to a lot of wastage. Therefore, you should implement an
adjacency matrix only if your graph is dense. A graph is said to be dense if there are many
edges in the graph.
A matrix is said to be sparse if most of the entries in the matrix are zeroes.
Adjacency List
An adjacency list uses a linked representation for a graph. In this type of implementation,
you are required to maintain two types of lists. One list keeps track of all the vertices in
the graph and the second list keeps track of the adjacent vertices for every vertex.  ¤NIIT Solving Programming Problems Using Graphs 11.9
Consider the following undirected graph.
Undirected Graph
The adjacency list representation for the preceding graph will be, as shown in the
following figure.
Adjacency List Representation of a Graph
In the preceding representation of the graph, there is one list that contains the details of all
vertices in the graph. Each node in this linked list contains the address of another linked
list that contains the details of all vertices adjacent to that vertex.
When you implement a graph by using an adjacency list, you do not need to specify the
total number of nodes in advance. The nodes in the graph are added as and when required.
Therefore, unlike adjacency matrix, there is no wastage of space. Hence, implementing an
adjacency list is a good choice if the graph is not dense.
However, one disadvantage of using an adjacency list is that extra memory space is
required for storing the variables/pointers. 11.10 Solving Programming Problems Using Graphs  ¤NIIT
To represent an adjacency list, you need to declare two classes. They are as follows:
1. Class Vertex: This class represents a vertex in the graph. It consists of three parts:
vertex name, a variable/pointer pointing to the next vertex, and a variable/pointer
pointing to the first node of the linked list containing adjacent nodes. The following
is the C# and C++ declaration of this class:
// Code in C#
class Vertex
{
string vertexName;
Vertex nextVertex;
AdjacentVertex nextAdjVertex;
}
// Code in C++
class Vertex
{
char vertexName[10];
Vertex *nextVertex;
AdjacentVertes *nextAdjVertex;
};
2. Class AdjacentVertex: This class represents a vertex adjacent to a given vertex in
the graph. If consists of two parts: name of the adjacent vertex and a variable/pointer
pointing to the next adjacent vertex. The following is the C# and C++ declaration of
this class:
// Code in C#
class AdjacentVertex
{
string VertexName;
AdjacentVertex nextAdjVertex;
}
// Code in C++
class AdjacentVertex
{
char VertexName[10];
AdjacentVertex *nextAdjVertex;
};¤NIIT Solving Programming Problems Using Graphs 11.11
Traversing a graph means visiting all the vertices in the graph. In a graph, there is no
special vertex designated as the starting vertex. Therefore traversal of the graph may start
from any vertex.
You can traverse a graph with the help of the following two methods:
„ Depth First Search (DFS)
„ Breadth First Search (BFS)
DFS
In DFS, you begin the traversal by starting from any vertex v as the starting vertex. After
traversing the starting vertex, you then traverse any one of the vertices adjacent to the
starting vertex. Next, you traverse along any one of the vertices adjacent to the last visited
vertex. This process will continue until you reach a vertex for which there are no
unvisited adjacent vertices.
After you reach a node for which there are no unvisited adjacent vertices, you will
backtrack to the last visited vertex that has an unvisited adjacent vertex, and initiate a
DFS from there. This process terminates when no unvisited vertex can be reached from
any of the visited vertices.
Consider the following graph to understand DFS.
Graph to be Traversed
In the given graph, start the traversal from v1. After traversing vertex v1, traverse any one
of its adjacent vertices. The vertices adjacent to v1 are v2 and v4. Traverse one of these
adjacent vertices, say v2. Now, the unvisited vertices adjacent to v2 are v3 and v6. So
now, you may visit v3.
Traversing a Graph 11.12 Solving Programming Problems Using Graphs  ¤NIIT
Next, you need to visit any of the unvisited vertices adjacent to v3. The unvisited vertices
adjacent to v3 are v5 and v6.
Therefore, now you may visit v5. Next, you need to traverse to any one of the unvisited
vertices adjacent to v5. In the given graph, there is no unvisited vertex adjacent to v5.
Therefore, you will backtrack to the last vertex visited that has an unvisited adjacent
vertex and initiate a DFS from there. Here, v3 is the last visited vertex and the only
unvisited vertex adjacent to v3 is v6. Therefore, you will now visit v6.
There is no vertex adjacent to v6; therefore, you need to backtrack to the last visited
vertex, that is, v3. There is no unvisited vertex adjacent to v3; therefore, you need to
backtrack to the vertex visited before v3, that is, v2. However, v2 does not have any
unvisited adjacent vertices.
Therefore, you will again backtrack to the vertex visited before v2, that is, v1. Now, v1
has an unvisited adjacent vertex v4. Therefore, you need to visit v4.
There is no vertex adjacent to v4; therefore, you will have to backtrack to the last visited
vertex, that is, v1. There is no vertex adjacent to v1 that is unvisited. Therefore the DFS
will terminate here. At this stage, all the vertices in the given graph have been visited.
Implementing DFS by Using a Stack
DFS can be easily implemented by using a stack. The following is the algorithm to
implement DFS by using a stack:
Algorithm: DFS(v)
1. Push the starting vertex, v into the stack.
2. Repeat until the stack becomes empty:
a. Pop a vertex from the stack.
b. Visit the popped vertex.
c. Push all the unvisited vertices adjacent to the popped vertex into the stack.  ¤NIIT Solving Programming Problems Using Graphs 11.13
Consider the following graph.
Graph to be Traversed
Suppose the starting vertex is v1. The following table depicts the DFS traversal of the
preceding graph by using a stack.
Steps Action Stack Representation Vertices Visited
1 Push the starting vertex v1
into the stack.
2 Pop the top element v1 from
the stack, visit it, and push
all vertices adjacent to v1 in
the stack.
v1
3 Pop the top element v2 from
the stack, visit it, and push
all its unvisited adjacent
vertices in the stack.
v1, v2
4 Pop the top element v3 from
the stack, visit it, and push
all its unvisited adjacent
vertices in the stack.
v1, v2, v3 11.14 Solving Programming Problems Using Graphs  ¤NIIT
Steps Action Stack Representation Vertices Visited
5 Pop the top element v5 from
the stack, visit it, and push
all its unvisited adjacent
vertices in the stack.
Vertex v5 does not have any
unvisited adjacent vertex;
therefore no vertex will be
pushed into the stack.
v1, v2, v3, v5
6 Pop the top element v6 from
the stack, visit it, and push
all its unvisited adjacent
vertices in the stack.
Vertex v6 does not have any
adjacent vertex; therefore
no vertex will be pushed into
the stack.
v1, v2, v3, v5,
v6
7 Pop the top element v4 from
the stack, traverse it, and
push all its unvisited
adjacent vertices in the
stack.
Vertex v4 does not have any
unvisited adjacent vertices.
Therefore no vertex will be
pushed into the stack.
The stack is now empty.
Therefore, the traversal is
complete.
v1, v2, v3, v5,
v6, v4
Implementing DFS by Using a Stack
Although the preceding algorithm provides a simple and convenient method to traverse a
graph, the algorithm will not work correctly if the graph is not connected.
In such a case, you will not be able to traverse all the vertices from one single starting
vertex. To solve this problem, you need to execute the preceding algorithm repeatedly for
all unvisited vertices in the graph. You can do this by executing the following algorithm:
1. Repeat step 2 for each vertex, v in the graph
2. If v is not visited:
a. Call DFS(v) ¤NIIT Solving Programming Problems Using Graphs 11.15
BFS
In BFS, you begin by visiting the starting vertex v1. After traversing the starting vertex,
you then visit the vertices adjacent to the starting vertex.
Consider the following graph.
Graph to be Traversed
In the preceding graph, start the traversal from the first vertex v1. After visiting vertex v1,
you need to visit all the vertices adjacent to v1. The vertices adjacent to v1 are v2 and v4.
Therefore, you visit the vertices v2 and v4 in any order. Suppose you visit vertex v2
before visiting vertex v4.
Now, you need to traverse all the unvisited vertices adjacent to v2 and then the unvisited
vertices adjacent to v4. The unvisited vertices adjacent to vertex v2 are v3 and v6.
Therefore, you visit the vertices v3 and v6. The only unvisited vertex adjacent to v4 is v5.
Therefore, you visit vertex v5.
Next, you need to traverse the vertices adjacent to vertices v3, v6, and v5. There are no
unvisited vertices adjacent to v3, v6, and v5. Therefore, you do not need to traverse them
again. Now all the vertices have been traversed.
Implementing BFS by Using a Queue
BFS can be easily implemented by using a queue. The following is the algorithm to
implement BFS by using a queue:
1. Visit the starting vertex, v and insert it into the queue.
2. Repeat step 3 until the queue becomes empty.
3. Delete the front vertex from the queue, visit all its unvisited adjacent vertices, and
insert them into the queue.  11.16 Solving Programming Problems Using Graphs  ¤NIIT
Consider the following graph.
Graph to be Traversed
The following table depicts the BFS process by using a queue.
Steps Action Queue Representation  Vertices
Visited
1 Visit the starting vertex v1
and insert it into the queue.
v1
2 Delete the front element, v1
from the queue, visit all its
adjacent vertices, and insert
them into the queue.
v1, v2, v4
3 Delete the front element v2
from the queue, visit all its
adjacent vertices, and insert
them into the queue.
v1, v2, v4, v3,
v6
4 Delete the front element v4
from the queue, visit all its
unvisited adjacent vertices,
and insert them into the
queue.
v1, v2, v4, v3,
v6, v5
5 Delete the front element v3
from the queue. v3 does not
have any unvisited adjacent
vertices. Therefore, no
vertices are visited or
inserted into the queue.
v1, v2, v4, v3,
v6, v5 ¤NIIT Solving Programming Problems Using Graphs 11.17
Steps Action Queue Representation  Vertices
Visited
6 Delete the front element v6
from the queue. v6 does not
have any unvisited adjacent
vertices. Therefore, no
vertices are visited or
inserted into the queue.
v1, v2, v4, v3,
v6, v5
7 Delete the front element v5
from the queue. v5 does not
have any unvisited adjacent
vertices. Therefore, no
vertices are visited or
inserted into the queue.
The queue is now empty.
Therefore, the traversal is
complete.
v1, v2, v4, v3,
v6, v5
Implementing BFS by Using a Queue
Although the preceding algorithm provides a simple and convenient method to traverse a
graph, the algorithm will not work correctly if the graph is not connected.
In such a case, you will not be able to traverse all the vertices from one single starting
vertex. To solve this problem, you need to execute this algorithm repeatedly for all
unvisited vertices in the graph. You can do this by executing the following algorithm:
1. Visit the starting vertex v and insert it into a queue.
2. Repeat step 3 until the queue becomes empty.
3.  Delete the front element from the queue, visit all its unvisited adjacent vertices, and
insert them into the queue. 11.18 Solving Programming Problems Using Graphs  ¤NIIT
Problem Statement
You have to represent a set of cities and the distances between them in the form of a
graph. Write a program to represent the graph in the form of an adjacency matrix.
Solution
The following is the C# and C++ code to represent a set of cities and the distances
between them in the form of an adjacency matrix:
// Code in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace GraphsUsingAdjMatrixInCSharp
{
class Graph
{
private string[] vertices = new string[10];
private int[,] cost = new int[10, 10]; /* Adjacency matrix
containing costs of edges. */
private int n; // n is the number of vertices
public Graph()
{
n = 0;
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
cost[i, j] = 0;
}
}
private bool edgeExists()
{
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
if (cost[i, j] != 0)
return (true);
Activity: Implementing a Graph by Using Adjacency
Matrix Representation ¤NIIT Solving Programming Problems Using Graphs 11.19
return (false);

}
public void addVertex()
{
string vname;
Console.Write(“\nEnter vertex name: “);
vname = Console.ReadLine();
int i = getIndex(vname);
if (i != -1)
{
Console.WriteLine(“\nVertex already exists.”);
return;
}
vertices[n] = vname;
n++;
}
private int getIndex(String vname)
{
for (int i = 0; i < n; i++)
if (vertices[i] == vname)
return (i);
return (-1); /* If the vertex is not found in the list,
-1 is returned.*/
}
public void addEdge()
{
string v1, v2;
int i1, i2;
if (n == 0)
{
Console.WriteLine(“\nNo vertex exists. You must first
add a vertex.”);
return;
}
while (true)
{
Console.Write(“\nEnter the source vertex: “);
v1 = Console.ReadLine();
i1 = getIndex(v1);
if (i1 == -1) 11.20 Solving Programming Problems Using Graphs  ¤NIIT
Console.WriteLine(“\nSource vertex does not
exist. Try again.”);
else
break;
}
while (true)
{
Console.Write(“\nEnter the destination vertex: “);
v2 = Console.ReadLine();
i2 = getIndex(v2);
if (i2 == -1)
Console.WriteLine(“\nDestination vertex does not
exist. Try again.”);
else
break;
}
Console.Write(“\nEnter the cost of the edge: “);
cost[i1, i2] = Convert.ToInt32(Console.ReadLine());
}
public void display()
{
if (n == 0)
{
Console.WriteLine(“\nGraph does not exists.”);
return;
}
Console.WriteLine(“\nVertices:”);
for (int i = 0; i < n; i++)
Console.WriteLine(vertices[i]);
if (edgeExists())
{
Console.WriteLine(“\nEdges:”);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (cost[i, j] != 0)
Console.WriteLine(vertices[i] + “->” +
vertices[j] + ”  –   ” + cost[i, j]);
}
}
}
¤NIIT Solving Programming Problems Using Graphs 11.21
class Graph_Program
{
static void Main(string[] args)
{
Graph g = new Graph();
char ch;
do
{
Console.WriteLine();
Console.WriteLine(“Menu”);
Console.WriteLine(“1. Add a vertex”);
Console.WriteLine(“2. Add an edge”);
Console.WriteLine(“3. Display”);
Console.WriteLine(“4. Exit”);
Console.WriteLine();
Console.Write(“Enter your choice: “);
ch = Convert.ToChar(Console.ReadLine());
switch (ch)
{
case ‘1’: g.addVertex(); break;
case ‘2’: g.addEdge(); break;
case ‘3’: g.display(); break;
case ‘4’: break;
default: Console.WriteLine(“Invalid choice.”);
break;
}
} while (ch != ‘4’);
}
}
}
// Code in C++
#include <iostream.h>
#include <string.h>
class Graph
{
private:
char vertices [10][15]; /* This array will store the
names of vertices. */
int cost[10][10]; /* Adjacency matrix containing the cost
of edges. */
int n; // n is the number of vertices 11.22 Solving Programming Problems Using Graphs  ¤NIIT
public:
Graph()
{
n = 0;
for (int i=0; i<10; i++)
for (int j=0; j<10; j++)
cost[i][j] = 0; /* 0 indicates that there
is no edge from vertex i to vertex j. */
}
int edgeExists()
{
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
if (cost[i][j] != 0)
return (1);
return (0);

}
int getIndex(char *vname)
{
for (int i = 0; i < n; i++)
if (strcmp(vertices[i],vname) == 0)
return (i);
return (-1); /* If the vertex is not found in the
list, -1 is returned.*/
}
void addVertex()
{
char vname[15]; /* This array will store the name
of the vertex to be added. */
cout << “\nEnter vertex name: “;
cin >> vname;
int i = getIndex(vname);
if (i != -1)
{
cout << endl << “Vertex already exists.” <<
endl;
return;
}
strcpy(vertices[n],vname);
n++;
} ¤NIIT Solving Programming Problems Using Graphs 11.23
void addEdge()
{
char v1[15], v2[15];
int i1, i2;
if (n==0)
{
cout << “\nNo vertex exists. You must first
add a vertex.\n”;
return;
}
while (1)
{
cout << “\nEnter the source vertex: “;
cin >> v1;
i1 = getIndex(v1);
if (i1 == -1)
cout << endl << “Source vertex does not
exist. Try again.” << endl;
else
break;
}
while (1)
{
cout << “\nEnter the destination vertex: “;
cin >> v2;
i2 = getIndex(v2);
if (i2 == -1)
cout << endl << “Destination vertex
does not exist. Try again.” << endl;
else
break;
}
cout << “\nEnter the cost of the edge: “;
cin >> cost[i1][i2];
}
void display()
{
if (n==0)
{
cout << “\nGraph does not exist.\n”;
return;
} 11.24 Solving Programming Problems Using Graphs  ¤NIIT
cout << endl << “Vertices:” << endl;
for (int i = 0; i < n; i++)
cout << vertices[i] << endl;
if (edgeExists())
{
cout << endl << “Edges:” << endl;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (cost[i][j] != 0)
cout << vertices[i] <<
“->” << vertices[j] <<
”  –   ” << cost[i][j] <<
endl;
}
}
};
void main()
{
Graph g;
char ch;
do
{
cout<<endl<<“Menu”<<endl;
cout<< “1. Add a vertex” << endl;
cout<< “2. Add an edge” << endl;
cout<< “3. Display” << endl;
cout<< “4. Exit” << endl;

cout << “Enter your choice: “;
cin >> ch;
switch (ch)
{
case ‘1’: g.addVertex(); break;
case ‘2’: g.addEdge(); break;
case ‘3’: g.display(); break;
case ‘4’: break;
default: cout << “Invalid choice.”;
}
} while (ch != ‘4’);
}¤NIIT Solving Programming Problems Using Graphs 11.25
A graph is a powerful tool for creating mathematical models of a wide variety of
situations. The graph theory has been instrumental in analyzing and solving problems in
areas as diverse as computer network design, urban planning, finding shortest paths, and
molecular biology. It is also used in game programming.
Many problems can be easily solved by reducing them in the form of a graph. For
example, in transport management system, graphs are frequently used to model situations
involving routes. In this situation, the vertices in the graph represent cities and the edges
represent the roads or some other links.
Once the cities and the links between them are represented in the form of a graph, you can
use the graph to solve various problems such as:
„ Solving the shortest path problem
„ Determining the shortest route connecting a set of cities
A common problem that is frequently solved with the help of graphs is the shortest path
problem. The shortest path problem is used in many situations where you need to know
the shortest path from one vertex to another.
In our day-to-day activity, we come across various situations where we need to find the
shortest distance between two points. For example, a person might want to know the
shortest route to reach a particular location.
Similarly, it is desirable to have shortest route while implementing general electric supply
system and water distribution system between any two points. To solve such problems,
you can use a graph.
Graphs can also be implemented in a networking environment to determine the best
possible route for a data packet to travel. One of the major concerns in routing the data
packets in a network is to determine the shortest path between the source and destination.
In such a scenario, the entire network can be considered as an interconnected set of
vertices, in which each vertex represents different locations in the network, and an edge
represents the link among the locations. Therefore, by looking at the graph, you can easily
determine the best possible route for a data packet.
A graph can also be used to represent a map of railway routes. The graph for the railway
routes will be created in such a manner that the vertices in the graph would represent the
stations and the edges would represent the tracks.
Applications of Graphs
Solving the Shortest Path Problem 11.26 Solving Programming Problems Using Graphs  ¤NIIT
For example, the electric supply system and the water supply system use the shortest path
algorithm for its functionality.
Consider another example of a railway track system. If you want to travel from one
station to another, you will want to cover the distance in the shortest time. For this, you
can use the shortest path algorithm to find the shortest distance between the stations. In
this case, a station would represent the node and tracks would represent the edges.
You have seen that in graph traversals, you traverse through the edges. These edges might
have certain weights attached to them. These weights can represent distance, time, cost or
some other quantity. Therefore, the shortest path problem would enable you to find the
vertices in the graph such that the sum of the weights of its constituent edges in the path is
the minimum. Now, you need to determine the shortest path between any two vertices.
Consider the following weighted graph.
Weighted Graph
Suppose you have to find the shortest path from vertex v1 to vertex v6. There are many
paths from vertex v1 to vertex v6:
„ v1ĺv4ĺv3ĺv6: Distance = 8 (3 + 2 + 3)
„ v1ĺv2ĺv6: Distance = 11 (5 + 6)
„ v1ĺv2ĺv3ĺv6: Distance = 12 (5 + 4 + 3)
Therefore, the shortest path from vertex v1 to vertex v6 is v1ĺv4ĺv3ĺv6, which has a
total distance of 8.
Now, you may also need to find the shortest path from a starting vertex to all the
remaining vertices in the graph. Dijkstra’s algorithm enables you to find the shortest
routes between a given starting vertex and all the other vertices in the graph. This
algorithm is based on the assumption that weights on the edges are non negative.  ¤NIIT Solving Programming Problems Using Graphs 11.27
Let v1 be the starting vertex, from which the shortest distance to all other nodes needs to
be determined. Dijkstra’s algorithm uses an array FINAL to hold the list of those vertices
whose shortest distance from v1 has been determined. Initially, FINAL contains only the
starting vertex v1. At each step, a remaining vertex for which the shortest path from the
starting vertex has been determined is added to FINAL.
In addition to the array FINAL, another array DISTANCE, is required that stores for each
vertex v, the distance from v1 to v. The distance may be direct or via other vertices, that is
if vertices v1, v2, v3, v4, v5, and v6 are given indices 0, 1, 2, 3, 4, and 5 respectively, then
DISTANCE[v] gives the distance from vertex v1 to a vertex with index v. This distance
may or may not be the shortest distance from v1 to v. This will depend on whether or not
v is in FINAL.
If v is in FINAL, it indicates that the shortest distance from v1 to v has been determined
and can be obtained in DISTANCE[v]. On the other hand, if v is not in FINAL,
DISTANCE[v] gives the distance of a path from v1 to v but may not be the shortest path
from v1 to v.
The array DISTANCE is initialized by setting DISTANCE[v] to the weight of the edge
from v1 to v if it exists and to infinity (f) if it does not exist.
For the graph shown in the preceding figure, the arrays DISTANCE and FINAL would be
initialized as:
DISTANCE = {0, 5, f, 3, f, f}
FINAL = {v1}
Now, you will use the Dijkstra’s algorithm to determine the shortest distance from vertex
v1 to all the other vertices. The steps in the Dijkstra’s algorithm are:
1. Choose vertex v corresponding to the smallest distance recorded in the DISTANCE
array such that v is not already in FINAL.
2. Add v to FINAL.
3. Repeat for each vertex w in the graph that is not in FINAL:
a. If the path from v1 to w via v is shorter than the previously recorded distance
from v1 to w (If ((DISTANCE[v] + weight of edge(v,w)) < DISTANCE[w])):
i. Set DISTANCE[w] = DISTANCE[v] + weight of edge(v,w).
4. If FINAL does not contain all the vertices, go to step 1. 11.28 Solving Programming Problems Using Graphs  ¤NIIT
Now, you may use the preceding algorithm to find the shortest routes from the starting
vertex v1 to all other vertices in the following graph.
Graph Depicting Distances Between a Set of Vertices
Initially,
DISTANCE = {0, 5, f, 3, f, f}
FINAL = {v1}
The process of determining the shortest path from v1 to all other nodes is shown in the
following table.
Step Action Status
Choose vertex v with the smallest
distance recorded in the
DISTANCE array such that v is
not already in FINAL.
Add v to FINAL.
The vertex with the smallest distance
in the DISTANCE array is vertex v1
(with distance 0). However, vertex v1
is already there in the FINAL array.
Therefore, you select the vertex
corresponding to the next smallest
distance, that is, the vertex v4 (with
distance 3). Then you add vertex v4 to
FINAL.
DISTANCE = {0,
5, f, 3, f, f}
FINAL = {v1, v4} ¤NIIT Solving Programming Problems Using Graphs 11.29
Step Action Status
For all vertices w in the graph
that are not in FINAL, if the path
from v1 to w via v is shorter than
the previously recorded distance
from v1 to w set DISTANCE[w]
= DISTANCE[v] + weight of
edge(v, w).
Here, v = v4 and DISTANCE[v] = 3
Now, consider all vertices w not in
FINAL:
„ w = v2: The distance of the path
from v1 to v2 via v4 is 3+f = f.
Therefore, the distance of path
from v1 to v2 via v4 is infinity,
which is greater than the already
recorded distance from v1 to v2
(5). Therefore, the entry
corresponding to v2 in the
DISTANCE array remains
unchanged.
„ w = v3: The distance of the path
from v1 to v3 via v4 is 3 + 2 = 5,
which is smaller than the already
recorded distance from v1 to v3
(f). Therefore, the entry
corresponding to v3 in the
DISTANCE array is changed to 5.
„ w = v5: The distance of the path
from v1 to v5 via v4 is 3 + 6 = 9,
which is smaller than the already
recorded distance from v1 to v5
(f). Therefore, the entry
corresponding to v5 in the
DISTANCE array is changed to 9.
„ w = v6: The distance of the path
from v1 to v6 via v4 is 3 + f = f,
which is same as the already
recorded distance from v1 to v6
(f). Therefore, the entry
corresponding to v6 in the
DISTANCE array remains
unchanged.
FINAL does not contain all the edges
yet. Therefore, the process will
continue.
DISTANCE = {0,
5, 5, 3, 9, f}
FINAL = {v1, v4} 11.30 Solving Programming Problems Using Graphs  ¤NIIT
Step Action Status
Choose vertex v with the smallest
distance recorded in the
DISTANCE array, such that v is
not already in FINAL.
Add v to FINAL.
The vertex v with the smallest distance
in the DISTANCE array (where v is
not in FINAL) is vertex v2. Therefore,
you select vertex v2, and add it to
FINAL.
DISTANCE = {0,
5, 5, 3, 9, f}
FINAL = {v1, v4,
v2}
For all vertices w in the graph
that are not in FINAL, if the path
from v1 to w via v is shorter than
the previously recorded distance
from v1 to w set DISTANCE[w]
= DISTANCE[v] + weight of
edge(v, w).
Here, v = v2 and DISTANCE[v] = 5
Now, consider all vertices w not in
FINAL:
„ w = v3: The distance of the path
from v1 to v3 via v2 is 5 + 4 = 9,
which is greater than the already
recorded distance from v1 to v3
(5). Therefore, the entry
corresponding to v3 in the
DISTANCE array remains
unchanged.
„ w = v5: The distance of the path
from v1 to v5 via v2 is 5 + f  =
f, which is greater than the
already recorded distance from v1
to v5 (9). Therefore, the entry
corresponding to v5 in the
DISTANCE array remains
unchanged.
„ w = v6: The distance of the path
from v1 to v6 via v2 is 5 + 6 = 9,
which is smaller than the already
recorded distance from v1 to v6
(f). Therefore, the entry
corresponding to v6 in the
DISTANCE array is changed to 9.
DISTANCE = {0,
5, 5, 3, 9, 9}
FINAL = {v1, v4,
v2}
Choose vertex v with the smallest
distance recorded in the
DISTANCE array, such that v is
not already in FINAL.
Add v to FINAL.
The vertex, v with smallest distance in
the DISTANCE array (where v is not
in FINAL) is vertex v3. Therefore, you
select vertex v3 and add it to FINAL.
DISTANCE = {0,
5, 5, 3, 9, 9}
FINAL = {v1, v4,
v2, v3} ¤NIIT Solving Programming Problems Using Graphs 11.31
Step Action Status
For all vertices w in the graph
that are not in FINAL, if the path
from v1 to w via v is shorter than
the previously recorded distance
from v1 to w set DISTANCE[w]
= DISTANCE[v] + weight of
edge(v, w).
Here, v = v3 and DISTANCE[v] = 5
Now, consider all vertices w not in
FINAL:
„ w = v5: The distance of the path
from v1 to v5 via v3 is 5 + 3 = 8,
which is smaller than the already
recorded distance from v1 to v5
(9). Therefore, the entry
corresponding to v5 in the
DISTANCE array is changed to 8.
„ w = v6: The distance of the path
from v1 to v6 via v3 is 5 + 3 = 8,
which is smaller than the already
recorded distance from v1 to v6
(9). Therefore, the entry
corresponding to v6 in the
DISTANCE array is changed to 8.
DISTANCE = {0,
5, 5, 3, 8, 8}
FINAL = {v1, v4,
v2, v3}
Choose vertex v with the smallest
distance recorded in the
DISTANCE array, such that v is
not already in FINAL.
Add v to FINAL.
The vertex v with the smallest distance
in the DISTANCE array (where v is
not in FINAL) is vertex v5. Therefore,
you select vertex v5, and add it to
FINAL.
DISTANCE = {0,
5, 5, 3, 8, 8}
FINAL = {v1, v4,
v2, v3, v5}
For all vertices w in the graph
that are not in FINAL, if the path
from v1 to w via v is shorter than
the previously recorded distance
from v1 to w set DISTANCE[w]
= DISTANCE[v] + weight of
edge(v, w).
Here, v = v5 and DISTANCE[v] = 8
Now, consider all vertices, w not in
FINAL:
„ w = v6: The distance of the path
from v1 to v6 via v5 is 8 + f = f,
which is greater than the already
recorded distance from v1 to v6
(9). Therefore, the entry
corresponding to v6 in the
DISTANCE array remains
unchanged.
DISTANCE = {0,
5, 5, 3, 8, 8}
FINAL = {v1, v4,
v2, v3, v5} 11.32 Solving Programming Problems Using Graphs  ¤NIIT
Step Action Status
Choose vertex v with smallest
distance recorded in the
DISTANCE array, such that v is
not already in FINAL.
Add v to FINAL.
The vertex, v with smallest distance in
the DISTANCE array (where v is not
in FINAL) is vertex v6. Therefore, you
select vertex v6 and add it to FINAL.
All the vertices are now in the FINAL
array. Therefore, at this stage, the
shortest path of all vertices from the
starting vertex, v1 can be found in the
DISTANCE array.
DISTANCE = {0,
5, 5, 3, 8, 8}
FINAL = {v1, v4,
v2,  v3, v5, v6}
Determining the Shortest Distance from Vertex v1 to All Other Vertices
Suppose you are given a set of four cities. You need to device a route connecting the four
cities in such a way so that there are no cycles in the route, and the total distance of the
route is the minimum.
To solve this problem, you need to represent the cities and the distances between the pairs
of cities in the form of vertices and edges in a graph. The shortest path can then be
determined by finding the minimal spanning tree of the graph.
Spanning tree of a connected undirected graph G refers to a spanning subgraph of G,
which connects all the nodes together in such a way that there are no cycles. A spanning
tree with n vertices has exactly n – 1 edges.
Given a graph, you can construct many spanning trees out of it. Then you can select an
appropriate spanning tree, depending upon your requirement.
Consider the following connected graph.
Connected Graph
Determining the Shortest Route Connecting a Set of Cities ¤NIIT Solving Programming Problems Using Graphs 11.33
You can construct different spanning trees of the given graph. The following table depicts
the various spanning trees that you can construct for the preceding graph.
Spanning Tree 1 Spanning Tree 2 Spanning Tree 3 Spanning Tree 4
Spanning Trees
The minimal spanning tree is a spanning tree in which the sum of the weights (cost) of the
connecting edges is the minimum.
The most commonly used algorithms to determine the minimal spanning trees of a graph
are:
„ Prim’s algorithm
„ Kruskal’s algorithm
Prim’s Algorithm
In Prim’s algorithm, the minimal spanning tree is built one vertex at a time. You start with
any vertex and add it to the tree. Then, you need to select an edge with the minimum cost
that is adjacent to a vertex in the tree such that the graph induced after adding the edge is
acyclic.  11.34 Solving Programming Problems Using Graphs  ¤NIIT
This process continues until all the vertices are included in the tree. To understand the
implementation of Prim’s algorithm, consider the following graph.
Graph
To calculate the minimum cost of the given graph, you will start with the starting vertex
v1 and include it in the spanning tree, as shown in the following figure.
Starting Vertex
Now, you need to select an edge with the minimum weight that is adjacent to the starting
vertex. In the given graph, the edge with the minimum weight, adjacent to vertex v1 is
(v1, v2). Therefore, you will add the edge (v1, v2) to the spanning tree, as shown in the
following figure.
First Edge Added ¤NIIT Solving Programming Problems Using Graphs 11.35
Next, you need to add an edge with the minimum weight that is adjacent to the vertices
already in the tree. Therefore, you will add the edge (v1, v8) with weight 3 to the tree, as
shown in the following figure.
Second Edge Added
Now, you will add an edge (v8, v7) with weight 4 to the tree, as shown in the following
figure.
Third Edge Added
You will now add an edge (v2, v3) with weight 5 to the tree, as shown in the following
figure.
Fourth Edge Added 11.36 Solving Programming Problems Using Graphs  ¤NIIT
Next, you will add the edge (v7, v6) with weight 6 to the tree, as shown in the following
figure.
Fifth Edge Added
The edge with the next least weight adjacent to the vertices already included in the graph
is (v2, v8) with weight 7. However, this edge will make the graph cyclic. Therefore, it
cannot be included in the graph.
Now, you will add an edge (v6, v5) with weight 8 to the tree, as shown in the following
figure.
Sixth Edge Added ¤NIIT Solving Programming Problems Using Graphs 11.37
You will now add an edge (v3, v4) with weight 9 to the tree, as shown in the following
figure.
Seventh Edge Added
At this stage n – 1 edges have been included in the tree. This means that the minimal
spanning tree has been built. The cost of the minimal spanning tree is 2 + 3 + 4 + 5 + 6 +
8 + 9 = 37.
Kruskal’s Algorithm
In Kruskal’s algorithm, the minimum cost spanning tree is built one edge at a time. You
select the edges in an increasing order of their cost. The selected edge is added to the
spanning tree, if it does not form a cycle with the edges already in the tree. If the graph
has n vertices, the process of adding the edges will stop after n – 1 edges have been added
to the tree. 11.38 Solving Programming Problems Using Graphs  ¤NIIT
Consider the following graph.
Graph
You have to build a minimal spanning tree of the preceding graph by using the Kruskal’s
algorithm. Initially, there are no edges in the tree, as shown in the following figure.
Graph with No Edges ¤NIIT Solving Programming Problems Using Graphs 11.39
Now, you need to add the edges in the spanning tree, in an increasing order of their
weights. In the given graph, edge (v1, v2) has the minimum weight, 2. Therefore, you
need to first add this edge to the spanning tree, as shown in the following figure.
First Edge Added to the Spanning Tree
The next edge with the minimum weight is (v1, v8) with weight 3. Because this edge does
not form a cycle with the edges already included in the tree, you can include it in the tree,
as shown in the following figure.
Second Edge Added to the Spanning Tree 11.40 Solving Programming Problems Using Graphs  ¤NIIT
The next edge with the minimum weight is (v8, v7) with weight 4. Because this edge does
not form a cycle with the edges already included in the tree, you can include it in the tree,
as shown in the following figure.
Third Edge Added to the Spanning Tree
The next edge with the minimum weight is (v2, v3) with weight 5. Because this edge does
not form a cycle with the edges already included in the tree, you can include it in the tree,
as shown in the following figure.
Fourth Edge Added to the Spanning Tree ¤NIIT Solving Programming Problems Using Graphs 11.41
The next edge with the minimum weight is (v7, v6) with weight 6. Because this edge does
not form a cycle with the edges already included in the tree, you can include it in the tree,
as shown in the following figure.
Fifth Edge Added to the Spanning Tree
The next edge with minimum weight is (v2, v8) with weight 7. However, this edge makes
a cycle with the edges already included in the tree. Therefore, you can discard this edge.
The next edge with minimum weight is (v6, v5) with weight 8. Because this edge does not
form a cycle with the edges already included in the tree, you can include it in the tree, as
shown in the following figure.
Sixth Edge Added to the Spanning Tree 11.42 Solving Programming Problems Using Graphs  ¤NIIT
The next edge with minimum weight is (v3, v4) with weight 9. Because this edge does not
form a cycle with the edges already included in the tree, you can include it in the tree, as
shown in the following figure.
Seventh Edge Added to the Spanning Tree
At this stage, n – 1 edges have been included in the tree. This means that the minimal
spanning tree has been built. The cost of the minimal spanning tree is 2 + 3 + 4 + 5 + 6 +
8 + 9 = 37.  ¤NIIT Solving Programming Problems Using Graphs 11.43
Problem Statement
In the previous activity, you created a program to represent a set of cities and the
distances between them in the form of a graph. Extend the program to include the
functionality for finding the shortest path from a given city to all the other cities.
Solution
The following is the C# and C++ code to find the shortest path from a given city to all the
other cities in the graph:
// Code in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace GraphsUsingAdjMatrixInCSharp
{
class Graph
{
private string[] vertices = new string[10];
private int[,] cost = new int[10, 10]; /* Adjacency matrix
containing costs of edges. */
private int n; // n is the number of vertices;
int infinity = 9999999; /* Assign a very large value to
infinity. */
public Graph()
{
n = 0;
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
if (i == j)
cost[i, j] = 0;
else
cost[i, j] = infinity; /* Infinity indicates
that there is no edge from vertex i to vertex j
*/
}
Activity: Solving the Shortest Path Problem 11.44 Solving Programming Problems Using Graphs  ¤NIIT
}
private bool edgeExists()
{
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
if ((cost[i,j] != 0) && (cost[i,j] != infinity ))
return (true);
return (false);
}
public void addVertex()
{
string vname;
Console.Write(“\nEnter vertex name: “);
vname = Console.ReadLine();
int i = getIndex(vname);
if (i != -1)
{
Console.WriteLine(“\nVertex already exists.”);
return;
}
vertices[n] = vname;
n++;
}
private int getIndex(String vname)
{
for (int i = 0; i < n; i++)
if (vertices[i] == vname)
return (i);
return (-1); /* If the vertex is not found in the list,
-1 is returned.*/
}
public void addEdge()
{
string v1, v2;
int i1, i2;
if (n == 0)
{
Console.WriteLine(“\nNo vertex exists. You must first
add a vertex.”);
return; ¤NIIT Solving Programming Problems Using Graphs 11.45
}
while (true)
{
Console.Write(“\nEnter the source vertex: “);
v1 = Console.ReadLine();
i1 = getIndex(v1);
if (i1 == -1)
Console.WriteLine(“\nSource vertex does not
exist. Try again.”);
else
break;
}
while (true)
{
Console.Write(“\nEnter the destination vertex: “);
v2 = Console.ReadLine();
i2 = getIndex(v2);
if (i2 == -1)
Console.WriteLine(“\nDestination vertex does not
exist. Try again.”);
else
break;
}
Console.Write(“\nEnter the cost of the edge: “);
cost[i1, i2] = Convert.ToInt32(Console.ReadLine());
}
public void display()
{
if (n == 0)
{
Console.WriteLine(“\nGraph does not exists.”);
return;
}
Console.WriteLine(“\nVertices:”);
for (int i = 0; i < n; i++)
Console.WriteLine(vertices[i]);
if (edgeExists())
{
Console.WriteLine(“\nEdges:”);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if ((cost[i, j] != 0) && (cost[i, j] !=
infinity)) 11.46 Solving Programming Problems Using Graphs  ¤NIIT
Console.WriteLine(vertices[i] + “->” +
vertices[j] + ”  –   ” + cost[i, j]);
}
}
public void findShortestPath()
{
int[] Distance = new int[10];
bool[] Final = new bool[10];
string source;
int src;
if (n == 0)
{
Console.WriteLine(“\nGraph does not exist. You must
first insert some vertices and edges.”);
return;
}
while (true)
{
Console.WriteLine(“\nEnter source vertex: “);
source = Console.ReadLine();
src = getIndex(source);
if (src == -1)
Console.WriteLine(“\nSource vertex does not
exist.”);
else
break;
}
/* Initialize Distance Array */
for (int i = 0; i < n; i++)
Distance[i] = cost[src, i];
Final[src] = true;
for (int i = 1; i < n; i++) //n-1 passes
{
/* Find the smallest value in Distance array such
that the vertex with the smallest Distance value
has not been included in the Final array */
int v = 0; ¤NIIT Solving Programming Problems Using Graphs 11.47
/* Find a vertex that is not there in Final. Store
its index in v */
for (int j = 0; j < n; j++)
{
if (Final[j] == false)
{
v = j;
break;
}
}
/* Find the vertex with smallest distance in Distance
array */
for (int j = 0; j < n; j++)
{
if ((Final[j] == false) && (Distance[j] <
Distance[v]))
v = j;
}
Final[v] = true;
/* Compute the distance of all nodes via node with
index min */
for (int w = 0; w < n; w++)
{
if (Final[w] == false)
{
if (Distance[v] + cost[v, w] < Distance[w])
Distance[w] = Distance[v] + cost[v, w];
}
}
}
Console.WriteLine(“\nThe shortest distances of all the
vertices from vertex ” + source + ” are: “);
for (int j = 0; j < n; j++)
{
if (Distance[j] == infinity)
Console.WriteLine(source + ” -> ” + vertices[j] +
” = No path”);
else 11.48 Solving Programming Problems Using Graphs  ¤NIIT
Console.WriteLine(source + ” -> ” + vertices[j] +
” = ” + Distance[j]);
}
}
}
class Graph_Program
{
static void Main(string[] args)
{
Graph g = new Graph();
char ch;
do
{
Console.WriteLine();
Console.WriteLine(“Menu”);
Console.WriteLine(“1. Add a vertex”);
Console.WriteLine(“2. Add an edge”);
Console.WriteLine(“3. Display”);
Console.WriteLine(“4. Find shortest paths from a
given source vertex”);
Console.WriteLine(“5. Exit”);
Console.WriteLine();
Console.Write(“Enter your choice: “);
ch = Convert.ToChar(Console.ReadLine());
switch (ch)
{
case ‘1’: g.addVertex(); break;
case ‘2’: g.addEdge(); break;
case ‘3’: g.display(); break;
case ‘4’: g.findShortestPath(); break;
case ‘5’: break;
default: Console.WriteLine(“Invalid choice.”);
break;
}
} while (ch != ‘5’);
}
}
}
// Code in C++
#include <iostream.h>
#include <string.h>
#define infinity 9999 ¤NIIT Solving Programming Problems Using Graphs 11.49
class Graph
{
private:
char vertices [10][15]; /* This array will store the
names of vertices. */
int cost[10][10] ; /* Adjacency matrix containing the
cost of edges. */
int n; // n is the number of vertices
public:
Graph()
{
n = 0;
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
{
if (i == j)
cost[i][j] = 0;
else
cost[i][j] = infinity; /* infinity
indicates that there is no edge from
vertex i to vertex j */
}
}
int edgeExists()
{
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
if ((cost[i][j] != 0) && (cost[i][j] !=
infinity ))
return (1);
return (0);
}
int getIndex(char *vname)
{
for (int i = 0; i < n; i++)
if (strcmp(vertices[i],vname) == 0)
return (i);
return (-1); /* If the vertex is not found in the
list, -1 is returned.*/
} 11.50 Solving Programming Problems Using Graphs  ¤NIIT
void addVertex()
{
char vname[15]; /* This array will store the name
of the vertex to be added. */
cout << “\nEnter vertex name: “;
cin >> vname;
int i = getIndex(vname);
if (i != -1)
{
cout << endl << “Vertex already exists.” <<
endl;
return;
}
strcpy(vertices[n],vname);
n++;
}
void addEdge()
{
char v1[15], v2[15];
int i1, i2;
if (n==0)
{
cout << “\nNo vertex exists. You must first
add a vertex.\n”;
return;
}
while (1)
{
cout << “\nEnter the source vertex: “;
cin >> v1;
i1 = getIndex(v1);
if (i1 == -1)
cout << endl << “Source vertex does not
exist. Try again.” << endl;
else
break;
}
while (1)
{
cout << “\nEnter the destination vertex: “;
cin >> v2;
i2 = getIndex(v2); ¤NIIT Solving Programming Problems Using Graphs 11.51
if (i2 == -1)
cout << endl << “Destination vertex
does not exist. Try again.” << endl;
else
break;
}
cout << “\nEnter the cost of the edge: “;
cin >> cost[i1][i2];
}
void display()
{
if (n==0)
{
cout << “\nGraph does not exist.\n”;
return;
}
cout << endl << “Vertices:” << endl;
for (int i = 0; i < n; i++)
cout << vertices[i] << endl;
if (edgeExists())
{
cout << endl << “Edges:” << endl;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if ((cost[i][j] != 0) &&
(cost[i][j] != infinity))
cout << vertices[i] <<
“->” << vertices[j] <<
”  –   ” << cost[i][j]
<< endl;
}
}
void findShortestPath()
{
int Distance[10];
int Final[10];
char source[15];
int src; 11.52 Solving Programming Problems Using Graphs  ¤NIIT
if (n == 0)
{
cout << “\nGraph does not exist. You must first
insert some vertices and edges.\n”;
return;
}
while (1)
{
cout << “\nEnter source vertex: “;
cin >> source;
src = getIndex(source);
if (src == -1)
cout << “\nSource vertex does not exist.”;
else
break;
}
/* Initialize Distance Array and Final Array */
for (int i = 0; i < n; i++)
{
Distance[i] = cost[src][i];
Final[i] = 0;
}
Final[src] = 1;
for (int i = 1; i < n; i++) //n-1 passes
{
/* Find the smallest value in Distance array such
that the vertex with the smallest Distance value
has not been included in the Final array */
int v = 0;
/* Find a vertex that is not there in Final.
Store its index in v */
for (int j = 0; j < n; j++)
{
if (Final[j] == 0)
{
v = j;
break;
}
} ¤NIIT Solving Programming Problems Using Graphs 11.53
/* Find the vertex with smallest distance in Distance
array */
for (int j = 0; j < n; j++)
{
if ((Final[j] == 0) && (Distance[j] <
Distance[v]))
v = j;
}
Final[v] = 1;
/* Compute the distance of all nodes via node with
index min */
for (int w = 0; w < n; w++)
{
if (Final[w] == 0)
{
if (Distance[v] + cost[v][w] < Distance[w])
Distance[w] = Distance[v] + cost[v][w];
}
}
}
cout << “\nThe shortest distances of all the vertices
from vertex ” << source << ” are: \n”;
for (int j = 0; j < n; j++)
{
if (Distance[j] == infinity)
cout << source << ” -> ” << vertices[j] << ” = No
path” << endl;
else
cout << source << ” -> ” << vertices[j] << ” = ”
<< Distance[j]<< endl;
}
}
};
void main()
{
Graph g;
char ch;
do
{
cout<<endl<<“Menu”<<endl; 11.54 Solving Programming Problems Using Graphs  ¤NIIT
cout<< “1. Add a vertex” << endl;
cout<< “2. Add an edge” << endl;
cout<< “3. Display” << endl;
cout<< “4. Find shortest paths from a given source
vertex” << endl;
cout<< “5. Exit” << endl;

cout << “\nEnter your choice: “;
cin >> ch;
switch (ch)
{
case ‘1’: g.addVertex(); break;
case ‘2’: g.addEdge(); break;
case ‘3’: g.display(); break;
case ‘4’: g.findShortestPath(); break;
case ‘5’: break;
default: cout << “Invalid choice.”;
}
} while (ch != ‘5’);
}¤NIIT Solving Programming Problems Using Graphs 11.55
1. Consider the following graph.
Determine the DFS and BFS traversal sequence, taking v1 as the starting vertex.
2. Consider the following graph.
Which of the following is true for the given graph?
a. The graph is a directed graph with six nodes, seven edges, one loop, and one
isolated node.
b. The graph is a directed graph with seven nodes, eight edges, one loop, and one
isolated node.
c. The graph is an undirected graph with seven nodes, eight edges, one loop, and
one isolated node.
d. The graph is a directed graph with seven nodes, seven edges, one loop, and one
isolated node.
Practice Questions 11.56 Solving Programming Problems Using Graphs  ¤NIIT
3. Consider the following graph.
Identify the correct adjacency matrix representation for the given graph.
a.   A B C
A 0 1 0
B 1 0 1
C 0 0 0
b.   A B C
A 0 1 0
B 0 0 1
C 1 0 0
c.   A B C
A 0 0 0
B 1 0 1
C 0 1 0
d.   A B C
A 1 0 0
B 0 1 0
C 0 0 1 ¤NIIT Solving Programming Problems Using Graphs 11.57
4. Briefly discuss the application areas of graphs.
5. Consider the following graph.
Calculate the minimum cost of connecting the vertices in the given graph by using
the Kruskal’s algorithm.  11.58 Solving Programming Problems Using Graphs  ¤NIIT
In this chapter, you learned that:
„ A graph is defined as a data structure that consists of a set of vertices (nodes) and
edges (arcs).
„ There are two types of graphs:
z Directed
z Undirected
„ The two most commonly used ways of representing a graph are as follows:
z Adjacency matrix
z Adjacency list
„ Traversing a graph means visiting all the vertices in the graph.
„ In a graph, there is no special vertex designated as the starting vertex. Therefore,
traversal of the graph may start from any vertex.
„ You can traverse a graph with the help of the following two methods:
z DFS
z BFS
„ Graph theory has been instrumental in analyzing and solving problems in areas as
diverse as computer network design, urban planning, finding shortest paths and
molecular biology.
„ Spanning tree of a connected undirected graph G refers to a spanning subgraph of G,
which connects all the nodes together in such a way that there are no cycles.
„ A spanning tree with n vertices has exactly n – 1 edges.
„ The most commonly used algorithms to determine the minimal spanning tree of a
graph are:
z Prim’s algorithm
z Kruskal’s algorithm
Summary ¤NIIT Solving Programming Problems Using Graphs 11.59
Exercise 1
You have to represent a set of cities and the distances between them in the form of a
graph. Write a program to represent the graph in the form of an adjacency list.
Exercise 2
Write a program to perform the Depth first and Breadth first traversal of a graph, where
each vertex in the graph represents the name of a city.
Exercises 11.60 Solving Programming Problems Using Graphs  ¤NIIT

Improving the
Efficiency of Binary
Search Trees
Chapter 10
A binary search tree provides an efficient
mechanism for storing and retrieving data. However,
there are certain situations in which a binary search
tree proves to be very inefficient in terms of
execution time or memory usage. In such a case, you
can improve the efficiency of a binary search tree by
implementing certain variants of a binary search
tree.
This chapter discusses the implementation of two
variants of binary search trees called threaded binary
trees and height balanced trees. In addition, it
explains how these variants help improve the
efficiency of binary search trees.
In this chapter, you will learn to:
 Implement a threaded binary tree
 Implement a height balanced tree
Objectives ¤NIIT Improving the Efficiency of Binary Search Trees 10.3
Note
In a linked representation of a binary search tree, you generally perform the traversal
through recursion. However, if the tree is huge, implementing recursion to traverse the
tree requires a lot of memory space. If memory is not sufficient, recursive traversal of the
tree will not be space-efficient and may lead to a memory leak. To overcome this
problem, you can use a threaded binary tree, which gives you an alternate method of
traversing the tree.
In a binary search tree, there are many nodes that have an empty left child or empty right
child or both. In such a case, it would be good if these fields are utilized to hold the
address of some other nodes in the tree. Suppose you always need to traverse the tree in
the inorder sequence. In this case, a node with an empty left child can be made to store the
address of its inorder predecessor. Similarly, a node with an empty right child can be
made to store the address of its inorder successor.
The inorder successor of a node x refers to the node that succeeds node x in the inorder
traversal sequence.
The inorder predecessor of a node x refers to the node that precedes node x in the inorder
traversal sequence.
A field that holds the address of the inorder successor or inorder predecessor of a node is
called thread. A binary search tree that implements threads is called a threaded binary
tree. A threaded binary tree enables you to traverse the tree without implementing
recursion. This is because, in a threaded binary tree, you can easily traverse the tree by
following the threads.
A binary tree is threaded according to a particular traversal order. For example, if a
particular operation requires you to frequently traverse the tree in the inorder
sequence, then every empty left child field of a node can hold the address of its
inorder predecessor, and every empty right child field can hold the address of its
inorder successor. Similarly, for preorder / postorder traversals, every empty left
child field of a node can hold the address of its preorder/postorder predecessor, and
the empty right child field can hold the address of its preorder/postorder successor
respectively.
Implementing a Threaded Binary Tree
Defining Threaded Binary Trees 10.4 Improving the Efficiency of Binary Search Trees  ¤NIIT
Consider a threaded binary tree, as shown in the following figure.
Threaded Binary Tree
In the preceding figure, the dotted lines represent the threads and the solid lines represent
the links. Nodes with empty left or right children point to their inorder successor or
inorder predecessor respectively. For example, node 69 does not have a left child.
Therefore, the left child of node 69 is a thread pointing to its inorder predecessor, which is
node 65. Similarly, node 45 does not have a left and right child. Therefore, the left and
right child fields of node 45 are threads pointing to its inorder predecessor (node 40) and
inorder successor (node 50) respectively.
A threaded binary tree also contains a dummy node called the header node. The right
child of the header node is a link, which always points to the header node itself. The
threaded binary tree is represented as the left subtree of the header node, which means
that the left child of the header node points to the root of the tree. When the tree is empty,
the left child of the header node is a thread pointing to itself.
Now the leftmost node in a threaded binary tree does not have an inorder predecessor.
This is because it is the first node to be traversed in the inorder sequence. In this case, the
header node serves as the inorder predecessor of the leftmost node. Similarly, the
rightmost node in a threaded binary tree does not have an inorder successor. This is
because it is the last node to be traversed in the inorder sequence. In such a case, the
header node serves as the inorder successor of the rightmost node. ¤NIIT Improving the Efficiency of Binary Search Trees 10.5
Just a minute:
A threaded binary tree offers the following advantages:
„ Faster traversal: Traversal in a threaded binary tree is fast because you need not
implement recursion to traverse the tree. Therefore, no stack needs to be used to keep
track of recursive function calls, and all machine intensive operations, such as pop
and push, which require considerable execution time, can be done away with.
„ Less memory usage: When you implement recursion to traverse a binary search
tree, a stack is maintained in the memory to keep track of the recursive function
calls. If the tree is too big in size, a large numbers of entries may be pushed into the
stack, which may result in a memory overflow. A threaded binary tree overcomes
this disadvantage by avoiding the use of recursion to traverse the binary search tree.
In a threaded binary tree, the right thread of a node points to its inorder__________,
and the left thread points to its inorder ________.
Answer:
successor, predecessor
The representation of a threaded binary tree is similar to that of a binary search tree. It is
represented in the program by defining two classes:
„ Node class: It represents a node in a threaded binary tree. Like a binary search tree, a
node in a threaded binary tree consists of data, reference of its left child, and
reference of its right child. However, in a threaded binary tree, it is important to
determine whether the left and right child of a node is a thread or a link. Therefore,
to keep track of this information, you need to implement two additional variables in
the Node class:
z lthread: This variable can have two values, 0 or 1. If the value of 1thread is 0,
it means that the left child field contains a thread pointing to the inorder
predecessor. However, if the value is 1, it means that the left child field contains
a link pointing to the left child.
z rthread: This variable can also have two values, 0 or 1. If the value of the
rthread is 0, it means that the right child field contains a thread pointing to the
inorder successor. However, if the value is 1, it means that the right child field
contains a link pointing to the right child.
Representing a Threaded Binary Tree 10.6 Improving the Efficiency of Binary Search Trees  ¤NIIT
Note
The rest of the three fields, lchild, info, and rchild are same as that of a binary
search tree.
Various operations implemented in a threaded binary tree are same as that of a
normal binary search tree. However, you need to implement two additional
operations to find the inorder successor and inorder predecessor of a node.
One of the disadvantages of a threaded binary tree is that you need to maintain two
extra pieces of information to indicate whether the pointer is a link to its child or a
thread. This leads to slow insertions and deletions because extra information needs to
be maintained.
The following is the C# and C++ declaration of the Node class:
// Code in C#
class Node
{
public Node lchild;
public int lthread;
public int data;
public Node rchild;
public int rthread;
}
// Code in C++
class Node
{
public:
Node *lchild;
int lthread
int data;
Node *rchild;
int rthread;
};
„ ThreadedBST class: This class includes functions for implementing various
operations on a threaded binary tree. These operations include search, insertion,
deletion, traversal, and finding the inorder successor and predecessor of a node. It
also contains the declaration of the header node, head. The following is the
declaration of the ThreadedBST class in C# and C++:
// Code in C#

class ThreadedBST
{¤NIIT Improving the Efficiency of Binary Search Trees 10.7
Just a minute:
private Node head;
public ThreadedBST(){};
public void find(int element, ref Node parent, ref Node
currentNode){};
public void insert(int element){};
public Node Inorder_successor(ref Node currentNode){};
public void Inorder_traversal(){};
public void remove(int element){};
};
// Code in C++
class ThreadedBST
{
Node *head;
public:
ThreadedBST();
void find(int element,Node **parent,Node ** currentNode);
void insert(int element);
Node * Inorder_successor(Node *currentNode);
void Inorder_traversal();
void remove(int element);
};
How do you identify the root node in a threaded binary tree?
Answer:
In a threaded binary tree, the root node is identified as the left child of the header
node. If the tree is empty, the left child of the header node becomes a thread pointing
to itself. 10.8 Improving the Efficiency of Binary Search Trees  ¤NIIT
Just a minute:
How is the structure of the node of a threaded binary tree different from that of a
normal binary tree?
Answer:
Each node in a threaded binary tree holds two extra pieces of information known as
left thread and right thread. The value of these two fields indicates whether the
left/right child field of a node contains a link to a child node or a thread to its inorder
predecessor/successor.
In a threaded binary tree, traversal is implemented with the help of threads. Consider a
threaded binary tree in which the empty left child of a node points to the inorder
predecessor of the node, and the empty right child points to the inorder successor of the
node.
You can perform the inorder traversal of the threaded binary tree by finding the inorder
successor of each node that has been traversed.
The inorder successor of a node is the leftmost node in the right subtree of that node.
Therefore, if the right child of the node is a link, then we can traverse to the leftmost node
in the right subtree of that node to find its inorder successor. However, if the right child of
the node is a thread, then the thread will point to the inorder successor of that node.
Refer to the following algorithm to find the inorder successor of a node in a threaded
binary tree:
1. Identify the node for which you need to locate the inorder successor, and mark it as
currentNode.
2. If the right child of currentNode is a thread:
a. Mark the right child of currentNode as successor.
b. Exit.
3. Make currentNode point to its right child.
4. Repeat step 5 until the left child of currentNode becomes a thread.
5. Make currentNode point to its left child.
6. Mark currentNode as successor.
Traversing a Threaded Binary Tree ¤NIIT Improving the Efficiency of Binary Search Trees 10.9
Now write an algorithm to traverse a threaded binary tree in the inorder traversal
sequence. To traverse a threaded binary tree in the inorder sequence, you first need to visit
the leftmost node of the tree. After you reach the leftmost node of the tree and visit it, you
can then traverse the entire tree by finding the inorder successor of each node being
visited.
Refer to the following algorithm to traverse the threaded binary tree in inorder sequence:
1. If the left child of the header node is a thread pointing to itself:
a. Display “Tree is empty”.
b. Exit.
2. Mark the left child of the header node as currentNode.
3. Repeat step 4 until the left child of currentNode becomes a thread.
4. Make currentNode point to its left child.
5. Display the information contained in currentNode.
6. Repeat steps 7 and 8 until right child of currentNode points to the header node.
7. Find the inorder successor of currentNode, and mark the inorder successor as
currentNode.
8. Display the information contained in currentNode.
The insert operation in a threaded binary tree refers to the process of inserting a node in
the tree at its appropriate position. It is same as that of the insert operation in a binary
search tree. However, there is an additional overhead involved in the insert operation in a
threaded binary tree. This is because every insert operation not only requires you to link
the new node with the left/right child filed of its parent, but also requires you to adjust the
threads appropriately.
You need to consider two cases before performing an insert operation in a threaded binary
tree. The two cases are as follows:
„ Tree is empty: In this case, the new node to be inserted will be the root node.
Initially, when the tree is empty, the left child field of the header node is a thread
pointing to itself. Therefore, to insert a new node, you need to link the left child field
of the header node with the new node. This would also require you to update the left
thread field of the header node, so that now it becomes a link pointing to the new
node. Moreover, the newly inserted node is the only node in the tree; therefore, its
left and right child fields will be threads pointing to the header node. Refer to the
following algorithm to insert a node in an empty threaded binary tree:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. Set the values of the left and right thread fields of the new node as zero.
Inserting Nodes in a Threaded Binary Tree 10.10 Improving the Efficiency of Binary Search Trees  ¤NIIT
4. Set the value of the left thread field of the head node as one.
5. Make the left child field of the header node as a link pointing to the new node.
6. Make the left child field of the new node as a thread pointing to the header
node.
7. Make the right child field of the new node as a thread pointing to the header
node.
The process of inserting a new node in an empty threaded binary tree is illustrated in
the following table.
Operation Illustration
Allocate memory and
assign value to the data
field of the new node. Set
the values of the left and
right thread fields of the
new node as zero.
Set the value of the left
thread field of the header
node as one.
Make the left child field of
the header node as a link
pointing to the new node.
Make the left child field of
the new node as a thread
pointing to the header
node.
Make the right child field
of the new node as a
thread pointing to the
header node.
Inserting a New Node in an Empty Threaded Binary Tree¤NIIT Improving the Efficiency of Binary Search Trees 10.11
„ Tree is not empty: In this case, you first need to locate the appropriate position of
the new node to be inserted. To locate the position of the new node, you need to
locate its parent. This gives rise to two cases:
z Node to be inserted is the left child of its parent: In this case, you need to
adjust the threads of the new node, so that its left and right child fields point to
its inorder predecessor and inorder successor respectively. The inorder
predecessor of the new node will be the inorder predecessor of its parent. The
inorder successor of the new node will be its parent. In addition, you need to
link the new node with the left child field of its parent. This would also require
you to update the left thread field of the parent, so that now it becomes a link
pointing to the new node.
z Node to be inserted is the right child of its parent: In this case, you need to
adjust the threads of the new node so that its left and right child fields point to
its inorder predecessor and inorder successor respectively. The inorder
predecessor of the new node will be its parent. The inorder successor of the new
node will be the inorder successor of its parent. In addition, you need to link the
new node with the right child field of its parent. This would also require you to
update the right thread field of the parent, so that now it becomes a link pointing
to the new node.
Refer to the following algorithm to insert a new node in a threaded binary tree:
1. Locate the node which will be the parent of the node to be inserted. Mark it as
parent. Execute the following steps to locate the parent of the new node to be
inserted:
a. If the left child of the header node is a thread pointing to itself:
i. Mark head as parent.
ii. Go to step 2.
b. Mark the left child of head as currentNode.
c. Mark head as parent.
d. Repeat steps i, ii, iii, iv, and v until currentNode becomes NULL:
i. Mark currentNode as parent.
ii. If the value of the new node is less than that of the currentNode and the left
child of currentNode is a normal link:
a)   Make currentNode point to its left child and go to step d.
iii. If the value of the new node to be inserted is less than that of currentNode,
and if the left child of currentNode is a thread:
a)   Mark currentNode as NULL, and go to step d.
iv. If the value of the new node to be inserted is greater than that of
currentNode, and the right child of currentNode is a normal link:
a)   Make currentNode point to its right child and go to step d. 10.12 Improving the Efficiency of Binary Search Trees  ¤NIIT
v. If the value of the new node to be inserted is greater than that of
currentNode, and if the right child of currentNode is a thread:
a)   Mark currentNode as NULL and go to step d.
2. Allocate memory for the new node.
3. Assign value to the data field of the new node.
4. Set the values of the left and right thread fields of the new node as zero.
5. If parent points to the header node:
a. Set the value of the left thread field of the header node as one.
b. Make the left child of the header node point to the new node.
c. Make the left and right child fields of the new node point to the header node.
d. Exit.
6. If the value of the new node is less than that of parent:
a. Make the left child field of the new node point to the node pointed by the left
child field of the parent.
b. Make the right child field of the new node point to parent.
c. Set the value of the left thread field of the parent as one.
d. Make the left child of the parent point to the new node.
e. Exit.
7. If the value of the new node is greater than that of the parent:
a. Make the left child field of the new node point to the parent.
b. Make the right child field of the new node point to the node pointed by the right
child field of the parent.
c. Set the value of the right thread field of the parent as one.
d. Make the right child of the parent point to the new node.
e. Exit. ¤NIIT Improving the Efficiency of Binary Search Trees 10.13
Suppose you want to insert a node 75 in the threaded binary tree, as shown in the
following figure.
Threaded Binary Tree Before Inserting Node 75 10.14 Improving the Efficiency of Binary Search Trees  ¤NIIT
The process of inserting node 75 in a threaded binary tree is illustrated in the following
table.
Operation Illustration
Locate the
parent of the
new node to be
inserted. Mark
it as parent.
Allocate
memory and
assign value to
the data field of
the new node.
Set the values
of the left and
right thread
fields of the
new node as
zero. ¤NIIT Improving the Efficiency of Binary Search Trees 10.15
Operation Illustration
Make the left
child field of
the new node
point to the
node pointed
by the left child
field of parent. 10.16 Improving the Efficiency of Binary Search Trees  ¤NIIT
Operation Illustration
Make the right
child field of
the new node
point to parent. ¤NIIT Improving the Efficiency of Binary Search Trees 10.17
Operation Illustration
Set the value of
the left thread
field of parent
as 1.
Make the left
child of parent
point to the
new node.
Insert Operation in a Threaded Binary Tree 10.18 Improving the Efficiency of Binary Search Trees  ¤NIIT
Now insert a new node as the right child of its parent. Suppose you want to insert a node
35 in the threaded binary tree, as shown in the following figure.
Threaded Binary Tree Before Inserting Node 35 ¤NIIT Improving the Efficiency of Binary Search Trees 10.19
The process of inserting node 35 in a threaded binary tree is illustrated in the following
table.
Operation Illustration
Locate the
parent of the
new node to be
inserted. Mark it
as parent.
Allocate memory
and assign value
to the new node.
Set the values of
the left and right
thread fields of
the new node as
zero. 10.20 Improving the Efficiency of Binary Search Trees  ¤NIIT
Operation Illustration
Make the right
child field of the
new node point
to the node
pointed by the
right child field
of parent. ¤NIIT Improving the Efficiency of Binary Search Trees 10.21
Operation Illustration
Make the left
child field of the
new node point
to parent. 10.22 Improving the Efficiency of Binary Search Trees  ¤NIIT
Operation Illustration
Set the value of
the right thread
field of parent as
1.
Make the right
child of parent
point to the new
node.
Insert Operation in a Threaded Binary Tree
The delete operation in a threaded binary tree refers to the process of removing a specified
node from the tree. It is similar to the delete operation in a simple binary search tree.
However, to delete a node from a threaded binary tree, you need to implement a few
additional steps to adjust the left/right thread fields of the node to be deleted and its
parent.
Before implementing the delete operation, you first need to check whether the tree is
empty or not. If the tree is empty, an error message is shown.
If the tree is not empty, you need to locate the node to be deleted and its parent node.
Refer to the following algorithm to locate the node to be deleted and its parent:
1. If the left child of the header node is a thread pointing to itself:
a. Mark the header node as parent.
b. Mark currentNode as NULL.
c. Exit.
Deleting a Node from a Threaded Binary Tree ¤NIIT Improving the Efficiency of Binary Search Trees 10.23
2. Mark the left child of the header node as currentNode.
3. Mark the header node as parent.
4. Repeat steps a, b, c, d, and e until the node to be searched is found or currentNode
becomes NULL:
a. Mark currentNode as parent.
b. If the value of the node to be searched is less than that of currentNode, and the
left child of currentNode is a link:
i. Make currentNode point to its left child.
ii. Go to step 4.
c. If the value of the node to be searched is less than that of currentNode, and the
left child of currentNode is a thread:
i. Mark currentNode as NULL.
ii. Go to step 4.
d. If the value of the node to be searched is greater than that of currentNode, and
the right child of currentNode is a link:
i. Make currentNode point to its right child.
ii. Go to step 4.
e. If the value of the node to be searched is greater than that  of currentNode, and
the right child of currentNode is a thread:
i. Mark currentNode as NULL.
ii. Go to step 4.
After executing the preceding algorithm, currentNode is positioned on the node to be
deleted and parent is positioned on its parent. After these nodes are located, there can be
three cases.
„ Node to be deleted is a leaf node: If the tree contains only the root node, then
deletion of the root will make the tree empty. In this case, you need to make the left
child field of the header node as a thread pointing to itself, and set the left thread
field of the header node to zero. However, if more than one node is present in the
tree, there can be two possibilities:
z Node to be deleted is the left child of its parent: In this case, the left child
field of the parent is made a thread pointing to the inorder predecessor of the
node to be deleted.
z Node to be deleted is the right child of its parent: In this case, the right child
field of the parent is made a thread pointing to the inorder successor of the node
to be deleted.  10.24 Improving the Efficiency of Binary Search Trees  ¤NIIT
Refer to the following algorithm to delete a leaf node from a threaded binary tree:
1. Locate the position of the node to be deleted. Mark it as currentNode and its parent
as parent.
2. If parent is the header node:
a. Set the left thread field of the header node as zero.
b. Make the left child field of the header node as a thread pointing to itself.
c. Go to Step 5.
3. If currentNode is the left child of parent:
a. Set the left thread field of parent as zero.
b. Make the left child field of parent as a thread pointing to the inorder predecessor
of currentNode.
c. Go to step 5.
4. If currentNode is the right child of parent:
a. Set the right thread field of parent as zero.
b. Make the right child field of parent as a thread pointing to the inorder successor
of currentNode.
5. Release the memory for currentNode. ¤NIIT Improving the Efficiency of Binary Search Trees 10.25
The process of deleting a leaf node, 60 from a threaded binary tree is illustrated in the
following table.
Operation Illustration
Locate the
position of the
node to be
deleted. Mark it
as currentNode
and its parent
as parent. 10.26 Improving the Efficiency of Binary Search Trees  ¤NIIT
Operation Illustration
If currentNode
is the right
child of parent,
make the right
child field of
parent as a
thread pointing
to the inorder
successor of
currentNode.
Release the
memory for
current node.
Deleting a Leaf Node from a Threaded Binary Tree ¤NIIT Improving the Efficiency of Binary Search Trees 10.27
„ Node to be deleted has one child (left/right): In this case, you need to link the child
of the node to be deleted with the left or right child of its parent, depending upon
whether the node to be deleted is the left or right child of its parent. You also need to
locate the inorder successor and inorder predecessor of the node to be deleted. If the
node to be deleted has a right subtree, then make the left thread of its inorder
successor point to its inorder predecessor. If the node to be deleted has a left subtree,
then make the right thread of its inorder predecessor point to its inorder successor.
Refer to the following algorithm to delete a node that has one child:
1. Locate the node to be deleted. Mark it as currentNode and its parent as parent.
2. If currentNode has a left subtree:
a. Mark the left child of currentNode as child.
b. Go to step 4.
3. If currentNode has a right subtree:
a. Mark the right child of currentNode as child.
b. Go to step 4.
4. If currentNode is the left child of parent:
a. Make the left child of parent point to child.
b. Go to step 6.
5. If currentNode is the right child of parent:
a. Make the right child of parent point to child.
b. Go to step 6.
6. Find the inorder successor and inorder predecessor of currentNode. Mark them
as successor and predecessor, respectively.
7. If currentNode has a right child:
a. Make the left child field of its successor point to its predecessor.
b. Set the left thread of the successor to zero.
c. Go to step 9.
8. If currentNode has a left child:
a. Make the right child field of its predecessor point to its successor.
b. Set the right thread of the predecessor to zero.
9. Release the memory for currentNode. 10.28 Improving the Efficiency of Binary Search Trees  ¤NIIT
The process for deleting node, 50 from the threaded binary tree is illustrated in the
following table.
Operation Illustration
Locate the node
to be deleted.
Mark it as
currentNode
and its parent
as parent.
If currentNode
has a right
subtree, mark
the right child
of currentNode
as child. ¤NIIT Improving the Efficiency of Binary Search Trees 10.29
Operation Illustration
If currentNode
is the right child
of parent, make
the right child
of parent point
to child. 10.30 Improving the Efficiency of Binary Search Trees  ¤NIIT
Operation Illustration
Find the inorder
successor and
inorder
predecessor of
currentNode.
Mark them as
successor and
predecessor,
respectively. ¤NIIT Improving the Efficiency of Binary Search Trees 10.31
Operation Illustration
If currentNode
has a right
child, make the
left thread of
successor point
to predecessor. 10.32 Improving the Efficiency of Binary Search Trees  ¤NIIT
Operation Illustration
Release the
memory for
currentNode.
Deleting a Node Having One Child in a Threaded Binary Tree ¤NIIT Improving the Efficiency of Binary Search Trees 10.33
„ Node to be deleted has two children: In this case, the node to be deleted needs to be
replaced by its inorder successor. Refer to the following algorithm to delete a node
that has two children:
1. Locate the position of the node to be deleted. Mark it as currentNode.
2. Locate the inorder successor of currentNode. Mark it as Inorder_suc and its
parent as Inorder_parent.
3. Overwrite the data contained in currentNode with the data contained in
Inorder_suc.
4. Delete the node marked Inorder_suc. This node would have at the most one
child and can therefore be deleted by using the algorithm for one of the
following:
a. Deleting a leaf node.
b. Deleting a node with one child.
Suppose you want to delete node 40 in a threaded binary tree, as shown in the
following figure.
Threaded Binary Tree Before Deleting Node 40 10.34 Improving the Efficiency of Binary Search Trees  ¤NIIT
The process of deleting node, 40 from the threaded binary tree is illustrated in the
following table.
Operation Illustration
Locate the
position of the
node to be
deleted. Mark it
as currentNode. ¤NIIT Improving the Efficiency of Binary Search Trees 10.35
Operation Illustration
Locate the
inorder
successor of
currentNode.
Mark it as
Inorder_suc and
its parent as
Inorder_parent.
Overwrite the
data contained
in currentNode
with the data
contained in
Inorder_suc. 10.36 Improving the Efficiency of Binary Search Trees  ¤NIIT
Operation Illustration
The node
marked
Inorder_suc is a
leaf node.
Therefore, delete
the node marked
Inorder_suc by
using the
algorithm for
deleting a leaf
node.
.
Deleting a Node Having Two Children in a Threaded Binary Tree ¤NIIT Improving the Efficiency of Binary Search Trees 10.37
The time required to search for a value in a binary search tree depends on its height. The
shorter the height, the faster is the search. Therefore, it is desirable to keep the height of
the binary search tree to a minimum. This can be done by using a variant of the binary
search tree called a height balance tree.
Suppose elements are added to an empty binary search tree in the following sequence:
3   5   6   9   11   13   16
After inserting the preceding values, the binary search tree will appear, as shown in the
following figure.
Unbalanced Binary Search Tree
Implementing a Height Balanced Tree
Defining Height Balanced Tree 10.38 Improving the Efficiency of Binary Search Trees  ¤NIIT
In the preceding figure, the binary search tree has acquired a linear structure similar to a
linked list. Therefore, to search for a particular value in the binary search tree, you will
have to traverse all its preceding nodes before you reach the desired node. This means that
the preceding structure has lost its property of a binary search tree in which the number of
search operations is reduced to half after every comparison. In other words, you can say
that the tree has become unbalanced. To balance the tree and restore its property of a
binary search tree, the preceding structure can be reduced in form, as shown in the
following figure.
Balanced Binary Search Tree
Consider another case of binary search tree, as shown in the following figure.
Unbalanced Binary Search Tree
Suppose you want to search for a node 11 in the preceding binary search tree. The search
time in a binary search tree depends upon the number of comparisons made to search for a
particular value. The number of comparisons in turn depends upon the height of the tree.
For example, to reach node 11, you will have to compare its value with the nodes 1, 6, 12,
8, and 9, before you reach node 11.  ¤NIIT Improving the Efficiency of Binary Search Trees 10.39
However, if somehow you reduce the height of the preceding binary search tree, then the
number of comparisons to search for a particular node would also get reduced. Consider
the following binary search tree that contains the same nodes as in the preceding binary
search tree, arranged in a different manner so as to minimize the height of the binary
search tree.
Balanced Binary Search Tree
Now if you want to search for a value 11 in the preceding binary search tree, the
intermediate nodes to be visited will be 8, 12, and 10. This means that the number of
comparisons required to search a value in a shorter tree is less than the number of
comparisons required to search a value in a taller tree.
You can minimize the height of a binary search tree by implementing a height balanced
tree. A height balanced tree is a binary tree in which the difference between the height of
the left and right subtree is not more than one. A height balanced tree enables you to
optimize the search process by maintaining the height of the tree to its minimum.
Each node in a height balanced tree has a Balance Factor (BF) associated with it. BF of a
node can be calculated as follows:
BF = Height of left subtree – Height of right subtree
For the tree to be balanced, the BF for each node should have one of the following three
values:
„ 0: A BF value of 0 indicates that the height of the left subtree of a node is equal to
the height of its right subtree.
„ 1: A BF value of 1 indicates that the height of the left subtree is greater than the
height of the right subtree by one. A node in this state is said to be left heavy.
„ –1: A BF value of –1 indicates that the height of the right subtree is greater than the
height of the left subtree by one. A node in this state is said to be right heavy. 10.40 Improving the Efficiency of Binary Search Trees  ¤NIIT
Note
The value considered for the balance factor of a node is purely conventional. In some
books, you may find the balance factor of a left heavy node as –1 and that of right
heavy node as 1.
A tree becomes unbalanced if any node in the tree attains a balance factor other than 0, 1,
or –1.
Consider the binary search trees that are height balanced, as shown in the following
figure.
Height Balanced Trees
Consider the binary search trees that are not height balanced, as shown in the following
figure.
Unbalanced Binary Search Trees ¤NIIT Improving the Efficiency of Binary Search Trees 10.41
Just a minute:
In a height balanced tree, the maximum difference between the height of the left and
right subtree of a node can be ________.
Answer:
One
The insert operation in a height balanced tree is similar to that in a simple binary search
tree. However, inserting a node in a binary search tree can change the balance factor of
the various nodes in the subtree in which the new node is inserted. This may make the tree
unbalanced. If this happens, you need to restore the balance of the tree.
Refer to the following steps to insert a node in a binary search tree and restore its balance
in case it becomes unbalanced:
1. Insert the node at its appropriate place in the binary search tree.
2. Calculate the balance factors of all the nodes on the path starting from the newly
inserted node to the root node.
3. If the balance factor of each node in this path has a value 1, 0, or –1, then the tree is
balanced. Therefore, you can stop here.
4. If the value of the balance factor of any node in this path is other than 1, 0, or –1,
then the tree has become unbalanced. In this case, you need to restore the balance of
the tree.
To restore the balance of the tree, you first need to locate the pivot node. A pivot node
refers to the nearest unbalanced ancestor of the newly inserted node i.e. nearest ancestor
having a balance factor other than –1, 0, or 1.
Inserting Nodes in a Height Balanced Tree 10.42 Improving the Efficiency of Binary Search Trees  ¤NIIT
Consider the balanced binary search tree, as shown in the following figure.
Balanced Binary Search Tree Before Insert Operation
Suppose you insert the value 16 in the preceding binary search tree. Refer to the resultant
binary search tree, as shown in the following figure.
Node 16 Inserted ¤NIIT Improving the Efficiency of Binary Search Trees 10.43
The resultant tree is now unbalanced. The nearest ancestor of node 16 with a balance
factor 2 or –2 is node 17. Therefore, node 17 is the pivot node, as shown in the following
figure.
Pivot Node in an Unbalanced Binary Search Tree 10.44 Improving the Efficiency of Binary Search Trees  ¤NIIT
After the pivot node is located, you can balance the binary search tree by performing
appropriate rotations around the pivot node. This involves two cases:
„ Pivot node is initially right heavy and the new node is inserted in the right
subtree of the pivot node: Let P be the pivot node and X be its right child. Let Pr be
the right subtree of P, and Xr and Xl be the right and left subtree of X respectively.
When a new node is inserted in the right subtree of P, the balance factor of P
becomes –2. This makes the tree unbalanced. To restore the balance, you need to
perform appropriate rotations around the pivot node. The type of rotation to be
performed would depend on whether:
z The new node is inserted in the right subtree of X: In this case, a single left
rotation is required to restore the balance. In this type of rotation, node X is
moved upwards to form the root. The left subtree of X becomes the right subtree
of P and P becomes the left child of X, as shown in the following figure.
Before Rotation  After Rotation
Left Rotation Around the Pivot ¤NIIT Improving the Efficiency of Binary Search Trees 10.45
z The new node is inserted in the left subtree of x: In this case, a double
rotation is required to restore the balance of the tree. Let Y be the root of the left
subtree of X, and Yr and Yl be the right and left subtree of Y respectively, as
shown in the following figure.
Double Rotation
A double rotation in this case involves the following steps:
i. The subtree with root X is rotated right in such a way so that Y moves in
place of X. The right subtree of Y becomes the left subtree of X and X
becomes the right child of Y, as shown in the following figure.
Tree After First Rotation 10.46 Improving the Efficiency of Binary Search Trees  ¤NIIT
ii. The subtree with root P is rotated left so that Y moves upwards to form the
root. The left subtree of Y becomes the right subtree of P and P becomes
the left child of Y, as shown in the following figure.
Tree After Second Rotation ¤NIIT Improving the Efficiency of Binary Search Trees 10.47
„ Pivot node is initially left heavy and the new node is inserted in the left subtree
of the pivot node: Let P be the pivot node and X be its left child. When a new node
is inserted in the left subtree of P, the balance factor of P becomes +2. This makes
the tree unbalanced. To restore the balance, you need to perform appropriate
rotations around the pivot node. The type of rotation to be performed would depend
on whether:
z The new node is inserted in the left subtree of X: In this case, a single right
rotation is required to restore the balance. In this type of rotation, node X is
rotated upwards to form the root. The right subtree of X becomes the left
subtree of P and P becomes the right child of X, as shown in the following
figure.
Before Rotation  After Rotation
Right Rotation Around Pivot 10.48 Improving the Efficiency of Binary Search Trees  ¤NIIT
z The new node is inserted in the right subtree of X: In this case, a double
rotation is required to restore the balance. Let Y be the root of the right subtree
of X, as shown in the following figure.
Double Rotation
A double rotation in this case involves the following steps:
i. The subtree with root X is rotated left in such a way that Y moves in place
of X. The left subtree of Y becomes the right subtree of X and X becomes
the left child of Y, as shown in the following figure.
Tree After First Rotation ¤NIIT Improving the Efficiency of Binary Search Trees 10.49
ii. The subtree with root P is rotated right so that Y moves upwards to form
the root. The right subtree of Y becomes the left subtree of P and P
becomes the right child of Y, as shown in the following figure.
Tree After Second Rotation
Consider an example to insert values in a height balanced tree and restore its balance
whenever required. The values to be inserted are in the following order:
50   40   30   60   55   80   10   35   32
The step by step procedure of inserting the nodes in a height balanced tree is illustrated in
the following table.
Action Status Illustration
Insert 50 The tree is
balanced.
Insert 40 The tree is
balanced. 10.50 Improving the Efficiency of Binary Search Trees  ¤NIIT
Action Status Illustration
Insert 30 The tree becomes
unbalanced.
A single right
rotation is required
to restore the
balance.
Rotate right
around node 50
The tree now
becomes balanced.
Insert 60 The tree is
balanced.
Insert 55 The tree becomes
unbalanced.
A double rotation
is required to
restore the
balance. ¤NIIT Improving the Efficiency of Binary Search Trees 10.51
Action Status Illustration
Rotate right
around node 60
The tree is still
unbalanced.
Another rotation is
required.
Rotate left around
node 50
The tree now
becomes balanced.
Insert 80 The tree becomes
unbalanced.
A single left
rotation is required
to restore the
balance.
Rotate left around
node 40
The tree now
becomes balanced. 10.52 Improving the Efficiency of Binary Search Trees  ¤NIIT
Action Status Illustration
Insert 10 Tree is balanced.
Insert 35 Tree is balanced.
Insert 32 Tree becomes
unbalanced.
A double rotation
is required to
restore the
balance. ¤NIIT Improving the Efficiency of Binary Search Trees 10.53
Just a minute:
Action Status Illustration
Rotate left around
node 30
The tree is still
unbalanced.
Another rotation is
required to restore
the balance.
Rotate right
around node 40
The tree now
becomes balanced.
Insert Operation in a Height Balanced Tree
In which situation do you need to implement a double rotation to balance the tree?
Answer:
There can be two situations where a double rotation is required to balance the tree:
„ If the pivot node is right heavy and the right child of pivot node is left heavy
„ If the pivot node is left heavy and the left child of pivot node is right heavy10.54 Improving the Efficiency of Binary Search Trees  ¤NIIT
The delete operation in a height balanced tree is same as that in a normal binary tree.
However, if deletion of a node makes the tree unbalanced, then you need to perform
appropriate rotations to restore the balance. This process involves the same concept as
used in insertion of a node. Consider the following height balanced tree.
Height Balanced Tree
The process of deleting a few nodes from the preceding binary search tree is illustrated in
the following table.
Action Status Illustration
Delete 53 The tree becomes
unbalanced.
A double rotation
is required to
restore the
balance.
Deleting Nodes from a Height Balanced Tree ¤NIIT Improving the Efficiency of Binary Search Trees 10.55
Action Status Illustration
Rotate left around
node 30
The tree is still
unbalanced.
Another rotation
is required to
restore the
balance.
Rotate right
around node 40
The tree is now
balanced.
Delete 60 The tree becomes
unbalanced.
A single left is
required to
restore the
balance. 10.56 Improving the Efficiency of Binary Search Trees  ¤NIIT
Action Status Illustration
Rotate left around
node 70
The tree is now
balanced.
Delete 50 The tree is
balanced.
Delete 40 The tree becomes
unbalanced.
A single right
rotation is
required to
restore the
balance. ¤NIIT Improving the Efficiency of Binary Search Trees 10.57
Action Status Illustration
Rotate right
around node 35
The tree is now
balanced.
Deleting Nodes in a Height Balanced Tree 10.58 Improving the Efficiency of Binary Search Trees  ¤NIIT
1. In a threaded binary tree, if a node does not have a left child, its left child field
contains:
a. NULL
b. The address of its inorder successor
c. Its own address
d. The address of its inorder predecessor
2. In a threaded binary tree, if a node does not have a right child, its right child field
contains:
a. NULL
b. The address of its inorder successor
c. Its own address
d. The address of its inorder predecessor
3. In a height balanced tree, the difference between the heights of the left and right
subtree of a node:
a. Should be zero
b. Should be maximum one
c. Cannot be zero
d. Cannot be one
4. Consider a situation in which the insertion of a new node in a binary tree disrupts its
balance. As a result, a double rotation is performed to restore its balance. Identify a
situation that would require a double rotation to restore the balance.
a. The pivot node is initially left heavy and the new node is inserted in the left
subtree of the left child of the pivot node.
b. The pivot node is initially left heavy and the new node is inserted in the right
subtree of the left child of the pivot node.
c. The pivot node is initially right heavy and the new node is inserted in the right
subtree of the right child of the pivot node.
d. The pivot node is initially right heavy and the new node is inserted in the left
subtree of the left child of the pivot node.
Practice Questions ¤NIIT Improving the Efficiency of Binary Search Trees 10.59
In this chapter, you learned that:
„ A threaded binary tree is a binary tree in which a node with an empty left child stores
the address of its inorder predecessor and the empty right child stores the address of
its inorder successor.
„ In a threaded binary tree, the left and right child field of a node, which holds the
address of its inorder predecessor and inorder successor, respectively, is called a
thread.
„ You can traverse a threaded binary tree without implementing recursion.
„ A threaded binary tree is represented as the left subtree of the header node.
„ In contrast to a normal binary tree, each node in a threaded binary consists of two
additional fields to keep track of whether the left and right child field of a node is a
thread or a link.
„ A height balanced tree is a binary tree in which the difference between the height of
the left and right subtree is not more than one.
„ A tree becomes unbalanced if any node in the tree attains a balance factor other than
0, 1, or –1.
„ If the tree becomes unbalanced, you need to balance the tree by performing
appropriate rotations around the pivot node.
Summary 10.60 Improving the Efficiency of Binary Search Trees  ¤NIIT
Exercise 1
Write a program to implement insert, delete, and traverse operations in a threaded binary
search tree, where each node in the tree contains a dictionary word.

Exercises

Solving
Programming
Problems Using
Trees
Chapter 9
Many programming problems require data to be
stored in a hierarchical fashion. This can be done by
using a data structure called tree. A tree not only
helps you represent the hierarchical relationship
between data, but also provides an efficient
mechanism for data storage and retrieval.
This chapter introduces you to the basic features of a
tree as a data structure. It discusses the
implementation of a specific type of tree called a
binary tree. It also explains a common variant of a
binary tree called binary search tree. It also focuses
on the various applications of trees.
In this chapter, you will learn to:
 Store data in a tree
 Implement a binary tree
 Implement a binary search tree
 Apply trees to solve programming problems
Objectives ¤NIIT Solving Programming Problems Using Trees 9.3
Consider a scenario where you are required to represent the directory structure of your
operating system. The directory structure contains various folders and files. A folder may
further contain any number of subfolders and files. Such an arrangement enables you to
keep the related files and folder together. The directory structure of an operating system is
shown in the following figure.
Directory Structure
Suppose you want to represent a similar directory structure in the memory. It is not
possible to represent the structure linearly because all the items have a hierarchical
relationship among themselves. To represent such a structure, it would be good to have a
data storage mechanism that enables you to store your data in a non linear fashion.
You can implement a tree to solve such a problem. Trees offer a lot of practical
applications in the field of computer science. For example, most of the modern operating
systems have their file systems organized as a tree.
Storing Data in a Tree 9.4 Solving Programming Problems Using Trees  ¤NIIT
A tree is a nonlinear data structure that represents a hierarchical relationship among the
various data elements, as shown in the following figure.
A Sample Tree Structure
Each data element in a tree is called a node. The topmost node of the tree is called a root.
The nodes in a tree are connected to other nodes through edges. The only way to get from
one node to the other is to follow the path along the edges.
Each node in a tree can have zero or more child nodes. However, each node in a tree has
exactly one parent. An exception to this rule is the root node, which has no parent.
In the tree structure that represents a hierarchical file system, the root directory is the root
of the tree. The directories one level below the root directory are the child nodes. Like
this, we can have various levels of subdirectories, thereby forming a hierarchical
structure. Files, on the other hand, will have no children. Therefore, they can be termed as
the leaf nodes.
Defining Trees ¤NIIT Solving Programming Problems Using Trees 9.5
There are various terms that are frequently used while working with trees. Let us explain
these terms by using the tree, as shown in the following figure.
Tree
The various terms associated with a tree are as follows:
„ Leaf node: A node with no children is called a leaf node. They are also referred to as
terminal nodes. In the given figure, E, F, G, H, I, J, L, and M are the leaf nodes.
„ Subtree: A portion of a tree, which can be viewed as a tree in itself, is called a
subtree. In the preceding figure, the tree starting at node B, containing nodes E, F, G,
and H, is a subtree of the complete tree. A subtree can also contain just one node
called the leaf node. In other words, all the leaf nodes are subtrees, but all the
subtrees are not leaf nodes.
„ Children of a node: The roots of the subtrees of a node are called the children of the
node. In the preceding figure, E, F, G, and H are the children of node B, and B is the
parent of nodes E, F, G, and H. Similarly, J and K are children of node D, and D is
the parent of J and K.
„ Degree of a node: The number of subtrees of a node is called the degree of a node.
In the preceding figure:
z Degree of node A is 3
z Degree of node B is 4
z Degree of node C is 1
z Degree of node D is 2
„ Edge: A link from the parent to the child node is referred to as an edge. It is also
known as a branch. A tree with n nodes has n – 1 edges.
Tree Terminology9.6 Solving Programming Problems Using Trees  ¤NIIT
Note
„ Siblings/Brothers: Children of the same node are called siblings of each other. In
the preceding figure:
z Nodes B, C, D are siblings of each other
z Nodes E, F, G, H are siblings of each other
z L and M are siblings of each other
„ Internal node: An intermediate node between the root and the leaf nodes is called an
internal node. It is also referred to as a non terminal node. In the preceding figure,
nodes B, C, D, and K are internal nodes.
„ Level of a node: The distance (in number of nodes) of a node from the root is called
the level of a node. The root always lies at level 0. As you move down the tree, the
level of a node increases in such a way that if a node is at level n, then its children
are at level n + 1. In the preceding tree, level of node A is 0, level of nodes B, C, and
D is 1, level of nodes E, F, G, H, I, J, and K is 2, and level of nodes L and M is 3.
„ Depth of a tree: The maximum number of levels in a tree is called the depth of a
tree. In other words, depth of a tree is one more than the maximum level of the tree.
The depth of a tree is also referred to as the height of a tree. The depth of the tree in
the preceding figure is 4.
Maximum number of nodes in a binary tree of depth d can be 2d
–1¤NIIT Solving Programming Problems Using Trees 9.7
Just a minute:
Consider the following tree and answer the questions that follow:
a. What is the depth of the tree?
b. Which nodes are the children of node B?
c. Which node is the parent of node F?
d. What is the level of node E?
e. Which nodes are the siblings of node H?
f. Which nodes are the siblings of node D?
g. Which nodes are the leaf nodes?
Answer:
a. 4
b. D and E
c. C
d. 2
e. H does not have any siblings
f. The only sibling of D is E
g. F, G, H, and I 9.8 Solving Programming Problems Using Trees  ¤NIIT
A binary tree is a special type of tree that offers a lot of practical applications in the field
of computer science. This section discusses the concept and implementation of a binary
tree.
A binary tree is a specific type of tree in which each node can have a maximum of two
children. These child nodes are typically distinguished as the left and the right child. The
structure of a binary tree is shown in the following figure.
Binary Tree
In the preceding binary tree, node B is the left child of node A, and node C is the right
child of node A. Similarly, node D is the left child of node B, and node E is the right child
of node B.
Implementing a Binary Tree
Defining Binary Trees ¤NIIT Solving Programming Problems Using Trees 9.9
There are some variants of binary trees with some additional characteristics. These
variants include:
„ Strictly binary tree: A binary tree is said to be strictly binary if every node, except
for the leaf nodes, have non-empty left and right children. Consider a strictly binary
tree, as shown in the following figure.
Strictly Binary Tree
In the preceding binary tree, every non-leaf node has precisely two children.
Therefore, it is a strictly binary tree.
„ Full binary tree: A binary tree of depth d is said to be a full binary tree if it has
exactly 2d
–1 nodes. An example of a full binary tree is shown in the following
figure.
Full Binary Tree
„ Complete binary tree: A binary tree in which all levels, except possibly the deepest
level, are completely filled and at the deepest level, all nodes are as far left as
possible. An example of a complete binary tree is shown in the following figure.
Complete Binary Tree 9.10 Solving Programming Problems Using Trees  ¤NIIT
Binary trees can be implemented by using arrays as well as linked lists, depending upon
the requirement. Both arrays and linked lists have their own advantages and
disadvantages.
Array Representation of Binary Trees
In this method, the nodes of a binary tree are represented as elements in an array. The
nodes stored in an array are accessible sequentially. The root node always lies at index 0.
Consider the binary tree with the nodes labeled from 0 to 6, as shown in the following
figure.
Binary Tree
In the preceding binary tree, the node labeled x will be stored at index x in the array.
Consider the array representation of the preceding binary tree, as shown in the following
figure.
Array Representation of a Binary Tree
For any node with index i, 0 < i < n (where n is the total number of nodes in the tree),
the following holds true:
„ Parent of i is at index (i – 1)/2.
„ Left child of i is at index 2i + 1. If 2i + 1 > n – 1 there is no left child.
„ Right child of i is at index 2i + 2. If 2i + 2 > n – 1 there is no right child.
Representing a Binary Tree ¤NIIT Solving Programming Problems Using Trees 9.11
Note
Linked Representation of Binary Tree
In this method, a linked list is used to represent a binary tree. In a linked representation of
a binary tree, you declare two classes:
„ Class Node: This class represents the structure of each node in a binary tree. A node
in a binary tree consists of three parts. They are as follows:
z Information: It refers to the information held by each node in a binary tree.
z Left child: It holds the reference of the left child of the node.
z Right child: It holds the reference of the right child of the node.
Consider the structure of a node in a linked binary tree, as shown in the following
figure.
Structure of a Node in a Linked Binary Tree
If a node does not have a left child or a right child or both, the respective left or right
child field(s) of that node point to NULL.
Refer to the following declaration of the Node class in C# and C++:
// Code in C#
class Node
{
public int info;
public Node lchild;
public Node rchild;
}9.12 Solving Programming Problems Using Trees  ¤NIIT
// Code in C++
class Node
{
public:
int info;
Node *lchild;
Node *rchild;
};
„ Class BinaryTree: This class implements various operations on a binary tree, such
as insert, delete, and traverse. The class also provides the declaration of the
variable/pointer root, which contains the address of the root node of the tree. Refer to
the following declaration of the BinaryTree class in C# and C++:
// Code in C#
class BinaryTree
{
public Node ROOT;
public BinaryTree()
{
ROOT = null;
}
public void insert(int element);
public void find(int element, ref Node  parent, refNode
currentNode);
public void inorder(ref Node ptr);
public void preorder(ref Node ptr);
public void postorder(ref Node ptr);
};
// Code in C++
class BinaryTree
{
public:
Node *ROOT;
BinaryTree()
{
ROOT = NULL;
} ¤NIIT Solving Programming Problems Using Trees 9.13
void insert(int element);
void find(int element, Node **parent,Node **currentNode);
void inorder(Node *ptr);
void preorder(Node *ptr);
void postorder(Node *ptr);
};
Consider the linked representation of a binary tree, as shown in the following figure.
Linked Representation of a Binary Tree 9.14 Solving Programming Problems Using Trees  ¤NIIT
Traversal of the nodes is one of the most common operations in a binary tree. Traversing
a tree refers to the process of visiting all the nodes of the tree once.
There are three ways in which you can traverse a binary tree. They are inorder, preorder,
and postorder traversal. The sequence of traversal in the three traversal techniques is
different. Consider the following binary tree.
Binary Tree
Now discuss the inorder, preorder, and postorder traversal by referring to the preceding
binary tree.
Inorder Traversal
The steps for traversing a binary tree in the inorder sequence are as follows:
1. Traverse the left subtree
2. Visit the root
3. Traverse the right subtree
For performing the inorder traversal of the given binary tree, you need to start at the root,
and first traverse each node’s left branch, then the node, and finally the node’s right
branch. This is a recursive process because each node’s left and right branch is a tree in
itself.
The root of the tree is A. Before visiting A, you must traverse the left subtree of A.
Therefore, you move to node B. Now, before visiting B, you must traverse the left subtree
of B. Therefore, move to node D. Now, before visiting D, you must traverse the left
subtree of node D. However, the left subtree of D is empty. Therefore, visit node D.
Traversing a Binary Tree ¤NIIT Solving Programming Problems Using Trees 9.15
After visiting node D, you must traverse the right subtree of node D. Therefore, you move
to node H. Before visiting H, you must traverse the left subtree of H. However, H does
not have a left subtree. Therefore, visit node H.
After visiting node H, you must traverse the right subtree of node H. The right subtree of
H is empty. Now the traversal of the left subtree of node B is complete. Therefore, visit
node B.
After visiting node B, you must traverse the right subtree of node B. Therefore, move to
node E. Because E does not have a left subtree, visit E. Node E does not have a right
subtree either. Now, the traversal of the left subtree of A is complete. Therefore, visit
node A.
After visiting node A, you must traverse the right subtree of node A. Therefore, move to
node C. Before visiting C, you must visit the left subtree of C. Therefore, move to node F.
F does not have a left subtree, so visit F. F does not have a right subtree either. At this
stage, the traversal of the left subtree of C is complete. Therefore, visit node C.
After visiting node C, you must traverse the right subtree of C. Therefore, move to node
G. Before, visiting node G, you must traverse the left subtree of node G. Therefore, move
to node I. I does not have a left subtree. Therefore, visit I.
After visiting I, you must traverse the right subtree of I. However, I does not have a right
subtree. The traversal of the left subtree of G is now complete. Therefore, visit node G. G
does not have a right subtree. At this stage, the traversal of the right subtree of C is
complete. Also, the traversal of the right subtree of A is complete.
Therefore, the inorder traversal sequence is as follows:
DHBEAFCIG 9.16 Solving Programming Problems Using Trees  ¤NIIT
The following figure depicts the sequence of traversal in the inorder traversal.
Inorder Traversal
The following is the algorithm for inorder traversal:
Algorithm: Inorder (root)
1. If (root = NULL):
a. Exit
2. Inorder (left child of root)   // Recursive call to Inorder for traversing the left
// subtree
3. Visit (root)
4. Inorder (right child of root) // Recursive call to Inorder for traversing the
// right subtree
Preorder Traversal
The steps for traversing a binary tree in the preorder sequence are as follows:
1. Visit the root
2. Traverse the left subtree
3. Traverse the right subtree
For a preorder traversal, you must begin with the root node. The root of the tree is A.
Therefore, visit node A. Now move to the left subtree of A. The root of the left subtree of
A is B. Hence, visit node B. Move to the left subtree of B, and visit its root D. Now D
does not have a left subtree. Therefore, move to its right subtree. The root of its right
subtree is H. Therefore, visit H. Now move to the right subtree of node B, and visit E.
This finishes the traversal of the root and its left subtree. Now, traverse the right subtree
of the root in a similar fashion. ¤NIIT Solving Programming Problems Using Trees 9.17
The preorder traversal sequence is as follows:
ABDHECFGI
The following figure depicts the sequence of traversal in the preorder traversal.
Preorder Traversal
The following is the algorithm for the preorder traversal:
Algorithm: Preorder (root)
1. If (root = NULL):
a. Exit
2. Visit (root)
3. Preorder (left child of root)   // Recursive call to Preorder for traversing
// the left subtree
4. Preorder (right child of root) // Recursive call to Preorder for traversing the
// right subtree
Postorder Traversal
The steps for traversing a binary tree in the postorder sequence are as follows:
1. Traverse the left subtree
2. Traverse the right subtree
3. Visit the root
For postorder traversal, the left and right subtree of a node are traversed first and then the
node itself. Therefore, begin by traversing the left subtree of the root node A. The root of
its left subtree is B. Therefore, move to node B.  9.18 Solving Programming Problems Using Trees  ¤NIIT
Just a minute:
From node B, you need to further move to its left subtree. The root of its left subtree is D.
Node D does not have a left subtree, but has a right subtree. Therefore, move to its right
subtree. The root of its right subtree, which is H, does not have a left and right subtree,
therefore H will be the first node to be visited.
After having visited H, the traversal of the right subtree of D is complete. Therefore, you
need to visit node D. Until now, the left subtree of node B has been traversed. Now you
need to traverse the right subtree of B before you visit B. The root of its right subtree is E,
which does not have left and right subtrees. Hence, visit E, and then visit B. The left
subtree of node A has been traversed. You now need to traverse its right subtree in a
similar fashion before you visit node A.
The postorder traversal sequence of the given tree is as follows:
HDEBFIGCA
The following figure depicts the sequence of traversal in the postorder traversal.
Postorder Traversal
In ___________ traversal method, the root is processed before traversing the left and
right subtrees.
Answer:
Preorder ¤NIIT Solving Programming Problems Using Trees 9.19
Consider a scenario of a cellular phone company that maintains the information of
millions of its customers spread across the world. Each customer is assigned a unique
identification number (id). Individual customer records can be accessed by referring to the
respective id. These ids need to be stored in a sorted manner in such a way so that you can
perform various transactions, such as search, insertion, and deletion, easily.
Which data structure will you use to solve this problem? If you use an array, you can
perform a faster search. However, insertion and deletion would be a cumbersome process
in that case. If you use a linked list, insertion and deletion will be fast. However, the
search operation will be very time consuming, especially if the data to be searched is
present near the end of the list.
In such a case, it would be good to have a data storage mechanism, which provides the
advantages of both arrays as well as linked lists. A special type of binary tree called a
binary search tree can be used in this case. A binary search tree matches the search speed
of arrays, and also offers efficient insertions and deletions as in the case of linked list.
A binary search tree is a binary tree in which the value of the left child of a node is always
less than the value of the node, and the value of the right child of a node is always greater
than the value of the node. Consider the binary search tree given in the following figure.
Binary Search Tree
The root node contains 52. All the nodes in the left subtree of the root have a value less
than 52. Similarly, all the nodes in the right subtree of the root node have values greater
than 52. The same holds true for all the other subtrees as well.
Implementing a Binary Search Tree
Defining a Binary Search Tree 9.20 Solving Programming Problems Using Trees  ¤NIIT
Note
Inorder traversal of a binary search tree gives you a sorted list of elements.
The search operation in a binary search tree refers to the process of searching for a
specific value in the tree.
To search for a particular value in a binary search tree, you need to perform the following
steps:
1. Make currentNode point to the root node
2. If currentNode is null:
a. Display “Not found”
b. Exit
3. Compare the value to be searched with the value of currentNode. Depending on the
result of the comparison, there can be three possibilities:
a. If the value is equal to the value of currentNode:
i. Display “Found”
ii. Exit
b. If the value is less than the value of currentNode:
i. Make currentNode point to its left child
ii. Go to step 2
c. If the value is greater than the value of currentNode:
i. Make currentNode point to its right child
ii. Go to step 2
In the preceding figure, let us suppose you want to search for a value 59. You begin the
search from the root node, 52. Compare 52 with 59. Because 59 > 52, move to the right
child of 52, that is 68. Compare 59 with 68. Because 59 < 68, move to the left child of 68,
that is 59. Again compare 59 with 59. The values are equal. This means that you have
found the node in the binary search tree.
From the preceding example, you can see that after every comparison, the number of
elements to be searched reduces to half. As a result, binary search trees provide quick
access to data.
Searching a Node in a Binary Search Tree ¤NIIT Solving Programming Problems Using Trees 9.21
Just a minute:
In a binary search tree, all values in the left subtree of a node are ______ than the
value of the node.
Answer:
smaller
The insert operation involves the insertion of a new node into a binary search tree. The
new node must be inserted in such a way that the keys remain properly ordered. Before
implementing an insert operation, you first need to check whether the tree is empty or not.
If the tree is empty, the new node to be inserted becomes the root of the tree. However, if
the tree is not empty, then you need to locate the position of the new node to be inserted
in the binary search tree. A new node is always inserted as a leaf node.
Consider a binary search tree, which is initially empty. Suppose you want to insert nodes
in a binary search tree in the following order:
52    36    68    24    44    72
The process of inserting a new node in a binary search tree is shown in the following
table.
Operation Decisions Taken Illustration
Insert 52 The tree is empty;
therefore, node 52
becomes the root.
Insert 36 Compare the value 36
with that of the root.
Because 36 < 52, insert 36
as the left child of 52.
Inserting Nodes in a Binary Search Tree 9.22 Solving Programming Problems Using Trees  ¤NIIT
Operation Decisions Taken Illustration
Insert 68 Compare the value 68
with that of the root.
Because 68 > 52, insert 68
as the right child of 52.
Insert 24 Compare the value 24
with that of the root.
Because 24 < 52, 24 will
be inserted in the left
subtree of the root.
However, the left subtree
of the root is not empty.
Therefore, move to the left
child of 52, which is 36.
Compare the value 24
with 36. Because 24 < 36,
insert 24 as the left child
of 36.
Insert 44 Compare the value 44
with that of the root.
Because 44 < 52, 44 will
be inserted in the left
subtree of the root.
However, the left subtree
of the root is not empty.
Therefore, move to the left
child of root, which is
node 36. Compare the
value 44 with 36. Because
44 > 36, insert 44 as the
right child of 36.
Inserting Nodes in a Binary Search Tree
The following is the algorithm to insert a node in a binary search tree:
1. Allocate memory for the new node.
2. Assign value to the data field of new node.
3. Make the left and right child of the new node point to NULL. ¤NIIT Solving Programming Problems Using Trees 9.23
4. Locate the node that will be the parent of the node to be inserted. Mark it as parent.
Execute the following steps to locate the parent of the new node to be inserted:
a. Mark the root node as currentNode
b. Make parent point to NULL
c. Repeat steps d, e, and f, until currentNode becomes NULL
d. Make parent point to currentNode
e. If the value of the new node is less than that of currentNode:
i. Make currentNode point to its left child
f. If the value of the new node is greater than that of currentNode:
i. Make currentNode point to its right child
5. If parent is NULL (Tree is empty):
a. Mark the new node as ROOT
b. Exit
6. If the value in the data field of the new node is less than that of parent:
a. Make the left child of parent point to the new node
b. Exit
7. If the value in the data field of the new node is greater than that of the parent:
a. Make the right child of parent point to the new node
b. Exit
Consider a binary search tree, as shown in the following figure.
Binary Search Tree Before Insert Operation 9.24 Solving Programming Problems Using Trees  ¤NIIT
Suppose you want to insert a node 55 in the given binary search tree. The process of
inserting the node 55 is shown in the following table.
Operation Illustration
Allocate memory and assign value
to the data field of the new node.
Make the left and right child field
of the new node point to NULL.
Locate the node that will be the
parent of the node to be inserted.
Mark it as parent. ¤NIIT Solving Programming Problems Using Trees 9.25
Operation Illustration
If the value in the data field of new
node is less than that of parent,
make the left child of parent point
to the new node.
Inserting a Node in a Binary Search Tree
The delete operation in a binary search tree refers to the process of deleting a specified
node from the tree. To delete a node from a binary search tree, you first need to locate the
node to be deleted and its parent node. Refer to the following algorithm to locate the node
to be deleted and its parent:
1. Make a variable/pointer currentNode point to the ROOT node.
2. Make a variable/pointer parent point to NULL.
3. Repeat steps a, b, and c until currentNode becomes NULL or the value of the node to
be searched becomes equal to that of currentNode:
a. Make parent point to currentNode.
b. If the value to be deleted is less than that of currentNode:
i. Make currentNode point to its left child.
c. If the value to be deleted is greater than that of currentNode:
i. Make currentNode point to its right child.
After executing the preceding algorithm, currentNode is positioned on the node to be
deleted and parent is positioned on its parent.
Deleting Nodes from a Binary Search Tree 9.26 Solving Programming Problems Using Trees  ¤NIIT
Note
After executing the preceding algorithm, if currentNode becomes NULL, then it means
that the node to be deleted does not exist.
Once you locate the node to be deleted and its parent, there can be three cases:
„ Case I – The node to be deleted is a leaf node: In this case, the left and right child
field of currentNode is NULL. Refer to the following algorithm to implement a
delete operation on a leaf node:
1. If currentNode is the root node:  // If parent is NULL
a. Make ROOT point to NULL.
b. Go to step 4.
2. If currentNode is the left child of parent:
a. Make the left child field of parent point to NULL.
b. Go to step 4.
3. If the currentNode is the right child of parent:
a. Make the right child field of parent point to NULL.
b. Go to step 4.
4. Release the memory for currentNode.
Refer to the binary search tree, as shown in the following figure.
Binary Search Tree Before Deleting the Leaf Node ¤NIIT Solving Programming Problems Using Trees 9.27
Suppose you want to delete node 75. The process of deleting node 75 from the binary
search tree is shown in the following table.
Operations Illustration
Locate the node to be
deleted. Mark it as
currentNode and its parent
as parent.
If currentNode is the left
child of parent, make the
left child field of parent
point to NULL. 9.28 Solving Programming Problems Using Trees  ¤NIIT
Operations Illustration
Release the memory for
currentNode.
Deleting a Leaf Node in a Binary Search Tree
„ Case II – The node to be deleted has one child (left or right): In this case,
currentNode can either have a left child or a right child. Mark the only child of
currentNode as child. To delete currentNode, the left/right child field of parent is
linked with the left/right child of currentNode. Refer to the following algorithm to
implement a delete operation on a node having one child:
1. If currentNode has a left child:
a. Mark the left child of currentNode as child.
b. Go to step 3.
2. If currentNode has a right child:
a. Mark the right child of currentNode as child.
b. Go to step3.
3. If currentNode is the root node:
a. Mark child as ROOT.
b. Go to step 6.
4. If currentNode is the left child of parent:
a. Make left child field of parent point to child.
b. Go to step 6.
5. If currentNode is the right child of parent:
a. Make right child field of parent point to child.
b. Go to step 6.
6. Release the memory for currentNode. ¤NIIT Solving Programming Problems Using Trees 9.29
Consider the binary search tree, as shown in the following figure.
Binary Search Tree Before Deleting a Node Having One Child 9.30 Solving Programming Problems Using Trees  ¤NIIT
Suppose you want to delete node 80. The process of deleting node 80 is shown in the
following table.
Operation Illustration
Locate the node to be
deleted. Mark it as
currentNode and its parent
as parent. If currentNode
has a left child, mark the left
child of currentNode as
child.
If currentNode is the right
child of parent, make right
child field of parent point to
child.¤NIIT Solving Programming Problems Using Trees 9.31
Operation Illustration
Release the memory for
currentNode.
Deleting a Node Having One Child in a Binary Search Tree
„ Case III – The node to be deleted has two children: In this case, currentNode has
two children. To delete currentNode from the tree, you need to replace it with its
inorder successor. The inorder successor of a node x refers to the next node in
sequence of x that comes in the inorder traversal. To locate the inorder successor of a
node, you need to locate the left most node in its right subtree.
The following algorithm implements the delete operation on a node having two
children:
1. Locate the inorder successor of currentNode. Mark it as Inorder_suc. Execute
the following steps to locate Inorder_suc:
a. Mark the right child of currentNode as Inorder_suc.
b. Repeat until the left child of inorder_suc becomes null:
i. Make Inorder_suc point to its left child.
2. Replace the information held by currentNode with that of Inorder_suc.
3. If the node marked Inorder_suc is a leaf node:
a. Delete the node marked Inorder_suc by using the algorithm for Case I.
4. If the node marked Inorder_suc has one child:
a. Delete the node marked Inorder_suc by using the algorithm for Case II.  9.32 Solving Programming Problems Using Trees  ¤NIIT
Because the node marked inorder_suc is the leftmost node of the right subtree of
currentNode, it cannot have a left child. Therefore, the node marked Inorder_suc has at
the most one child. This means that the node marked Inorder_suc can be deleted by
executing the algorithm that was developed for deleting a leaf node, or the one that was
developed for deleting a node with one child.
Consider the following binary search tree.
Binary Search Tree Before Deleting a Node Having Two Children ¤NIIT Solving Programming Problems Using Trees 9.33
Suppose you want to delete node 72. The process of deleting node 72 is shown in the
following table.
Operation Illustration
Locate the node to be deleted. Mark
it as currentNode. Locate the
inorder successor of currentNode.
The inorder successor of
currentNode will be the leftmost
node in the right subtree of
currentNode. Mark the inorder
successor of currentNode as
Inorder_suc.  9.34 Solving Programming Problems Using Trees  ¤NIIT
Operation Illustration
Replace the information held by
currentNode with that of
Inorder_suc.
The node marked Inorder_suc is a
leaf node. Therefore, delete it by
using the algorithm for deleting a
leaf node.
Deleting a Node Having Two Children in a Binary Search Tree ¤NIIT Solving Programming Problems Using Trees 9.35
Problem Statement
Write a program to implement insert and traverse operations on a binary search tree that
contains the words in a dictionary.
Solution
The code to implement various operations on a binary search tree in C# and C++ is as
follows:
// Code in C#
using System;
using System.Text;
namespace BinarySearchTree
{
/* The Node class consists of three data members, the information,
reference to the right child, and reference to the left child. */
class Node
{
public string info;
public Node lchild;
public Node rchild;
public Node(string i, Node l, Node r) /* Constructor for the
Node class */
{
info = i;
lchild = l;
rchild = r;
}
}
class BinaryTree
{
public Node ROOT;
public BinaryTree()
{
ROOT = null; /* Initializing ROOT to null */
}
public void insert(string element) /* Inserts a Node in the
Binary Search Tree */
{
Node tmp, parent = null, currentNode = null;
find(element, ref parent, ref currentNode);
if (currentNode != null) /* Checks if the node to be
inserted is already present or not */
Activity: Implementing a Binary Search Tree 9.36 Solving Programming Problems Using Trees  ¤NIIT
{
Console.WriteLine(“Duplicates words not allowed”);
return;
}
else /* If the specified Node is not present */
{
tmp = new Node(element, null, null); /* Creates a
Node */
if (parent == null) /* If the tree is empty */
ROOT = tmp;
else
if (String.Compare(element, parent.info) < 0)
parent.lchild = tmp;
else
parent.rchild = tmp;
}
}
public void find(string element, ref Node parent, ref Node
currentNode)
{
/* This function finds a given element in the tree and
returns a variable containing the address of the
corresponding node. It also returns a variable
containing the address of the parent of the node. */
currentNode = ROOT;
parent = null;
while ((currentNode != null) && (currentNode.info !=
element))
{
parent = currentNode;
if (String.Compare(element, currentNode.info) < 0)
currentNode = currentNode.lchild;
else
currentNode = currentNode.rchild;
}
}
public void inorder(Node ptr) /* Performs the inorder
traversal of the tree */
{
if (ROOT == null)
{
Console.WriteLine(“Tree is empty”);
return;
}
if (ptr != null)
{
inorder(ptr.lchild);
Console.Write(ptr.info + ”   “);
inorder(ptr.rchild);
}
}
public void preorder(Node ptr) /* Performs the preorder
traversal of the tree */ ¤NIIT Solving Programming Problems Using Trees 9.37
{
if (ROOT == null)
{
Console.WriteLine(“Tree is empty”);
return;
}
if (ptr != null)
{
Console.Write(ptr.info + ”   “);
preorder(ptr.lchild);
preorder(ptr.rchild);
}
}
public void postorder(Node ptr) /* Performs the postorder
traversal of the tree */
{
if (ROOT == null)
{
Console.WriteLine(“Tree is empty”);
return;
}
if (ptr != null)
{
postorder(ptr.lchild);
postorder(ptr.rchild);
Console.Write(ptr.info + ”   “);
}
}
static void Main(string[] args)
{
BinaryTree b = new BinaryTree();
while (true)
{
Console.WriteLine(“\nMenu”);
Console.WriteLine(“1. Implement insert operation”);
Console.WriteLine(“2. Perform inorder traversal”);
Console.WriteLine(“3. Perform preorder traversal”);
Console.WriteLine(“4. Perform postorder traversal”);
Console.WriteLine(“5. Exit”);
Console.Write(“\nEnter your choice (1-5): “);
char ch = Convert.ToChar(Console.ReadLine());
Console.WriteLine();
switch (ch)
{
case ‘1’:
{
Console.Write(“Enter a word: “);
string word = Console.ReadLine();
b.insert(word);
}
break;
case ‘2’:
{ 9.38 Solving Programming Problems Using Trees  ¤NIIT
b.inorder(b.ROOT);
}
break;
case ‘3’:
{
b.preorder(b.ROOT);
}
break;
case ‘4’:
{
b.postorder(b.ROOT);
}
break;
case ‘5’:
return;
default:
{
Console.WriteLine(“Invalid option”);
break;
}
}
}
}
}
}
// Code in C++
#include<iostream.h>
#include<string.h>
class Node
{
/* The Node class consists of three data members, the
information, reference to the right child, and reference to the left
child. */
public:
char info[50];
Node *lchild;
Node *rchild;
Node(char i[20],Node *l,Node *r)
{
strcpy (info, i);
lchild = l;
rchild = r;
} /* Constructor for the Node class */
};
class BinaryTree
{
public:
Node *ROOT;
BinaryTree();
void insert(char element[20]);
void find(char element[20], Node **parent,Node **location); ¤NIIT Solving Programming Problems Using Trees 9.39
void inorder(Node *ptr);
void preorder(Node *ptr);
void postorder(Node *ptr);
};
BinaryTree :: BinaryTree()
{
ROOT=NULL; /* Initializing ROOT to null */
}
void BinaryTree :: insert(char element[50]) /* Inserts a Node in the
Binary Search Tree */
{
Node *tmp, *parent,*currentNode;
find(element,&parent,&currentNode);
if(currentNode!=NULL) /* Checks if the node to be  inserted is
already present or not */
{
cout<<“\nDuplicate words not allowed”;
return;
}
else /* If the specified Node is not present */
{
tmp=new Node(element,NULL,NULL); // creates a Node
if(parent==NULL) /* If the tree is empty */
ROOT=tmp;
else
if(strcmp(element,parent->info)<0)
parent->lchild=tmp;
else
parent->rchild=tmp;
}
}
void BinaryTree :: find(char element[50],Node **parent, Node
**currentNode)
{
/* This function finds a given element in the tree and
returns a variable containing the address of the
corresponding node. It also returns a variable
containing the address of the parent of the node. */
*currentNode = ROOT;
*parent = NULL;
while ((*currentNode != NULL) && (strcmp((*currentNode)
->info,element) != 0))
{
*parent = *currentNode;
if (strcmp(element,(*currentNode)->info)<0)
*currentNode = (*currentNode)->lchild;
else
*currentNode = (*currentNode)->rchild;
}
}9.40 Solving Programming Problems Using Trees  ¤NIIT
void BinaryTree :: inorder(Node *ptr) /* Performs the inorder
traversal of the tree */
{
if(ROOT==NULL)
{
cout<<“Tree is empty”;
return;
}
if(ptr!=NULL)
{
inorder(ptr->lchild);
cout<<ptr->info<<”   “;
inorder(ptr->rchild);
}

}
void BinaryTree :: preorder(Node *ptr) /* Performs the preorder
traversal of the tree */
{
if(ROOT==NULL)
{
cout<<“Tree is empty”;
return;
}
if(ptr!=NULL)
{
cout<<ptr->info<<”   “;
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}
void BinaryTree :: postorder(Node *ptr) /* Performs the postorder
traversal of the tree */
{
if(ROOT==NULL)
{
cout<<“Tree is empty”;
return;
}
if(ptr!=NULL)
{
postorder(ptr->lchild);
postorder(ptr->rchild);
cout<<ptr->info<<”   “;
}
}
void main()
{
BinaryTree b;
char ch,word[50];
int num;
while(1)
{
cout<<“\nMenu”;;
cout<<“\n1. Implement insert operation”<<endl; ¤NIIT Solving Programming Problems Using Trees 9.41
cout<<“2. Perform inorder traversal”<<endl;
cout<<“3. Perform preorder traversal”<<endl;
cout<<“4. Perform postorder traversal”<<endl;
cout<<“5. Exit”<<endl;
cout<<“\nEnter your choice (1-5): “;
cin>>ch;
switch(ch)
{
case ‘1’:
{

cout<<“\nEnter a word: “;
cin>>word;
b.insert(word);
}
break;
case ‘2’:
{
cout<<“\n”;
b.inorder(b.ROOT);
cout<<“\n”;
}
break;
case ‘3’:
{
cout<<“\n”;
b.preorder(b.ROOT);
cout<<“\n”;
}
break;
case ‘4’:
{;
cout<<“\n”;
b.postorder(b.ROOT);
cout<<“\n”;
}
break;
case ‘5’:
{
exit(0);
}
break;
default:
{
cout<<“Invalid Option.”<<endl;
break;
}
}
}
}9.42 Solving Programming Problems Using Trees  ¤NIIT
Binary search trees offer a large number of applications in various fields. Some of the
common applications of binary search trees include indexing, message encoding, and
arithmetic expression evaluation. This section discusses these applications in detail.
Data on disk files is usually organized as records. A record is made up of several fields,
one of which is the key field. This key field is used to uniquely identify each record in a
file. To access a particular record, you first need to search the record from the file.
One way to search the record is to sequentially start from the first record in the file till
you reach the desired record. This is known as sequential access. In this case, if the record
is present near the end of file, the search process can be very time consuming.
Therefore, a better approach is to implement a mechanism in which a record can be
accessed by specifying its respective key field. This can be done by implementing a table
called index. Index contains all key fields of each record along with the offset positions of
the beginning of the records in the file. Refer to the following table representing an index.
Key Field Offset
24 0
35 200
36 400
40 600
43 800
44 1000
52 1200
55 1400
59 1600
68 1800
72 2000
Index
Applications of Trees
Indexing ¤NIIT Solving Programming Problems Using Trees 9.43
The index should be sorted in ascending order of the key field values. To access a
particular record, you need to specify its key value. If the key value is present in the index
table, the corresponding entry of the offset position for that record is retrieved. After you
know the offset position of a record, you can directly access that record from the file.
Suppose you want to access a record having key field 55. To do so, you need to search the
index for this key field, and retrieve the value of the offset position for that record. The
offset position of the record with key value 55 is 1400. Now you can directly access the
record from the file starting from this offset position. This access method is called
indexed access.
The index is usually written to the disk along with the data file so that it can be used as
and when required to access data. When a new record is inserted or deleted from a file,
the index gets updated simultaneously.
When a file is opened for performing insertion, deletion, or search operations, the index is
loaded in the main memory. To remain in the main memory, the index must be stored in
some data structure. The choice of the data structure to store the index is a critical
decision to make, in order to allow efficient insertion, deletion, and search from the index.
If you use an array to store the index, you can perform a quick search for the key values.
However, the insert and delete operation in an array is complex and time consuming.
If you use a linked list to store the index, you can perform the insert and delete operations
quickly. However, searching for a particular key value can be time consuming, especially
if the key value to be searched is present near the end of the list.
Therefore, a better approach would be to implement a binary search tree to store the index
because it provides the advantage of both arrays and linked lists.
While working with records of a file, the index is loaded from the hard disk into the
memory in the form of a binary search tree. When you want to access a particular record
from a file, the corresponding key field of the record is searched in the binary search tree,
and its offset value is retrieved.  9.44 Solving Programming Problems Using Trees  ¤NIIT
Refer to the binary search tree, as shown in the following figure storing all the key fields
and offset values.
Index Implemented in the Form of a Binary Search Tree
Consider the problem of encoding a message consisting of a sequence of characters into a
binary message. This is routinely done in a computer system by using various encoding
schemes. The most common of these encoding schemes is ASCII that uses 8 bits to store
each character. In the ASCII scheme, the character A is represented as 01000001.
This scheme however, is highly inefficient. This is because it uses the same number of
bits to represent all the characters. Therefore, a character such as “e”, which occurs very
frequently in messages, uses the same number of bits as “q”, which occurs much less
frequently. As a result, the messages are very long.
Consider the following message, which is composed of the combination of four symbols,
A, B, C, and D:
ABCADACBCACADAA
Symbol A is used most frequently as compared to symbols B, C, and D. The frequency of
occurrence of symbol C is higher than that of B and D, but less than A.
Suppose, three bits are used to store each symbol, as follows:
1. A – 000
2. B – 001
Encoding Messages Using a Huffman Tree ¤NIIT Solving Programming Problems Using Trees 9.45
3. C – 100
4. D – 101
Therefore, the message can be represented in the form of bits in the following manner:
000001100000101000001100100000100000101000000
The total number of bits occupied by this message is 45.
Messages need to be short and compact, especially when sent over a network. This
increases the speed at which data is transferred.
To reduce the length of messages, it would be helpful to use an encoding scheme that
assigns lesser number of bits to characters that occur more frequently as compared to
those, which occur less frequently. This makes the length of the message short.
However, there is again a problem associated with this approach. If the number of bits in
a message is not fixed, you would need to introduce some separator character to indicate
the end of each character.
This problem can be overcome by using an encoding scheme with a prefix property. This
means that the binary code of any character is not a prefix of the binary code of any other
character.
Now consider the following codes assigned to the four characters contained in the
message:
1. A – 0
2. B – 110
3. C – 10
4. D – 111
In the preceding coding scheme, different number of bits is assigned to the characters.
Also, the code of any of the four characters is not a prefix of the code of any other
character.
Now refer to the message given in the preceding example. After assigning variable bit
sequences to the symbols, the final encoded message appears, as follows:
011010011101011010010011100
In the preceding encoded message, the total numbers of bits have been reduced to 27.
Therefore, by using a variable length encoding scheme with a prefix property, the length
of a message can be significantly reduced. But how do you generate such a code. A
special type of tree called Huffman tree can be used to generate this code. 9.46 Solving Programming Problems Using Trees  ¤NIIT
In a Huffman tree, each leaf node is labeled with a symbol. A binary code can be assigned
to each symbol as follows:
„ Associate “0” to the path from a node to its left child.
„ Associate “1” to the path from a node to its right child.
The code for a symbol is obtained by following the path from the root to the leaf node
containing the symbol. The code would definitely have a prefix property because a leaf
node cannot appear on a path to another leaf node.
Another property of a Huffman tree is that it places the most frequently accessed elements
closer towards the root. This helps in assigning short codes to the characters that appear
frequently.
The following figure depicts the Huffman tree corresponding to the variable length
character codes used in the preceding example.
Huffman Tree
As you can see, the symbol A is closest to the root and is assigned the code 0. After A,
symbol C is the most frequently used. Therefore, C appears at a level lower than A and is
assigned the code 10. The frequency of occurrence of B and D is the same. Therefore,
they appear at the same level. ¤NIIT Solving Programming Problems Using Trees 9.47
Just a minute:
State one advantage of a Huffman tree.
Answer:
A Huffman tree helps assign variable length codes to the characters in a message. It
also ensures that the character codes have the prefix property.
Binary trees can be used to represent various algebraic expressions. This approach is
implemented by various compilers to obtain a form of an arithmetic expression, which
can be evaluated efficiently.
When an arithmetic expression is represented in the form of a binary tree, all the internal
nodes are labeled by operators and all the leaf nodes are labeled by operands. Refer to the
following figure that represents an arithmetic expression in the form of a binary tree.
Binary Tree Representing Arithmetic Expression
You can perform different traversals on such a binary tree to produce different types of
notations of the algebraic expressions. For example, the inorder traversal produces infix
notation. Similarly, the preorder and postorder traversal produces prefix and postfix
notations, respectively. Following is the infix, prefix, and postfix notation for the
preceding binary tree:
Infix notation: (a + b) × c – (d + e) × f
Prefix notation: – × + abc × + def
Arithmetic Expression Evaluation 9.48 Solving Programming Problems Using Trees  ¤NIIT
Postfix notation: ab + c × de + f × –
A heap tree or heap is defined as a complete binary tree of n nodes such that the value of
each node is less than or equal to its parent.
This means that the root node of the heap contains the largest key. The following figure
depicts the structure of a heap.
A Heap Structure
The heap depicted in the preceding figure is a max heap because every parent node in the
heap has a value greater than or equal to the value of its child nodes. However, if every
parent node has a value less than or equal to the value of its child nodes, then it is called a
min heap.
An efficient sorting algorithm called heap sort can be used to sort data stored in a heap.
Therefore, if you have to sort data stored in an array by using heap sort, you need to first
formulate a method to represent the array elements in the form of a binary tree, and then
convert the binary tree into a heap.
Sorting Data by Using a Heap Tree ¤NIIT Solving Programming Problems Using Trees 9.49
Representing the Array Elements as a Binary Tree
As a part of the sorting process, you first need to represent the unsorted list in the form of
a binary tree. Suppose you number the nodes in a binary tree from 0 to n – 1, as shown in
the following figure.
The Representation of a Heap Tree
The number associated with each node represents the index of the array where the number
is stored.
To understand this concept, consider the following unsorted list stored in an array.
Unsorted List Stored in an Array
You can represent this list of items in the form of a binary tree, as shown in the following
figure.
The Tree Representation of the Elements in an Array  9.50 Solving Programming Problems Using Trees  ¤NIIT
Here, the location of the root, left child, and right child of any node is determined with the
help of the following formulas:
„ Parent of a node at index i is at index (i – 1)/2.
„ Left child of a node at index i is at index 2i + 1. If 2i + 1 > n – 1 there is no left child.
„ Right child of a node at index i is at index 2i + 2. If 2i + 2 > n – 1 there is no right
child.
Converting a Binary Tree into a Heap
After data has been represented as a binary tree, you need to convert the binary tree into a
heap. In other words, you need to build a heap of the given data. Once the heap is built,
you can apply the heap sort algorithm.
To understand the process of building a heap, consider the following unsorted list stored
in an array.
Unsorted List Stored in an Array
The following is the binary tree representation of the preceding array.
Binary Tree Representation of an Array
To convert the preceding binary tree into a heap, you need to perform the following steps:
1. Start with the parent of the last node in the list. The parent of the last node is at
index 2.  ¤NIIT Solving Programming Problems Using Trees 9.51
2. Compare the value of node 2 with the value of its greater child. Here, the greater
child of node 2 is node 6. Node 2 has a value smaller than node 6. Therefore, swap
the values of the two nodes, as shown in the following figure.
Swap 40 with 95
3. Compare the value of node 1 with the value of its greater child. Here, the greater
child of node 1 is node 3. Node 1 has a value greater than node 3. Therefore,
swapping is not required.
4. Compare the value of node 0 with the value of its greater child. Here, the greater
child of node 0 is node 2. Node 0 has a value smaller than node 2. Therefore, swap
the values of the two nodes, as shown in the following figure.
Swap 25 with 95 9.52 Solving Programming Problems Using Trees  ¤NIIT
5. Now, compare the value of node 2 with the value of its greater child. Here, the
greater child of node 2 is node 6. Node 2 has a value smaller than node 6. Therefore,
swap the values of the two nodes, as shown in the following figure.
Swap 25 with 80
The tree has now been converted into a heap.
The following is the algorithm for converting a binary tree into a heap:
1. Set i = (n – 1)/2  // i is the index of the parent of the last node
2. Set j = 2i + 1  // j is the left child of node at index i
3. Let heap = False  // False indicates that initially the tree is not a heap
4. Compare the value at index j with the value of its sibling at index j + 1:  // If j + 1
// exists
a. If A[j + 1] > A[j]:
b. j = j + 1  // j now contains the index of the greater of the two siblings
5. If A[j] > A[(j – 1)/2]:  // If value at index j is greater than its parent
Swap A[j] with A[(j – 1)/2]   // Swap the value of A[j] with that of its parent
j = 2j + 1                                // 2j + 1 gives the index of the left child of j
Else
heap = True    // By moving down the tree starting from i and
// pushing the entries upwards, we have found a value which
// greater than the greater of its two children. This indicates
// that the tree is now a heap.
6. If ((j < n) or (heap = False)), repeat step 4, 5, and 6
7. Decrement i by 1
8. If (i  > 0), repeat steps 2 through 8 ¤NIIT Solving Programming Problems Using Trees 9.53
Implementing Heap Sort Algorithm
After the list is organized in a heap, you need to perform the following steps to sort the
list:
1. Replace the value of the root node with the value of the last node in the heap tree, as
shown in the following figure.
Interchanging the First Node with the Last Node
This is because the element at the root node contains the greatest value and should
therefore be placed at the end of the list.
The following figure depicts the array representation of the given heap.
Array Representation
The greatest element has reached its correct position in the list. Therefore, you will
now sort the remaining elements. 9.54 Solving Programming Problems Using Trees  ¤NIIT
2. Rearrange the remaining elements in the tree to covert it into a heap. The following
figure depicts the resultant heap structure.
Heap
3. Replace the value of the root node with the value of the last node of the heap, as
shown in the following figure.
Interchanging the Root Node with Last Node
The following figure depicts the array representation of the heap structure.
Array Representation of the Heap
The second largest element has now reached its correct position in the list. Therefore,
you will now sort the remaining five elements. ¤NIIT Solving Programming Problems Using Trees 9.55
4. Rearrange the elements in the tree to create a heap. The following figure depicts the
resultant heap structure.
Heap
5. Replace the root node with the last node of the heap, as shown in the following
figure.
Interchanging the Root Node with Last Node
The following figure depicts the array representation of the given heap structure.
Array Representation of the Heap
The third largest element has now reached its correct position in the list. Therefore, you
will now sort the remaining four elements.
To sort the remaining four elements, you will repeat the preceding process, until all the
elements in the list are sorted. 9.56 Solving Programming Problems Using Trees  ¤NIIT
Note
Note
Just a minute:
The algorithm for heap sort is as follows:
1. Set last = n – 1.
2. Convert the list arr[0] to arr[last] into a heap.
3. Swap arr[0] with arr[last].
4. Decrement last by 1.
5. If last > 0, go to step 2.
For sorting a list in descending order, a min heap must be used.
At the end of each pass in heap sort, one element reaches its correct position.
Therefore, if there are a total of n elements, n passes are required to sort the list. The
maximum number of comparisons performed in each pass is of the order log n.
Therefore, the worst case efficiency of heap sort is of the order O(n log n).
You may recall that the worst case efficiency of quick sort is O(n2
). This means that the
worst case efficiency of heap sort is much better than the worst case efficiency of quick
sort.
A min heap is used to sort the list in _______________ order.
Answer:
Descending ¤NIIT Solving Programming Problems Using Trees 9.57
1. A binary tree is a data structure used to represent data that have:
a. A linked relationship between them
b. Hierarchical relationship between them
c. No relationships between them
d. Networked relationship between them
2. In a complete binary tree of depth 10, level 3 will have __________ nodes.
a. 3
b. 6
c. 8
d. 9
3. In the ___________ traversal technique, a node is visited after traversing its left and
right subtrees.
a. inorder
b. postorder
c. preorder
d. binary
4. You need to store the details of all the students in a university in such a manner so
that you can perform fast insert, delete, and search operations on data. Select an
appropriate data structure for this purpose.
a. Linked list
b. Binary search tree
c. Binary tree
d. Arrays
5. Briefly discuss the delete operation of a node having two children from a binary
search tree.
6. How is a binary search tree useful in implementing indexing?
Practice Questions 9.58 Solving Programming Problems Using Trees  ¤NIIT
In this chapter, you learned that:
„ A tree is a nonlinear data structure that represents a hierarchical relationship among
the various data elements.
„ A binary tree is a specific type of tree in which each node can have a maximum of
two children.
„ Binary trees can be implemented by using arrays as well as linked lists, depending
upon the requirement.
„ Traversal of a tree is the process of visiting all the nodes of the tree once. There are
three types of traversals, namely inorder, preorder, and postorder traversal.
„ Binary search tree is a binary tree in which the value of the left child of a node is
always less than the value of the node, and the value of the right child of a node is
greater than the value of the node.
„ Inserting a node in a binary search tree requires you to first locate the appropriate
position for the node to be inserted.
„ You need to check for the following three cases before deleting a node from a binary
search tree:
z If the node to be deleted is the leaf node
z If the node to be deleted has one child (left or right)
z If the node to be deleted has two children
„ Binary search trees offer large number of applications in various fields. Some of
them are as follows:
z Indexing
z Encoding messages using Huffman tree
z Arithmetic expression evaluation
z Sorting data by using heap tree
Summary ¤NIIT Solving Programming Problems Using Trees 9.59
Exercise 1
You are given a program that implements the insert and traverse operations on a binary
search tree, where each node in the tree contains a dictionary word. Extend the given
program to include the functionality for deleting a node from the binary search tree.
Refer to the following partial code in C# and C++:
// Code in C#
using System;
using System.Text;
namespace BinarySearchTree
{
/* The Node class consists of three data members, the information,
reference to the right child, and reference to the left child. */
class Node
{
public string info;
public Node lchild;
public Node rchild;
public Node(string i, Node l, Node r) /* Constructor for the
Node class */
{
info = i;
lchild = l;
rchild = r;
}
}
class BinaryTree
{
public Node ROOT;
public BinaryTree()
{
ROOT = null; /* Initializing ROOT to null */
}
public void insert(string element) /* Inserts a Node in the
Binary Search Tree */
{
Node tmp, parent = null, currentNode = null;
find(element, ref parent, ref currentNode);
if (currentNode != null) /* Checks if the node to be
inserted is already present or not */
{
Console.WriteLine(“Duplicates words not allowed”);
return;
}
Exercises 9.60 Solving Programming Problems Using Trees  ¤NIIT
else /* If the specified Node is not present */
{
tmp = new Node(element, null, null); /* Creates a
Node */
if (parent == null) /* If the tree is empty */
ROOT = tmp;
else
if (String.Compare(element, parent.info) < 0)
parent.lchild = tmp;
else
parent.rchild = tmp;
}
}
public void find(string element, ref Node parent, ref Node
currentNode)
{
/* This function finds a given element in the tree and
returns a variable containing the address of the
corresponding node. It also returns a variable
containing the address of the parent of the node. */
currentNode = ROOT;
parent = null;
while ((currentNode != null) && (currentNode.info !=
element))
{
parent = currentNode;
if (String.Compare(element, currentNode.info) < 0)
currentNode = currentNode.lchild;
else
currentNode = currentNode.rchild;
}
}
public void inorder(Node ptr) /* Performs the inorder
traversal of the tree */
{
if (ROOT == null)
{
Console.WriteLine(“Tree is empty”);
return;
}
if (ptr != null)
{
inorder(ptr.lchild);
Console.Write(ptr.info + ”   “);
inorder(ptr.rchild);
}
}
public void preorder(Node ptr) /* Performs the preorder
traversal of the tree */
{
if (ROOT == null)
{ ¤NIIT Solving Programming Problems Using Trees 9.61
Console.WriteLine(“Tree is empty”);
return;
}
if (ptr != null)
{
Console.Write(ptr.info + ”   “);
preorder(ptr.lchild);
preorder(ptr.rchild);
}
}
public void postorder(Node ptr) /* Performs the postorder
traversal of the tree */
{
if (ROOT == null)
{
Console.WriteLine(“Tree is empty”);
return;
}
if (ptr != null)
{
postorder(ptr.lchild);
postorder(ptr.rchild);
Console.Write(ptr.info + ”   “);
}
}
static void Main(string[] args)
{
BinaryTree b = new BinaryTree();
while (true)
{
Console.WriteLine(“\nMenu”);
Console.WriteLine(“1. Implement insert operation”);
Console.WriteLine(“2. Perform inorder traversal”);
Console.WriteLine(“3. Perform preorder traversal”);
Console.WriteLine(“4. Perform postorder traversal”);
Console.WriteLine(“5. Exit”);
Console.Write(“\nEnter your choice (1-5): “);
char ch = Convert.ToChar(Console.ReadLine());
Console.WriteLine();
switch (ch)
{
case ‘1’:
{
Console.Write(“Enter a word: “);
string word = Console.ReadLine();
b.insert(word);
}
break;
case ‘2’:
{
b.inorder(b.ROOT);
}
break; 9.62 Solving Programming Problems Using Trees  ¤NIIT
case ‘3’:
{
b.preorder(b.ROOT);
}
break;
case ‘4’:
{
b.postorder(b.ROOT);
}
break;
case ‘5’:
return;
default:
{
Console.WriteLine(“Invalid option”);
break;
}
}
}
}
}
}
// Code in C++
#include<iostream.h>
#include<string.h>
class Node
{
/* A Node class consists of three data elements, the
information, reference to the right child, and reference to the left
child. */
public:
char info[50];
Node *lchild;
Node *rchild;
Node(char i[20],Node *l,Node *r)
{
strcpy (info, i);
lchild = l;
rchild = r;
} /* Constructor for the Node class */
};
class BinaryTree
{
public:
Node *ROOT;
BinaryTree();
void insert(char element[20]);
void find(char element[20], Node **parent,Node **location);
void inorder(Node *ptr);
void preorder(Node *ptr);
void postorder(Node *ptr);
};¤NIIT Solving Programming Problems Using Trees 9.63
BinaryTree :: BinaryTree()
{
ROOT=NULL; /* Initializing ROOT to null */
}
void BinaryTree :: insert(char element[50]) /* Inserts a Node in the
Binary Search Tree */
{
Node *tmp, *parent,*currentNode;
find(element,&parent,&currentNode);
if(currentNode!=NULL) /* Checks if the node to be inserted is already
present or not */
{
cout<<“\nDuplicate words not allowed”;
return;
}
else /* If the specified Node is not present */
{
tmp=new Node(element,NULL,NULL); // Creates a Node
if(parent==NULL) /* If the tree is empty */
ROOT=tmp;
else
if(strcmp(element,parent->info)<0)
parent->lchild=tmp;
else
parent->rchild=tmp;
}
}
void BinaryTree :: find(char element[50],Node **parent, Node
**currentNode)
{
/* This function finds a given element in the tree and
returns a variable containing the address of the
corresponding node. It also returns a variable
containing the address of the parent of the node. */
*currentNode = ROOT;
*parent = NULL;
while ((*currentNode != NULL) && (strcmp((*currentNode)
->info,element) != 0))
{
*parent = *currentNode;
if (strcmp(element,(*currentNode)->info)<0)
*currentNode = (*currentNode)->lchild;
else
*currentNode = (*currentNode)->rchild;
}
}9.64 Solving Programming Problems Using Trees  ¤NIIT
void BinaryTree :: inorder(Node *ptr) /* Performs the inorder
traversal of the tree */
{
if(ROOT==NULL)
{
cout<<“Tree is empty”;
return;
}
if(ptr!=NULL)
{
inorder(ptr->lchild);
cout<<ptr->info<<”   “;
inorder(ptr->rchild);
}

}
void BinaryTree :: preorder(Node *ptr) /* Performs the preorder
traversal of the tree */
{
if(ROOT==NULL)
{
cout<<“Tree is empty”;
return;
}
if(ptr!=NULL)
{
cout<<ptr->info<<”   “;
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}
void BinaryTree :: postorder(Node *ptr) /* Performs the postorder
traversal of the tree */
{
if(ROOT==NULL)
{
cout<<“Tree is empty”;
return;
}
if(ptr!=NULL)
{
postorder(ptr->lchild);
postorder(ptr->rchild);
cout<<ptr->info<<”   “;
}
}
void main()
{
BinaryTree b;
char ch,word[50];
int num;
while(1)
{
cout<<“\nMenu”;; ¤NIIT Solving Programming Problems Using Trees 9.65
cout<<“\n1. Implement insert operation”<<endl;
cout<<“2. Perform inorder traversal”<<endl;
cout<<“3. Perform preorder traversal”<<endl;
cout<<“4. Perform postorder traversal”<<endl;
cout<<“5. Exit”<<endl;
cout<<“\nEnter your choice (1-5): “;
cin>>ch;
switch(ch)
{
case ‘1’:
{

cout<<“\nEnter a word: “;
cin>>word;
b.insert(word);
}
break;
case ‘2’:
{
cout<<“\n”;
b.inorder(b.ROOT);
cout<<“\n”;
}
break;
case ‘3’:
{
cout<<“\n”;
b.preorder(b.ROOT);
cout<<“\n”;
}
break;
case ‘4’:
{;
cout<<“\n”;
b.postorder(b.ROOT);
cout<<“\n”;
}
break;
case ‘5’:
{
exit(0);
}
break;
default:
{
cout<<“Invalid Option.”<<endl;
break;
}
}
}
}9.66 Solving Programming Problems Using Trees  ¤NIIT

Solving
Programming
Problems Using
Queues
Chapter 8
Many programming problems require you to
implement a list in such a way so that items can be
retrieved in the same order in which they arrive.
This kind of a list can be implemented by using a
data structure called queue. Queues offer a lot of
practical applications in various fields, such as
networking and internal working of computer
systems.
This chapter discusses the concept and
implementation of queues. In addition, it discusses
the various applications of queues.
In this chapter, you will learn to:
 Identify the features of queues
 Implement the different types of queues
 Apply queues to solve programming problems
Objectives ¤NIIT Solving Programming Problems Using Queues 8.3
Consider the scenario of a bank, where there is only one counter to resolve customer
queries. Therefore, customers have to stand in a queue to get their queries resolved. To
avoid the inconvenience caused to the customers, the bank has decided to set up a new
system.
Under the system, whenever a customer visits the bank, a request entry will be made into
the system and the customer will be given a request number. The requests will be stored
in the system in the order in which they were received. The request number of the earliest
request will be automatically flashed on the query counter, to indicate that the customer
with that request number can come next to get his/her query resolved. When a customer’s
request has been processed, the request will be removed from the system.
To implement this kind of a system, you need a data structure that stores and retrieves the
requests in the order of their arrival. A data structure that implements this concept is a
queue.
A queue is a list of elements in which items are inserted at one end of the queue and
deleted from the other end of the queue. You can think of a queue as an open ended pipe,
with elements being pushed from one end and coming out of another. The end at which
elements are inserted is called the rear and the end from which the elements are deleted is
called the front. A queue is also called a First-In-First-Out (FIFO) list because the first
element to be inserted in the queue is the first one to be deleted. The following figure
represents a queue.
Structure of a Queue
The queue data structure is very similar to the queues in real life. Consider the scenario of
a cafeteria where there is a queue of customers at the counter. The customer standing in
the front of the queue is served first. When new customers arrive, they are made to stand
Queues
Defining Queues 8.4 Solving Programming Problems Using Queues  ¤NIIT
Just a minute:
at the rear end of the queue. When a customer is served, he/she moves away from the
queue and the next person is served.
A queue is also known as a ___________ list.
Answer:
FIFO
There are two types of operations that can be performed on queues:
„ Insert: It refers to the addition of an item in the queue. Items are always inserted at
the rear end of the queue. Consider the queue, as shown in the following figure.
Queue Before Insertion
In the preceding queue, there are five elements. The element ‘B’ is labeled as
FRONT to indicate that it is the first element in the queue. Similarly, the element ‘D’
is labeled as REAR to indicate that it is the last element in the queue.
Identifying Various Operations on Queues ¤NIIT Solving Programming Problems Using Queues 8.5
Now suppose you want to add an item ‘F’ in the queue. Because addition takes place
at the rear end of the queue, ‘F’ will be inserted after ‘D. Now ‘F’ becomes the rear
end of the queue. Hence, we label ‘F’ as REAR, as shown in the following figure.
Queue After Insertion of an Element
„ Delete: It refers to the deletion of an item from the queue. Items are always deleted
from the front of the queue. When an item is deleted, the next item in sequence
becomes the front end of the queue. Consider the queue, as shown in the following
figure.
Queue Before Deletion 8.6 Solving Programming Problems Using Queues  ¤NIIT
Just a minute:
On implementing a delete operation, item ‘B’ will be removed from the queue. Now,
‘A’ will become the new front end of the queue. Therefore, ‘A’ is labeled as
FRONT, as shown in the following figure.
Queue After Deletion
Queues are data structures in which data can be added at one end called _________
and deleted from the other end called __________.
Answer:
rear, front ¤NIIT Solving Programming Problems Using Queues 8.7
You can implement a queue by using either an array or a linked list. Both the approaches
have their own set of advantages and disadvantages. Therefore, you need to decide
between the two depending upon the requirement.
You should implement a queue by using an array only if you are sure about the maximum
number of elements in the queue. This is because the size of the array needs to be
specified in advance.
To implement a queue by using an array, you need to first represent a queue in the form of
an array, and then implement the insert and delete operations on it.
Representing a Queue in an Array
To represent a queue in an array, you need to declare an array to store the elements in the
queue. The size of the array should be large enough to hold the maximum number of
elements in the queue. For example, if the queue needs to hold a maximum of five
integers, declare an array:
// Code in C#
int [] queue_array = new int [5];
// Code in C++
int queue_array [5];
In addition to declaring an array to store the elements in the queue, you also need to
declare two integer variables, FRONT and REAR, to keep track of the front and rear
index positions of the queue respectively. Initially, the value of FRONT and REAR is set
to – 1 to indicate that the queue is empty. The array representation of a queue is shown in
the following figure.
Array Representation of a Queue
Implementing Queues
Implementing a Queue Using an Array 8.8 Solving Programming Problems Using Queues  ¤NIIT
Once a queue is represented in the form of an array, you can write algorithms to
implement the insert and delete operations on the queue.
Implementing Insert and Delete Operations on a Queue
An element is always inserted at the rear end of the queue. Therefore, to implement the
insert operation, you need to execute the following algorithm:
1. If the queue is empty:
a. Set FRONT = 0.
2. Increment REAR by 1.
3. Store the element at index position REAR in the array.
Consider a queue of size five, which is initially empty, as shown in the following figure.
Empty Queue
The process of inserting elements in the preceding queue is illustrated in the following
table.
Operation Illustration
Insert element 3
Insert element 5 ¤NIIT Solving Programming Problems Using Queues 8.9
Operation Illustration
Insert element 7
Insert element 10
Insert element 15
Insert Operation in a Queue
An element is always deleted from the front end of the queue. Refer to the following
algorithm to implement a delete operation on a queue:
1. Retrieve the element at index FRONT.
2. Increment FRONT by 1.
Consider a queue of size five, as shown in the following figure.
Queue Before Delete Operation 8.10 Solving Programming Problems Using Queues  ¤NIIT
The process of deleting elements from the preceding queue is illustrated in the following
table.
Operation Illustration
Delete an element
Delete an element
Delete an element
Delete Operation in a Queue
From the preceding two algorithms, it is clear that to insert an element in a queue, you
need to increment the value of REAR by one. Similarly, to delete an element from a
queue, you need to increment the value of FRONT by one. Therefore, the value of
FRONT and REAR is always increased and never decreased. This approach however has
a drawback.
In the preceding figure, REAR has reached the last index position and its value cannot be
incremented further. Therefore, it is not possible to insert any more elements in the queue.
Although, there are three vacant positions in the beginning of the array, there is no
provision to fill these positions. In such a case, these empty positions go waste.
This approach is not space efficient because even though there are empty locations in the
beginning of the array, the locations cannot be utilized.  ¤NIIT Solving Programming Problems Using Queues 8.11
One way to solve the above problem is to always keep FRONT at the first index position,
0. This means that whenever an element is deleted from the queue, the remaining
elements are shifted one position backwards in the array to fill the space. Insertion of the
elements in the queue remains the same as before. Consider the queue, as shown in the
following figure.
Queue Before Delete Operation
If you want to perform a delete operation on the above queue, the element at index
FRONT will be deleted and the remaining elements will be shifted one position
backwards, so that FRONT is maintained at the zero index position. Refer to the queue, as
shown in the following figure.
Shift the Remaining Elements One Position Left
Therefore, after deletion, the queue appears, as shown in the following figure.
Queue After Delete Operation
Although this approach is more space efficient, it has another drawback associated with it.
This is because it involves an additional overhead of moving all the elements in the array
after the delete operation. If the array is very large, this process becomes very time
consuming. 8.12 Solving Programming Problems Using Queues  ¤NIIT
Note
An effective way to solve this problem is to implement the array as a circular array. In
this approach, if the last index position of the array is occupied with an element, then you
can start inserting elements from the beginning that is from the index position zero,
provided there is free space at the beginning. Therefore, the cells in the array are treated
as if they are arranged in a ring, as shown in the following figure.
Queue Implemented in the Form of a Circular Array
Please note that there is nothing called a circular array. The elements are stored in the
same linear array. However, the linear array is treated as if it is circular. ¤NIIT Solving Programming Problems Using Queues 8.13
When the queue is implemented in the form of a circular array, you need to perform a few
additional steps to implement various operations on the queue. Consider the following
operations performed on a queue:
„ Insert Operation: When an element is inserted in a circular array, the value of
REAR is incremented by one. This is same as that of a simple queue. However, if
REAR is at the last index position, you can reinitialize the value of REAR to zero
and start inserting elements from the beginning, provided there is space at the
beginning of the list. However, if you try to insert an element in a queue which is
full, it leads to queue overflow. The overflow condition will occur when one of the
following two conditions is true:
z FRONT = 0 and REAR = last index position, as shown in the following figure.
Queue Overflow Condition
z FRONT = REAR + 1, as shown in the following figure.
Queue Overflow Condition
Refer to the following algorithm to insert an element in a queue:
1. If the queue is full:
a. Display “Queue overflow”
b. Exit
2. If the queue is empty (If FRONT =  – 1):
a. Set FRONT = 0
b. Set REAR = 0
c. Go to step 5 8.14 Solving Programming Problems Using Queues  ¤NIIT
3. If REAR is at the last index position:
a. Set REAR = 0 // Set REAR to the first index position
b. Go to step 5
4. Increment REAR by 1
5. Queue [REAR] = element
„ Delete Operation: To delete an element from a circular queue, the value of FRONT
is incremented by one. This is similar to that of a simple queue. However, if the
element to be deleted is present at the last index position, then the value of front is
set to zero.
If the element to be deleted is the only element in the queue, both FRONT and
REAR point to the same index. In this case, the value of FRONT and REAR is set to
– 1 after deletion.
If you try to implement a delete operation on a queue, which is empty, it results in a
queue underflow condition. Therefore, you should always check for the queue
underflow condition before implementing a delete operation. The underflow
condition will occur when FRONT = REAR = – 1.
Refer to the following algorithm to delete an element from the queue implemented in
the form of a circular array:
1. If the queue is empty: // If FRONT  =   – 1
a. Display “Queue underflow”
b. Exit
2. If there is only one element in the queue: // If FRONT = REAR
a. Set FRONT  =  – 1
b. Set REAR  =  – 1
c. Exit
3. If FRONT is at the last index position:
a. Set FRONT = 0 // Set FRONT to the first index position
b. Exit
4. Increment FRONT by 1
Consider a queue of size five, as shown in the following figure.
Circular Queue ¤NIIT Solving Programming Problems Using Queues 8.15
The process of inserting and deleting elements in the preceding queue is illustrated in the
following table.
Operation Illustration
Insert element 1
Insert element 9
Insert element 3
Delete an element
Delete an element 8.16 Solving Programming Problems Using Queues  ¤NIIT
Just a minute:
Operation Illustration
Delete an element
Delete an element
Delete an element
Insert and Delete Operation in a Queue
What is the advantage of implementing a queue in the form of a circular array, instead
of a linear array structure?
Answer:
If you implement a queue in the form of a linear array, you can add elements only in
the successive index positions. However, when you reach the end of the queue, you
cannot start inserting elements from the beginning, even if there is space for them at
the beginning. You can overcome this disadvantage by implementing a queue in the
form of a circular array. In this case, you can keep inserting elements till all the index
positions are filled. Hence, it solves the problem of unutilized space. ¤NIIT Solving Programming Problems Using Queues 8.17
Problem Statement
Write a program to implement insert and delete operations on a queue implemented in the
form of a circular array.
Solution
Refer to the following code in C# and C++ code to implement a queue in the form of a
circular array:
// Code in C#
using System;
using System.Text;
namespace CircularQueues
{
class Queues
{
int FRONT, REAR, max = 5;
int[] queue_array = new int[5];
public Queues()
{
/* Initializing the values of the variables REAR and
FRONT to -1 to indicate that the queue is initially
empty. */
FRONT = -1;
REAR = -1;
}
public void insert(int element)
{
if ((FRONT == 0 && REAR == max – 1) || (FRONT == REAR + 1))
/* This statement checks for the overflow condition. */
{
Console.WriteLine(“\nQueue overflow\n”);
return;
}
/* The following statement checks whether the queue is
empty. If the queue is empty, then the value of the REAR
and FRONT variables is set to 0. */
if (FRONT == -1)
{
FRONT = 0;
REAR = 0;
Activity: Implementing a Queue Using Circular
Array 8.18 Solving Programming Problems Using Queues  ¤NIIT
}
else
{
/* If REAR is at the last position of the array, then
the value of REAR is set to 0 that corresponds to the
first position of the array. */
if (REAR == max – 1)
REAR = 0;
else
REAR = REAR + 1; /* If REAR is not at the
last position, then its
value is incremented by one.
*/
}
/* Once the position of REAR is determined, the element
is added at its proper place. */
queue_array[REAR] = element;
}
public void remove()
{
if (FRONT == -1)
/*Checks whether the queue is empty. */
{
Console.WriteLine(“Queue underflow\n”);
return;
}
Console.WriteLine(“\nThe element deleted from the queue
is: ” + queue_array[FRONT] + “\n”);
if (FRONT == REAR) /* Checks if the queue has one
element. */
{
FRONT = -1;
REAR = -1;
}
else
{
/* If the element to be deleted is at the last position
of the array, then the value of FRONT is set to 0 i.e to
the first element of the array. */
if (FRONT == max – 1)
FRONT = 0;
else
FRONT = FRONT + 1; /* FRONT is incremented by
one if it is not the first
element of array. */
}
}
public void display()
{
int FRONT_position = FRONT;
int REAR_position = REAR;
if (FRONT == -1) /* Checks if the queue is empty. */
{
Console.WriteLine(“Queue is empty\n”); ¤NIIT Solving Programming Problems Using Queues 8.19
return;
}
Console.WriteLine(“\nElements in the queue
are……………\n”);
if (FRONT_position <= REAR_position)
{
while (FRONT_position <= REAR_position)
/* Traverses the queue till the last element
present in an array. */
{

Console.Write(queue_array[FRONT_position] + ”   “);
FRONT_position++;
}
Console.WriteLine();
}
else
{
while (FRONT_position <= max – 1)
/* Traverses the queue till the last position of
the array. */
{

Console.Write(queue_array[FRONT_position] + ”   “);
FRONT_position++;
}
FRONT_position = 0; /* Set the FRONT position to
the first element of the
array. */
while (FRONT_position <= REAR_position)
/* Traverses the array till the last element
present in the queue. */
{

Console.Write(queue_array[FRONT_position] + ”   “);
FRONT_position++;
}
Console.WriteLine();
}
}
static void Main(string[] args)
{
Queues q = new Queues();
char ch;
while (true)
{
try
{
Console.WriteLine(“Menu”);
Console.WriteLine(“1. Implement insert
operation”);
Console.WriteLine(“2. Implement delete
operation”);
Console.WriteLine(“3. Display values”);
Console.WriteLine(“4. Exit”); 8.20 Solving Programming Problems Using Queues  ¤NIIT
Console.Write(“\nEnter your choice (1-4): “);
ch = Convert.ToChar(Console.ReadLine());
Console.WriteLine();
switch (ch)
{
case ‘1’:
{
Console.Write(“Enter a number:”);
int num =
Convert.ToInt32(System.Console.ReadLine());
Console.WriteLine();
q.insert(num);
}
break;
case ‘2’:
{
q.remove();
}
break;
case ‘3’:
{
q.display();
}
break;
case ‘4’:
return;
default:
{
Console.WriteLine(“Invalid
option!!”);
}
break;
}
}
catch (Exception e)
{
Console.WriteLine(“Check for the values
entered.”);
}
}
}
}
}
// Code in C++
#include<iostream.h>
class Queues
{

int FRONT, REAR, max;
int queue_array[5];
public: ¤NIIT Solving Programming Problems Using Queues 8.21
Queues();
void insert(int element);
void remove();
void display();
};
Queues :: Queues()
{
/* Initializing the values of the variables REAR and FRONT to -1 to
indicate that the queue is initially empty. */
FRONT = -1;
REAR = -1;
max = 5;
}
void Queues :: insert(int element)
{
if((FRONT == 0 && REAR == max-1) || (FRONT == REAR + 1)) /*This
statement checks for the overflow condition. */
{
cout<<“\nQueue overflow\n”<<endl;
return;
}
/* The following statement checks whether the queue
is empty. If the queue is empty, then the value of
the REAR and FRONT variables is set to 0. */
if(FRONT == -1)
{
FRONT = 0;
REAR = 0;
}
else
{
/* If REAR is at the last position of the array, then the
value of REAR is set to 0 that corresponds to the first
position of the array. */
if(REAR == max-1)
REAR = 0;
else
REAR = REAR + 1; /* If REAR is not at the last
position, then its value is incremented by one. */

}
/* Once the position of REAR is determined, the
element is added at its proper place. */
queue_array[REAR] = element;
}
void Queues :: remove()
{
if (FRONT == -1) /* Checks whether the queue is
empty. */
{ 8.22 Solving Programming Problems Using Queues  ¤NIIT
cout<<“Queue underflow\n”<<endl;
return;
}
cout<<“The element deleted from the queue is:
“<<queue_array[FRONT]<<endl<<endl;
if (FRONT == REAR) /* Checks if the queue has one
element. */
{
FRONT = -1;
REAR = -1;
}
else
{
/* If the element to be deleted is at the last position
of the array, then the value of FRONT is set to 0 i.e to
the first element of the array. */
if (FRONT == max – 1)
FRONT = 0;
else
FRONT = FRONT + 1; /* FRONT is incremented by
one if it is not the first
element of array. */
}
}
void Queues :: display()
{
int FRONT_position = FRONT;
int REAR_position = REAR;
if (FRONT == -1) /* Checks if the queue is empty. */
{
cout<<“Queue is empty\n”<<endl;
return;
}
cout<<“\nElements in the queue
are……………\n”<<endl;
if (FRONT_position <= REAR_position)
{
while (FRONT_position <= REAR_position)
/* Traverses the queue till the last element
present in an array.*/
{
cout<<queue_array[FRONT_position]<<”   “;
FRONT_position++;
}
cout<<endl;
}
else
{
while (FRONT_position <= max – 1) /* Traverses the
queue till the last position of the array. */
{
cout<<queue_array[FRONT_position] << ”   “;
FRONT_position++;
} ¤NIIT Solving Programming Problems Using Queues 8.23
FRONT_position = 0; /* Set the FRONT position to
the first element of the
array. */
while (FRONT_position <= REAR_position)
/* Traverses the array till the last element
present in the queue. */
{
cout<<queue_array[FRONT_position] <<”   “;
FRONT_position++;
}
cout<<endl;
}
}

void main()
{
Queues obj;
char ch;
int num;
while (1)
{
cout<<“Menu”;
cout<<“\n1. Implement insert operation”<<endl;
cout<<“2. Implement delete operation”<<endl;
cout<<“3. Display values”<<endl;
cout<<“4. Exit”<<endl;
cout<<“\nEnter your choice (1-4): “;
cin>>ch;
cout<<endl;
switch (ch)
{
case ‘1’:
{
cout<<“Enter a number: “;
cin>>num;
cout<<endl;
obj.insert(num);

}
break;
case ‘2’:
{
obj.remove();
}
break;
case ‘3’:
{
obj.display();
cout<<“\n”;
}
break;
case ‘4’:
{
exit(0);
} 8.24 Solving Programming Problems Using Queues  ¤NIIT
break;
default:
{
cout<<“Invalid option”<<endl;
}
break;
}
}
}
When you implement a queue in the form of an array, you need to specify its size in
advance. Therefore, this approach is not useful if you do not know the size of the queue in
advance. To overcome this disadvantage, you can implement a queue in the form of a
linked list. A queue implemented in the form of a linked list is known as a linked queue.
Representing a Queue as a Linked List
To represent a queue in the form of a linked list, you need to declare two classes:
„ Node class: This class represents a node in the linked queue, and is similar to the
node of a singly linked list. Refer to the following declaration of the Node class in C#
and C++:
// Code in C#
class Node
{
public int data;
public Node next;
}
// Code in C++
class Node
{
public:
int data;
Node *next;
};
Implementing a Queue Using a Linked List ¤NIIT Solving Programming Problems Using Queues 8.25
„ LinkedQueue class: This class implements all the operations on a queue such as
insert and remove. In addition it declares two variables/pointers,  FRONT and  REAR
that point to the first and last elements in the queue respectively. Initially, FRONT and
REAR are made to point to  NULL indicating that the queue is empty. Refer to the
following declarations of the LinkedQueue class in C# and C++:
// Code in C#
class LinkedQueue
{
Node FRONT, REAR;
public LinkedQueue()
{
FRONT = null;
REAR = null;
}
public void insert (int element){}
public void remove(){}
public void display(){}
}
// Code in C++
class LinkedQueue
{
Node * FRONT, REAR;
public:
LinkedQueue()
{
FRONT = NULL;
REAR = NULL;
}
void insert(int element){}
void remove(){}
void display(){}
};
The structure of a linked queue is shown in the following figure.
Linked Queue
After deciding the representation for the linked queue, you can start writing algorithms for
inserting and deleting elements in the queue. 8.26 Solving Programming Problems Using Queues  ¤NIIT
Inserting an Element in a Linked Queue
An element is always inserted at the rear end of the queue. Therefore, you need to insert a
new node at the rear end of the linked queue. To insert a node at the rear end of a linked
queue, you can use the following algorithm:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. Make the next field of the new node point to NULL.
4. If the queue is empty, execute the following steps:
a. Make FRONT point to the new node
b. Make REAR point to the new node
c. Exit
5. Make the next field of REAR point to the new node.
6. Make REAR point to the new node.
The process of inserting an element in a linked queue is illustrated in the following table.
Operation Illustration
Allocate memory and assign value
to the data field for the new node.
Make the next field of the new
node point to NULL.
Make the next field of REAR point
to the new node.
Make REAR point to the new node.
Insert Operation in a Linked Queue ¤NIIT Solving Programming Problems Using Queues 8.27
Note
Because the queue is implemented as a linked list, there is no limit on the maximum
number of elements that the queue can contain. Therefore, you do not need to check for
the queue full condition before inserting a node in the linked queue.
Deleting an Element from a Linked Queue
An element is always deleted from the front end of a queue. Therefore, you need to delete
a node from the front end of the linked queue. To delete a node from the front end of a
linked queue, you can use the following algorithm:
1. If the queue is empty: // FRONT = NULL
a. Display “Queue empty”
b. Exit
2. Mark the node marked FRONT as current
3. Make FRONT point to the next node in its sequence
4. Release memory for the node marked as current
The process of deleting an element from a linked queue is illustrated in the following
table.
Operation Illustration
Mark the node marked FRONT as
current.
Make FRONT point to the next node
in its sequence. 8.28 Solving Programming Problems Using Queues  ¤NIIT
Just a minute:
Operation Illustration
Release memory for the node
marked as current.
Delete Operation in a Linked Queue
How does the implementation of a linked list differ from that of a linked queue?
Answer:
In a linked list, you can insert and delete elements anywhere in the list. However, in a
linked queue, insertion and deletion takes place only from the ends. More specifically,
insertion takes place at the rear end and deletion takes place at the front end of the
queue. ¤NIIT Solving Programming Problems Using Queues 8.29
Queues find their use in applications that need to serve the requests of multiple users on a
First-Come-First-Served (FCFS) basis. These applications usually have limited resources
to process the requests. Because the resources are limited, the rate at which the
application receives requests is much faster than the rate at which it processes the
requests. Therefore, you need to store the requests in a queue until they are processed.
This section discusses the various application areas of queues such as printer spooling,
CPU scheduling, mail service, keyboard buffering, and elevator.
A printer may receive multiple print requests in a short span of time. In such a case, the
rate at which the print requests are received becomes much faster than the rate at which
the requests are processed.
In such a scenario, a temporary storage mechanism is required to store the print requests
in the order of their arrival. A queue is the best choice in this case, which stores the print
requests in such a manner so that they are processed on a FCFS basis.
Another type of queue called a priority queue is also used in printer spooling. When you
issue a print request, you can increase or decrease the priority of the request depending on
the requirement. Each request in the queue therefore, has a priority associated with it.
When a priority queue is used, requests are processed depending upon their priority,
rather than their order of arrival. A request with higher priority is processed before a
request with lower priority. If some elements have equal priority, then they are processed
on a FCFS basis.
A CPU can process only one request at a time. However, most of the times, the rate at
which a CPU receives requests is much greater than the rate at which it can process them.
Therefore, these requests are temporarily stored in a queue in the order of their arrival.
Whenever the CPU becomes free, it obtains the requests from the queue one by one and
processes them. Once a request is processed, its reference is deleted from the queue. The
CPU then obtains the next request in sequence and the process continues. This allows the
requests to be processed on a FCFS basis.
Applications of Queues
Printer Spooling
CPU Scheduling 8.30 Solving Programming Problems Using Queues  ¤NIIT
In a time sharing system, the CPU processes each request for a fixed period of time. In
this case, the CPU is allocated to each process for a fixed time period. All the requests are
temporarily stored in a queue. The CPU processes each request one by one for a fixed
period of time.
If the request is processed within that specified time period, it is deleted from the queue.
However, if the request is not processed within the time allocated, it is shifted to the end
of the queue. The CPU then serves the next request in the queue, and the process
continues.
In various organizations, many transactions are conducted through mails. However, if the
mail server goes down, and someone tries to send you a mail, the mail is bounced back to
the sender.
To avoid any such situation, various organizations implement a mail backup service.
Therefore, whenever there is some problem with the mail server because of which the
messages are not delivered, the mail is routed to the backup server.
The backup server stores the mails temporarily in a queue. Whenever the mail server is
up, all the mails are transferred to the recipient in the order in which they arrived.
Queues are also used for storing the keystrokes as you type on a keyboard. You must have
sometimes observed that when you hit a key; it is not immediately displayed on the
screen. This happens because during that time, the processor is busy doing some other
tasks and is therefore not available to process your request.
However, when this happens, your data is not lost, but stored in a queue temporarily, till
the processor reads it. Once the processor is free, all the keystrokes that you have sent are
read in the sequence of their arrival and displayed on the screen.
An elevator also makes use of a queue to store the requests placed by users. Suppose a
user on the ground floor presses the elevator button to request for the elevator. At almost
the same time a user on the second floor also presses the elevator button. Suppose the
elevator is currently on the first floor. In that case, the elevator would go to the floor on
which the button was pressed earlier, that is, the requests will be processed on a
FCFS basis.
Mail Service
Keyboard Buffering
Elevator ¤NIIT Solving Programming Problems Using Queues 8.31
However, if one of the users had been on the ground floor and the other had been on the
ninth floor, then irrespective of who pressed the button first, the elevator would go to the
ground floor first because the distance to the ground floor is much less than the distance
to the ninth floor. In this case, some sort of a priority queue would need to be used. 8.32 Solving Programming Problems Using Queues  ¤NIIT
1. A queue is referred to as a _____________ list.
a. First-in-first-out
b. First-in-last-out
c. Last-in-first-out
d. Last-in-last-out
2. Briefly discuss the advantages of a queue implemented as a linked list rather than as
an array.
3. Briefly discuss the advantages of a queue implemented in the form of a circular array
as compared to a linear array.
4. In a priority queue, if two elements share the same priority, then ________________.
a. The elements are processed on a random basis
b. The element that came in last is processed first
c. The element sent by a user with more rights is processed first
d. The element that came in first is processed first
5. Briefly discuss the mechanism that a time sharing system implements to serve
multiple requests simultaneously.
Practice Questions ¤NIIT Solving Programming Problems Using Queues 8.33
In this chapter, you learned that:
„ A queue is a linear data structure in which the elements are inserted at the rear end
and deleted from the front.
„ The various operations implemented on a queue are insert and remove.
„ A queue can be implemented by using arrays or linked list.
„ A queue implemented in the form of a circular array overcomes the problem of
unutilized space encountered in queues implemented by using a linear array.
„ A queue implemented by using a linked list is called a linked queue.
„ Queues offer large number of applications in various fields such as:
z Printer spooling
z CPU scheduling
z Mail service
z Keyboard buffering
z Elevator
Summary 8.34 Solving Programming Problems Using Queues  ¤NIIT
Exercise 1
Write a program to implement insert and delete operations on a linked queue.
Exercise 2
Write a program to implement a double-ended queue.
Hint: A double-ended queue is a queue in which elements can be inserted and deleted at
either end.
Exercises

Solving
Programming
Problems Using
Stacks
Chapter 7
Many programming problems require you to
maintain a list of items. Consider a situation where
you need to maintain a list of student records in the
ascending order of their names. To maintain such a
list, you may need to insert or delete records from
any position in the list.
However, there can be situations where you want to
implement a list in such a way that allows items to
be inserted and deleted at one end of the list only.
This kind of a list can be implemented by using a
stack.
This chapter discusses the concept and
implementation of stacks. In addition, it discusses
the various applications of stacks.
In this chapter, you will learn to:
 Identify the features of a stack
 Implement stacks
 Apply stacks to solve programming
problems
Objectives ¤NIIT Solving Programming Problems Using Stacks 7.3
Consider an example of a card game called Rummy. To start the game, a stock pile and a
discard pile are placed in the center. A player can draw either the topmost card of the
stock pile or the topmost card of the discard pile. If the drawn card does not make a valid
sequence in the player’s hand, the player can discard the card by placing it on the top of
the discard pile.
The next player can then draw either the topmost card of the stock pile or the topmost
card of the discard pile, and so on.
To represent and manipulate such type of a discard pile in a computer program, you need
a data structure that allows insertion and deletion at only one end. It should ensure that the
last item inserted is the first one to be removed. A data structure that implements this
concept is called a stack.
This section discusses the stack data structure and explains the operations that can be
performed on a stack.
A stack is a collection of data items that can be accessed at only one end, called top. This
means that the items are inserted and deleted at the top. The last item that is inserted in a
stack is the first one to be deleted. Therefore, a stack is called a Last-In-First-Out (LIFO)
data structure.
A stack is like an empty box containing books, which is just wide enough to hold the
books in one pile. The books can be placed as well as removed only from the top of the
box. The book most recently put in the box is the first one to be taken out. The book at the
bottom is the first one to be put inside the box and the last one to be taken out.
The following figure shows a stack of books.
Stack of Books
Stacks
Defining a Stack 7.4 Solving Programming Problems Using Stacks  ¤NIIT
The characteristics of stacks are as follows:
„ Data can only be inserted on the top of the stack.
„ Data can only be deleted from the top of the stack.
„ Data cannot be deleted from the middle of the stack without first removing all items
from the top.
There are two basic operations that can be performed on a stack. They are:
„ PUSH
„ POP
When you insert an item into a stack, you say that you have pushed the item onto the
stack. When you delete an item from a stack, you say that you have popped the item from
the stack.
The following table depicts the PUSH and POP operations on a stack.
Operation Stack Contents
Push book 1 into an
empty stack
Push book 2 into the
stack
Pop a book from the
stack
Identifying the Operations on Stacks
1
1
2¤NIIT Solving Programming Problems Using Stacks 7.5
Just a minute:
Operation Stack Contents
Push book 3 into the
stack
Push book 4 into the
stack
Pop book 3 from the
stack
Invalid Operation. To pop book 3, you need to first pop book 4
from the stack.
Pop a book from the
stack
PUSH and POP Operations on a Stack
Elements in stacks are inserted and deleted on a ___________ basis.
Answer:
LIFO
1
3
1
3
4
1
3 47.6 Solving Programming Problems Using Stacks  ¤NIIT
Just a minute:
List down some real life examples that work on the LIFO principle.
Answer:
Pile of books: Suppose a set of books are placed one over the other in a pile. When
you remove books from the pile, the topmost book will be removed first. Similarly,
when you have to add a book to the pile, the book will be placed at the top of the pile.
Pile of plates: The first plate begins the pile. The second plate is placed on the top of
the first plate and the third plate is placed on the top of the second plate, and so on. In
general, if you want to add a plate to the pile, you can keep it on the top of the pile.
Similarly, if you want to remove a plate, you can remove the plate from the top of the
pile.
Bangles in a hand: When a person wears bangles, the last bangle worn is the first one
to be removed. ¤NIIT Solving Programming Problems Using Stacks 7.7
A stack is simply a list in which insertion and deletion is allowed only at one end.
Therefore, a stack can be implemented by using an array or a linked list. When a stack is
implemented by using an array, the stack is said to be static. In this case, the size of the
stack is fixed and cannot change at runtime.
When a stack is implemented by using a linked list, the stack is said to be dynamic. In this
case, memory is dynamically allocated to the stack, and the size of the stack can grow and
shrink at runtime.
An array should be used to implement a stack only when the maximum number of
elements in the stack is known in advance. When a stack is implemented by using an
array, you must ensure that the array is declared large enough to store the maximum
number of elements in the stack.
To represent a stack by using an array, you need to first declare an array to hold the items
in the stack. For example:
int Stack[5];
The preceding declaration declares an integer array of size 5. This means that the stack
can hold a maximum of five integer values.
After declaring an array, you need to declare a variable to hold the index of the topmost
element in the stack. This variable can be declared as:
int top;
For an empty stack, top is set to – 1.
After declaring an array to hold the items in the stack and a variable to hold the index of
the topmost element, you can implement the PUSH and POP operations.
Implementing the PUSH Operation
The PUSH operation stores a given item on top of the topmost item in the stack. The
index of the topmost item is stored in the variable top. Therefore, to implement the PUSH
operation, you need to execute the following algorithm:
1. Increment top by 1.
Implementing Stacks
Implementing a Stack Using an Array 7.8 Solving Programming Problems Using Stacks  ¤NIIT
2. Store the value to be pushed at index top in the array. Top now contains the index of
the topmost element.
Let us consider an example. Suppose, you have implemented a stack in an array, arr of
size 5. Initially, when the stack is empty, top is set to – 1. The following figure depicts an
empty stack.
An Empty Stack
Now you need to push an element 13 into the stack. Once you have pushed this element
into the stack, the value of the top variable will change to 0, as shown in the following
figure.
An Element Pushed into the Stack
When a stack is implemented in an array, the size of the stack is fixed. This means that
there is an upper bound on the maximum number of elements that the stack can contain.
When a stack contains the maximum number of elements, it is said to be full. When you
attempt to push an element in a full stack, there is an overflow. Therefore, before pushing
an element into a stack, you need to check whether the stack is full or not.
If the size of the array is MAX, the condition for stack full is:
top = MAX – 1
If the stack full condition is true, PUSH operation should not be performed.
The following is the modified algorithm for the PUSH operation:
1. If top = MAX – 1:
a. Display “Stack Full”
b. Exit
2. Increment top by 1 ¤NIIT Solving Programming Problems Using Stacks 7.9
Just a minute:
3. Store the value to be pushed at index top in the array
Implementing the POP Operation
The POP operation removes the item at the topmost position in the stack. To implement
the POP operation, you need to execute the following algorithm:
1. Retrieve the value stored at index top.
2. Decrement top by 1. Top now contains the index of the new topmost element.
However, before popping an element from a stack, you need to check whether the stack
contains any elements. If you attempt to pop an element from an empty stack, there is an
underflow. Therefore, before popping an element from the stack, you need to check for
the stack empty condition. The condition for stack empty is:
top =  – 1
If the stack empty condition is true, POP operation should not be performed.
The following is the modified algorithm for the POP operation:
1. If top = – 1:
a. Display “Stack Empty”
b. Exit
2. Retrieve the value stored at index top
3. Decrement top by 1
In a stack, data can be stored and removed only from one end of the stack called the
______ of the stack.
Answer:
top 7.10 Solving Programming Problems Using Stacks  ¤NIIT
When a stack is implemented by using an array, the maximum size of the stack needs to
be specified in advance. This limitation can be overcome by using a linked list.
To represent a stack as a linked list, you need to first declare a class Node to represent a
node in the linked list. The following code snippets give the declaration of the Node class
in C# and C++:
// Code in C#
class Node
{
public int info;
public Node next;
public Node(int i, Node n)
{
info = i;
next = n;
}
}
// Code in C++
class Node
{
public:
int info;
Node *next;
};
After representing a node of a stack, you need to declare a class Stacks to implement
operations on a stack and declare a variable/pointer to hold the address of the topmost
element in the stack.
The following code snippets give the declaration of the Stacks class in C# and C++:
// Code in C#
class Stacks
{
Node top;
public Stacks()
{
top = null;
Implementing a Stack Using a Linked List ¤NIIT Solving Programming Problems Using Stacks 7.11
}
bool empty()
// Returns true if the stack is empty, false otherwise
{
// Statements
}
public void push(int element)
{
// Statements
}
public void pop()
{
// Statements
}
}
// Code in C++
class Stack
{
private:
Node *top;
public:
Stack()
{
top = NULL;
}
int empty()
{
// Statements
}
void push( int element)
{
// Statements
}
int pop()
{
// Statements
}
};
After declaring the preceding classes, you need to implement the PUSH and POP
operations. 7.12 Solving Programming Problems Using Stacks  ¤NIIT
Note
Implementing the PUSH Operation
To implement the PUSH operation, you need to insert a node at the beginning of the
linked list. The algorithm for PUSH operation is as follows:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. Make the next field of the new node point to top.
4. Make top point to the new node.
When a stack is implemented by using a linked list, there is no upper bound limit on the
size of the stack. Therefore, the condition for stack full need not be checked when pushing
an element into the stack.
Implementing the POP Operation
To implement the POP operation, you need to delete a node from the beginning of the
linked list. The algorithm for the POP operation is as follows:
1. Make a variable/pointer tmp point to the topmost node.
2. Retrieve the value contained in the topmost node.
3. Make top point to the next node in sequence.
4. Release memory allocated to the node marked by tmp.
You can also implement the POP operation by simply making top point to the next node
in sequence. However, in this case, the memory will not be released after popping the
element.
When deleting a node, you need to check whether the stack contains any elements. If you
attempt to pop an element from an empty stack, there is an underflow. Therefore, before
popping an element from the stack, you need to check for the stack empty condition. The
condition for stack empty is:
top = NULL
If the stack empty condition is true, the POP operation should not be performed. ¤NIIT Solving Programming Problems Using Stacks 7.13
The following is the modified algorithm for the POP operation:
1. If top = NULL:
a. Display “Stack Underflow: Cannot delete from an empty stack”
b. Exit
2. Make tmp point to the topmost node
3. Retrieve the value contained in the topmost node
4. Make top point to the next node in sequence
5. Release the memory allocated to the node marked as tmp 7.14 Solving Programming Problems Using Stacks  ¤NIIT
Problem Statement
Write a program to implement a stack by using an array that can store five elements.
Solution
The following is the program code to implement a stack by using an array:
// Code in C#
using System;
using System.Text;
namespace StacksInCSharp
{
class Stacks
{
int[] stack_array = new int[5];
int top;
Stacks()
{
top = – 1;
}
public bool full()
{
if (top == 4)
return (true);
else
return (false);
}
public bool empty()// Returns true if the stack is empty,
// false otherwise
{
if (top == – 1)
return (true);
else
Activity: Implementing a Stack Using an Array ¤NIIT Solving Programming Problems Using Stacks 7.15
return (false);
}
public void push(int item)
// Function to push an element into the stack
{
top = top + 1;
stack_array[top] = item;
Console.WriteLine();
Console.WriteLine(item + ” pushed.”);
}
public void pop()
// Function to pop an element from the stack
{
Console.WriteLine(“\nThe popped item is: ” +
stack_array[top]);
top = top – 1;
}
public void display()
{
int i;
if (empty())
Console.WriteLine(“\nStack empty”);
else
{
Console.WriteLine(“\nThe contents of the stack are:\n
“);
for (i = top; i >= 0; i ––)
Console.WriteLine(stack_array[i]);
Console.WriteLine();
}
}
static void Main(string[] args)
{
Stacks obj = new Stacks();
char choice;
while (true)
{
Console.WriteLine(“\nMenu”);
Console.WriteLine(“1. Push”);
Console.WriteLine(“2. Pop”); 7.16 Solving Programming Problems Using Stacks  ¤NIIT
Console.WriteLine(“3. Display”);
Console.WriteLine(“4. Exit”);
Console.Write(“\nEnter your choice: “);
choice = Convert.ToChar(Console.ReadLine());
switch (choice)
{
case ‘1’:
int item;
if (obj.full())
{
Console.WriteLine(“\nStack Full”);
break;
}
Console.Write(“\nEnter a number: “);
item = Convert.ToInt32(Console.ReadLine());
obj.push(item);
break;
case ‘2’:
if (obj.empty())
{
Console.WriteLine(“\nStack Empty”);
break;
}
obj.pop();
break;
case ‘3’:
obj.display();
break;
case ‘4’:
return;
default:
Console.WriteLine(“\nInvalid choice.”);
break;
}
}
}
}
}¤NIIT Solving Programming Problems Using Stacks 7.17
// Code in C++
#include<iostream.h>
class Stack
{
private:
int stack_array[5];
int top;
public:
Stack()
{
top = – 1;
}

int full()
{
if (top == 4)
return(1);
else
return(0);
}

int empty()
{
if (top == – 1)
return(1);
else
return(0);
}
void push( int passed_value)
{
top++;
stack_array[top] = passed_value;
cout << endl << passed_value << ” pushed.” << endl;
}
void pop()
{
cout<<“\nThe popped value is ”
<<stack_array[top]<<“\n”;
top–;
} 7.18 Solving Programming Problems Using Stacks  ¤NIIT
void display()
{
if (empty())
cout << endl << “Stack Empty” << endl;
else
{
cout << endl << “\nThe contents of the stack
are :\n” << endl;

for (int i=top; i>=0; i –)
{
cout<<stack_array[i]<<“\n”;
}
}
}
};
void main()
{
int choice;
Stack mystack;
while (1)
{
cout<<“\n\n***STACK MENU***\n\n”;
cout<<“1. PUSH\n”;
cout<<“2. POP\n”;
cout<<“3. Display\n”;
cout<<“4. Exit\n”;
cout<<“\nEnter your choice: “;
cin>>choice;
switch(choice)
{
case 1:
if (mystack.full())
{
cout << “\nStack Full”;
break;
}
cout<<“\nEnter a number: “;
cin>>choice;
mystack.push(choice); ¤NIIT Solving Programming Problems Using Stacks 7.19
break;

case 2:
if (mystack.empty())
{
cout << “\nStack Empty”;
break;
}
mystack.pop();
break;
case 3:
mystack.display();
break;

case 4:
exit(0);
default:
cout<<“\nInvalid choice. Try again\n”;

}
}
}7.20 Solving Programming Problems Using Stacks  ¤NIIT
Problem Statement
Write a program to implement a stack by using a linked list.
Solution
The following is the program code to implement a stack by using a linked list:
// Code in C#
using System;
using System.Text;
namespace Stack_Implementation
{
class Node
{
public int info;
public Node next;
public Node(int i, Node n)
{
info = i;
next = n;
}
}
class Stacks
{
Node top;
public Stacks()
{
top = null;
}
bool empty()
{
if (top == null)
return (true);
else
return (false);
Activity: Implementing a Stack Using a Linked List ¤NIIT Solving Programming Problems Using Stacks 7.21
}
public void push(int element)
{
Node fresh;
fresh = new Node(element, null);
fresh.next = top;
top = fresh;
Console.WriteLine(“\n” + element + ” pushed.”);
}
public void pop()
{
Console.WriteLine(“\nThe popped element is: ” +
top.info);
top = top.next; /* Make top point to the next node in
sequence */
}
public void display()
{
Node tmp;
if (empty())    // If stack is empty
Console.WriteLine(“\nStack Empty”);
else
{
// Traverse the list from beginning till end
for (tmp = top; tmp != null; tmp = tmp.next)
{
Console.WriteLine(tmp.info);
}
Console.WriteLine();
}
}
static void Main(string[] args)
{
Stacks s = new Stacks();
while (true)
{
Console.WriteLine();
Console.WriteLine(“\n***Stack Menu***\n”);
Console.WriteLine(“1. Push.”); 7.22 Solving Programming Problems Using Stacks  ¤NIIT
Console.WriteLine(“2. Pop”);
Console.WriteLine(“3. Display”);
Console.WriteLine(“4. Exit”);
Console.Write(“\nEnter your choice: “);
string sInput = Console.ReadLine();
char ch = Convert.ToChar(sInput == “” ? “0” :
sInput);
switch (ch)
{
case ‘1’:
Console.Write(“\nEnter a number: “);
int num =
Convert.ToInt32(Console.ReadLine());
s.push(num);
break;
case ‘2’:
if (s.empty())
{
Console.WriteLine(“\nStack Empty”);
break;
}
s.pop();
break;
case ‘3’:
s.display();
break;
case ‘4’:
return;
default:
Console.WriteLine(“\nInvalid Choice”);
break;
}
}
}
}
}
// Code in C++
#include<iostream.h>
class Node
{
public:
int info; ¤NIIT Solving Programming Problems Using Stacks 7.23
Node *next;
};
class Stack
{
private:
Node *top;
public:
Stack()
{
top = NULL;
}
int empty()
{
if (top == NULL)
return(true);
else
return(false);
}
void push( int passed_value)
{
Node *temp;
if ( top == NULL )
{
top = new Node;
top->info = passed_value;
top->next = NULL;
}
else
{
temp = new Node();
temp->info = passed_value;
temp->next = top;
top = temp;
}
cout << endl << passed_value << ” pushed.” << endl;
} 7.24 Solving Programming Problems Using Stacks  ¤NIIT
int pop()
{
Node *tmp;
tmp = top; /* Make tmp point the first node of the
list */
top = top->next;
int x = tmp->info;
delete(tmp);
return(x);
}
void display()
{
if (top == NULL) // If stack is empty
cout << endl << “Stack Empty.” << endl;
else
{
Node *currentNode;

cout << endl << “The contents of the stack
are:” << endl;

for (currentNode = top; currentNode!=NULL;
currentNode = currentNode->next)
{
cout<<currentNode->info<<“\n”;
}
}
}
};
void main()
{
int choice,x;
Stack mystack;
while (1)
{
cout<<“\n***STACK MENU***\n\n”;
cout<<“1. PUSH\n”;
cout<<“2. POP\n”;
cout<<“3. Display\n”; ¤NIIT Solving Programming Problems Using Stacks 7.25
cout<<“4. Exit\n”;
cout<<“\nEnter your choice: “;
cin>>choice;
switch(choice)
{
case 1:
cout<<“\nEnter a number: “;
cin>>choice;
mystack.push(choice);
break;

case 2:
if (mystack.empty())
{
cout << endl << “Stack Empty.” <<
endl;
break;
}
x = mystack.pop();
cout << endl << “The popped value is ” << x
<< endl;
break;
case 3:
mystack.display();
break;

case 4:
exit(0);
default:
cout<<“\nInvalid choice. Try again\n”;

}
}
}7.26 Solving Programming Problems Using Stacks  ¤NIIT
Just a minute:
Just a minute:
What will be the condition for stack full in a stack implemented as a linked list?
Answer:
When a stack is implemented as a linked list, there is no upper bound limit on the size
of the stack. Therefore, there will be no stack full condition in this case.
If a stack is represented in memory by using a linked list, then insertion and deletion
of data will be done __________.
1. At the end of the list
2. At the beginning of the list
3. Anywhere in the list
4. At the beginning and at the end of the list respectively
Answer:
2.    At the beginning of the list ¤NIIT Solving Programming Problems Using Stacks 7.27
Stacks are simple data structures that play a prominent role in many algorithms. Stacks
are used for various applications, such as implementing function calls, maintaining the
undo list for an application, checking the validity of an expression, and evaluating an
expression. This section discusses the mentioned applications of stacks.
One of the most important applications of stacks is their use in implementing a function
call. When a function is called, the system must remember the address from where the call
was made so that the system can return there after the called function is executed. The
program must also remember the values of all the local variables of the calling function so
that no information is lost while the called function is being executed.
Consider an example to understand this concept. Assume that you have three functions
F1, F2, and F3, and suppose that F1 invokes F2 and F2 invokes F3, then F2 cannot finish
its execution until F3 has finished and returned. Also F1 cannot finish its execution until
F2 has finished and returned.
Therefore, we find that F1 is the first to start but is the last to be finished. Thus the
sequence of function execution is LIFO. Since a stack implements a LIFO list, we can use
a stack for storing the return address and the values of local variables whenever a call to a
function is made.
When F1 calls F2, the return address and values of local variables of F1 are pushed into a
stack, as shown in the following figure.
The Return Address and Values of Local Variable of F1 Pushed into the Stack
Applications of Stacks
Implementing Function Calls 7.28 Solving Programming Problems Using Stacks  ¤NIIT
Similarly, when F2 calls F3, the return address and values of local variables of F2 are
pushed in the stack, as shown in the following figure.
The Return Address and Values of Local Variable of F2 Pushed into the Stack
When F3 finishes its execution, the topmost frame in the stack is popped to obtain the
following information pertaining to function, F2:
„ Address of the next instruction to be executed
„ Values of the local variables of function F2
Similarly, once F2 finishes its execution, the topmost frame in the stack is popped to
obtain the address of the next instruction to be executed in F1 and the values of the local
variables of F1.
Stacks help you maintain the UNDO list for an application. For example, when you make
any changes to the content of a Word document, Word provides you the facility of
undoing those changes.
When you repeatedly issue the UNDO command, changes are undone in the reverse
order. This means that the last change made to the application is the first one to be
undone. Because a stack implements a LIFO list, you can use a stack to implement the
undo list.
Stacks help in the conversion of a decimal number (base 10) to an equivalent number in
any other base (say x). This can be accomplished by dividing the number by x, and then
repeatedly dividing the quotient of division by x until a zero quotient is obtained.
Maintaining the UNDO List for an Application
Conversion of Number Bases  ¤NIIT Solving Programming Problems Using Stacks 7.29
The remainder after each division must be stored, and at the end, the remainders must be
written out in the reverse order. Again, since the remainders are required in the reverse
order, a LIFO list, that is, a stack can be used for storing the remainders after each
division.
For example, you need to convert the decimal number 24 with base 10 into a binary
number with base 2. The following table illustrates the conversion process.
Number to
be Divided
Divisor  Quotient Remainder  Stack Storing the
Remainder
24  2 12 0 0
12  2 6 0 00
6  2 3 0 000
3   2 1 1 0001
1  2 0  1 00011
Conversion Process
As shown in the preceding table, the remainders are stored in a stack. You now need to
pop the remainders one by one to get the remainders in the reverse order.
Popping the remainders, you get 11000. Therefore, the decimal number, 24 is equal to the
binary number 11000.
In various applications that use parenthesized expressions, you need to check whether the
nesting of parentheses in the expression is correct or not. You can do this by checking the
following two conditions:
„ The number of left paranthesis should be equal to the number of right paranthesis.
„ Each right parenthesis is preceded by a matching left paranthesis.
Consider the following expressions:
„ {(A + B) – (C × D}}: This expression is invalid because one right parenthesis does
not match its corresponding left parenthesis.
„ {(A + B) – (C × D): This expression is invalid because the number of left
parentheses is more than the number of right parentheses.
„ {(A + B) – (C × D)}]: This expression is invalid because the number of left
parentheses is less than the number of right parentheses.
Checking the Nesting of Parentheses in an Expression 7.30 Solving Programming Problems Using Stacks  ¤NIIT
Let us see how you can use a stack to check an expression for correct nesting of
parentheses. You start by scanning the expression from left to right. Every left
parentheses encountered is pushed onto a stack. Whenever a right parenthesis is
encountered, an entry is popped from the stack.
If the popped left parenthesis does not match the right parenthesis, the expression is
invalid. However, if the parentheses match, the next token is extracted from the
expression and the process continues till the entire expression has been scanned.
If during a pop operation, the stack is found to be empty, then it implies that the number
of right parentheses is more than the number of left parentheses.
If even at the end of the expression, the stack does not get empty, then it indicates that the
number of left parentheses is more than the number of right parentheses.
Consider the expression, {(A + B) – (C × D)}]. The following table depicts the process of
checking the validity of this expression.
Step No. Element Scanned Action Stack Contents
1 { Push in the stack {
2 ( Push in the stack { (
3 A Discard { (
4 + Discard { (
5 B Discard { (
6 ) Pop an item from the stack. The popped
left parenthesis matches the scanned
right parenthesis. Therefore, continue
{
7 – Discard {
8 ( Push in the stack { (
9 C Discard { (
10 × Discard { (
11 D Discard { (
12 ) Pop an item from the stack. The popped
left parenthesis matches the scanned
right parenthesis. Therefore, continue
{¤NIIT Solving Programming Problems Using Stacks 7.31
Step No. Element Scanned Action Stack Contents
13 } Pop an item from the stack. The popped
left parenthesis matches the scanned
right parenthesis. Therefore, continue
14 ] The stack is empty. Therefore, an item
cannot be popped from the stack.
Therefore, the number of left
parenthesis is less than the number of
right parenthesis
Checking the Validity of an Expression
Consider another example, {(A + B) – (C × D}). The following table depicts the process
of checking the validity of this expression.
Step No. Element Scanned Action Stack Contents
1 { Push in the stack {
2 ( Push in the stack { (
3 A Discard { (
4 + Discard { (
5 B Discard { (
6 ) Pop an item from the stack. The
popped left parenthesis matches
the scanned right parenthesis.
Therefore, continue
{
7 – Discard {
8 ( Push in the stack { (
9 C Discard { (
10 × Discard { (
11 D Discard { ( 7.32 Solving Programming Problems Using Stacks  ¤NIIT
Step No. Element Scanned Action Stack Contents
12 } Pop an item from the stack. The
popped left parenthesis does not
match the scanned right
parenthesis. Therefore, the
expression is invalid
{
Checking the Validity of an Expression
Stacks can be used to solve complex arithmetic expressions. Arithmetic expressions are
usually written in the infix notation, in which the operator is placed between the operands.
For example,
1 × 2 and 7 + 5
Here, the expression 1 × 2 will result in 2 and 7 + 5 will result in 12. However, there may
be expressions that have two or more operators, such as A + B × C. To evaluate such
expressions, you need to use parentheses to indicate the order in which the operations are
to be carried out.
For example, in the expression, A + B × C, if addition needs to be performed before
multiplication, the same needs to be specified with the aid of parentheses, as shown in the
following expression:
(A + B) × C
When infix notation is used, expressions are evaluated by using the general mathematics
rules for operator precedence like:
„ Parenthesis (highest precedence)
„ Exponentiation (second highest precedence)
„ Multiplication and division (third highest precedence)
„ Addition and subtraction (lowest precedence)
Another notation that is used for writing arithmetic expressions is the postfix notation. In
the infix notation, the operator is placed between the operands. However, in the postfix
notation, the operator is placed after the operands. Therefore, in the postfix notation, A +
B × C will be written as ABC × + and (A + B) × C will be written as AB + C ×.
This means that if an infix expression could be converted into a postfix expression,
parentheses would not be required to indicate the order of operations. Also, the relative
priority of operators would be automatically taken care of.
Evaluating Expressions  ¤NIIT Solving Programming Problems Using Stacks 7.33
Note
Therefore, the evaluation of an infix expression is done in two steps:
1. Conversion of the infix expression into a postfix expression
2. Evaluation of the postfix expression
Converting an Infix Expression to a Postfix Expression
To convert an infix expression to a postfix expression, you can use the following
algorithm:
1. Initialize the stack to be empty.
2. Initialize the postfix string to be empty.
3. Scan the entries in the infix expression from left to right until the end of the infix
expression is encountered:
a. If the scanned entry is:
i. An operand: Append the operand to the postfix string.
ii. An operator: Compare the precedence of the operator with the operator on
the top of the stack. If the precedence of the operator on the top of the stack
is greater than or equal to the precedence of the scanned operator, pop the
operator from the stack and append it to the postfix string. Repeat this step
until the operator at the top of the stack has a precedence less than the
scanned operator or the stack becomes empty. Finally, push the scanned
operator onto the stack.
iii. A left parenthesis: Push the left parenthesis onto the stack.
iv. A right parenthesis: Pop stack elements one by one and append them to
the postfix string until a left parenthesis is popped.
4.  Pop all entries from the stack and append them to the postfix expression.
The preceding algorithm assumes that the nesting of parentheses within the given infix
expression is correct.
Consider the following expression:
(A – B) – C + D × E + F 7.34 Solving Programming Problems Using Stacks  ¤NIIT
The following table depicts the steps that are required to convert an infix expression to a
postfix expression.
Step No. Entry Scanned Action  Stack
Contents
Postfix Expression
1 ( Push into the stack (
2 A Append to postfix
expression
( A
3 – The precedence of
‘(‘  is less than that
of ‘–‘. Therefore,
push ‘–‘ into the
stack
(– A
4 B Append to postfix
expression
(– AB
5 ) Pop entries from
stack and append to
postfix expression
until a left
parenthesis is
popped
AB –
6 – Push into the stack –  AB –
7 C Append to postfix
expression
– AB  –  C
8 + The precedence of
‘–‘ is less than that
of ‘+‘. Therefore,
push ‘+‘ into the
stack
–  + AB  –  C
9 D Append to postfix
expression
–  + AB  –  CD
10 × The precedence of
‘+‘ is less than that
of ‘ב. Therefore,
push ‘ב  into the
stack
–  + × AB  –  CD ¤NIIT Solving Programming Problems Using Stacks 7.35
Step No. Entry Scanned Action  Stack
Contents
Postfix Expression
11 E Append to postfix
expression
–  + × AB  –  CDE
12 + Pop entries from
stack and append to
postfix expression
until the entry at the
top of the stack has
precedence less than
the scanned entry.
Then push the
scanned entry into
the stack
– + AB  –  CDE × +
13 F Append to postfix
expression
– + AB  –  CDE × + F
14  End of infix
expression
encountered. Pop all
elements from the
stack and append to
the postfix
expression
AB –  CDE ×  + F
+ –
Conversion of Infix Expression to a Postfix Expression
Evaluation of the Postfix Expression
Once the infix expression is converted into a postfix expression, the next step is to
evaluate the postfix expression. To evaluate the postfix expression, you can use the
following algorithm:
1. Initialize the stack to be empty.
2.  Scan the entries in the postfix expression from left to right until the end of the postfix
expression is encountered:
a. If an operand is encountered, PUSH it into the stack.
b. If an operator is encountered:
i. POP the top two values.
ii. Operate the two values by using the operator.
iii. PUSH the result to the stack.
3. Get result from the top of the stack. 7.36 Solving Programming Problems Using Stacks  ¤NIIT
Consider the postfix expression:
A B C × + D –
To evaluate this postfix expression, consider the following values for the variables:
A = 2, B = 5, C = 7, and D = 3
Therefore, the expression becomes:
2 5 7 × + 3 –
The following table depicts the steps that are required to evaluate the given postfix
expression.
Evaluating the Postfix Expression
The final result of the expression can be obtained from the top of the stack. Therefore, the
result is 34.
Element Scanned Action Stack Contents
2 Push into the stack 2
5 Push into the stack 2, 5
7 Push into the stack 2, 5, 7
× Pop the top two values and
multiply them. Push the
result into the stack
2, 35
+ Pop the top two values and
add them. Push the result
into the stack
37
3 Push into the stack 37, 3
– Pop the top two values and
subtract them. Push the
result into the stack
34¤NIIT Solving Programming Problems Using Stacks 7.37
Problem Statement
Write a program that accepts an infix expression, and then converts it into a postfix
expression. You can assume that the entered expression is a valid infix expression.
Solution
The following is the program to convert an infix expression to a postfix expression:
// Code in C#
using System;
using System.Text;
namespace InToPost
{
class stack
{
public char[] stack_array = new char[50];
public int top;
public stack()
{
top = – 1;
}
public void push(char symbol)
{
if (full())
{
Console.WriteLine(“\nStack overflow”);
}
else
{
top = top + 1;
stack_array[top] = symbol;
}
}
public char pop()
{
if (empty())
return (‘#’);   /* Return value ‘#’ indicates stack
empty */
else
return (stack_array[top –]);
Activity: Converting an Infix Expression into a Postfix
Expression 7.38 Solving Programming Problems Using Stacks  ¤NIIT
}
public bool empty()
{
if (top == –1)
return (true);
else
return (false);
}
public bool full()
{
if (top == 49)
return (true);
else
return (false);
}
}
class Expression
{
char[] infix = new char[50];
char[] postfix = new char[50];
public void read()
{
Console.Write(“\nEnter an infix expression: “);
infix = Console.ReadLine().ToCharArray();
}
public void ConvertToPostfix()
{
stack s = new stack();
int l, precedence, p;
char entry1, entry2;
l = infix.Length;
p = 0;
for (int i = 0; i < l; i++)
{
entry1 = infix[i];
if (!white_space(entry1))
{
switch (entry1)
{
case ‘(‘:
s.push(entry1);
break;
case ‘)’:
while ((entry2 = s.pop()) != ‘(‘)
postfix[p++] = entry2;
break;
case ‘+’: ¤NIIT Solving Programming Problems Using Stacks 7.39
case ‘–’:
case ‘×’:
case ‘/’:
if (!s.empty())
{
precedence = prec(entry1);
entry2 = s.pop();
while (precedence <= prec(entry2))
{
postfix[p++] = entry2;
if (!s.empty())
entry2 = s.pop();
else
break;
}
if (precedence > prec(entry2))
s.push(entry2);
}
s.push(entry1);
break;
default:
postfix[p++] = entry1;
break;
}
}
}
while (!s.empty())// While not stack empty
postfix[p++] = s.pop();
postfix[p] = ”;
string str = “”;
foreach (char c in postfix)
{
if (c != ”)
str = str + c;
else
break;
}
Console.WriteLine(“\nThe postfix expression is : ” + str);
}
public int prec(char symbol)
{
switch (symbol)
{
case ‘/’: return (4);  /* Precedence of / is 4 */
case ‘×’: return (3);  /* Precedence of × is 3 */
case ‘+’: return (2);  /* Precedence of + is 2 */
case ‘–’: return (1);  /* Precedence of – is 1 */
case ‘(‘: return (0);  /* Precedence of ( is 0 */
default: return (-1);
} 7.40 Solving Programming Problems Using Stacks  ¤NIIT
}
public bool white_space(char symbol)
{
if (symbol == ‘ ‘ || symbol == ‘\t’ || symbol == ”)
return true;
else
return false;
}
private bool openingParenthesis(char entry)
{
if ((entry == ‘(‘) || (entry == ‘{‘) || (entry == ‘[‘))
return (true);
else
return (false);
}
private bool closingParenthesis(char entry)
{
if ((entry == ‘)’) || (entry == ‘}’) || (entry == ‘]’))
return (true);
else
return (false);
}
private bool match(char entry1, char entry2)
{
if ((entry1 == ‘(‘) && (entry2 == ‘)’))
return (true);
else if ((entry1 == ‘{‘) && (entry2 == ‘}’))
return (true);
else if ((entry1 == ‘[‘) && (entry2 == ‘]’))
return (true);
else
return (false);
}
static void Main(string[] args)
{
Expression exp = new Expression();
char choice = ‘y’;
while (choice == ‘y’)
{
exp.read();
exp.ConvertToPostfix();
Console.Write(“\nDo you want to continue? (y/n): “);
choice = Char.Parse(Console.ReadLine());
}
}
}
}¤NIIT Solving Programming Problems Using Stacks 7.41
// Code in C++
#include <iostream.h>
class stack
{
public:
char stack_array [50];
int top;
stack()
{
top = -1;
}
void push(char symbol)
{
if (full())
{
cout << “\nStack overflow”<< endl;
}
else
{
top = top + 1;
stack_array[top] = symbol;
}
}
char pop()
{
if (empty())
return (‘#’);   // Return value ‘#’ indicates stack empty
else
return (stack_array[top–]);
}
int empty()
{
if (top == –1)
return (1);
else
return (0);
}
int full()
{
if (top == 49)
return (1);
else
return (0);
}
};7.42 Solving Programming Problems Using Stacks  ¤NIIT
class Expression
{
char infix[50];
char postfix[50];
public:
void read()
{
cout << “\nEnter an infix expression: “;
cin >> infix;
}
int white_space(char symbol)
{
if (symbol == ‘ ‘ || symbol == ‘\t’ || symbol == ”)
return 1;
else
return 0;
}
void ConvertToPostfix()
{
stack s;
int l, precedence, p;
char entry1, entry2;

p = 0;
for (int i = 0; infix[i] != ”; i++)
{
entry1 = infix[i];
if (!white_space(entry1))
{
switch (entry1)
{
case ‘(‘:
s.push(entry1);
break;
case ‘)’:
while ((entry2 = s.pop()) != ‘(‘)
postfix[p++] = entry2;
break;
case ‘+’:
case ‘–’:
case ‘×’:
case ‘/’:
if (!s.empty())
{
precedence = prec(entry1);
entry2 = s.pop();
while (precedence <= prec(entry2)) ¤NIIT Solving Programming Problems Using Stacks 7.43
{
postfix[p++] = entry2;
if (!s.empty())
entry2 = s.pop();
else
break;
}
if (precedence > prec(entry2))
s.push(entry2);
}
s.push(entry1);
break;
default:
postfix[p++] = entry1;
break;
}
}
}
while (!s.empty())//While not stack empty
postfix[p++] = s.pop();
postfix[p] = ”;

cout << “\nThe postfix expression is: ” << postfix << endl;
}
int prec(char symbol)
{
switch (symbol)
{
case ‘/’: return (4);  /* Precedence of / is 4 */
case ‘×’: return (3);  /* Precedence of × is 3 */
case ‘+’: return (2);  /* Precedence of + is 2 */
case ‘–’: return (1);  /* Precedence of – is 1 */
case ‘(‘: return (0);  /* Precedence of ( is 0 */
default: return (–1);
}
}
};
void main()
{
char choice = ‘y’;
Expression expr;
while (choice == ‘y’)
{
expr.read();
expr.ConvertToPostfix();
cout << “\nDo you want to continue? (y/n): “;
cin >> choice;
}
}7.44 Solving Programming Problems Using Stacks  ¤NIIT
1. The operations of adding and removing an item to and from a stack are also called
as _________ and ________ operation.
a. INSERT, DELETE
b. PUSH, PULL
c. PUSH, POP
d. ADD, DELETE
2. Which of the following will be the output of the given postfix expression? The
expression is 3 8 9 × + 4 –.
a. 71
b. 65
c. 73
d. 75
3. Which of the following will be the postfix expression for the given infix expression?
The infix expression is ((C + (D × E)) – F).
a. C D E × + F –
b. C D E + × F –
c. C D F × + E –
d. D C F × + E –
4. Briefly discuss the applications of a stack.
5. Consider the following statements:
Statement A: A stack is a collection of data items that can be accessed at only one
end, called a top.
Statement B: In a stack, data cannot be deleted from the middle of the stack without
first removing all items from the top.
Which of the following statements are true?
a. Statement A is true, and statement B is false.
b. Statement A is false, and statement B is true.
c. Both statement A and statement B are true.
d. Both statement A and statement B are false.
Practice Questions ¤NIIT Solving Programming Problems Using Stacks 7.45
In this chapter, you learned that:
„ A stack is a collection of data items that can be accessed at only one end, called top.
The last item inserted in a stack is the first one to be deleted.
„ A stack is called a LIFO data structure.
„ There are two operations that can be performed on stacks. They are:
z PUSH
z POP
„ Stacks can be implemented by using both arrays and linked lists.
„ Stacks are used in many applications. Some of the application domains of stacks are
as follows:
z Implementing function calls
z Maintaining the UNDO list for an application
z Conversion of number bases
z Checking the nesting of parenthesis in an expression
z Evaluating expressions
Summary 7.46 Solving Programming Problems Using Stacks  ¤NIIT
Exercise 1
You are given a program that converts a given infix expression to a postfix expression.
Include functionality in the given program for checking whether the parentheses in the
entered infix expression are correctly nested.
Exercise 2
Write a program to reverse a string by using a stack.
Exercises

Solving
Programming
Problems Using
Linked Lists – II
Chapter 6
A linked list provides a memory-efficient
mechanism for storing data. However, there are
certain situations in which a linked list proves to be
very inefficient in terms of execution time. In such a
case, you can improve the efficiency of a linked list
by using certain variants of a linked list.
This chapter discusses the implementation of two
variants of a linked list called doubly-linked list and
circular linked list.
In this chapter, you will learn to:
 Implement a doubly-linked list
 Implement a circular linked list
Objectives ¤NIIT Solving Programming Problems Using Linked Lists – II 6.3
Consider that you need to implement a singly-linked list to store the marks of students in
an ascending order. To display the marks of the students in the ascending order, you can
simply traverse the list starting from the first node.
Now consider another case where you need to display these marks in a descending order.
This problem could be easily solved if you could traverse the list in the reverse direction.
However, because each node in a singly-linked list contains the address of the next node
in sequence, traversal is possible in the forward direction only.
To solve this problem, each node in a linked list can be made to hold the reference of its
preceding node in addition to its next node in sequence. Such type of linked list is known
as doubly-linked list. In a doubly-linked list, each node contains the address of its next
node as well as its previous node. This allows the flexibility to traverse in both directions.
The various operations in a doubly-linked list include insertion, deletion, search, and
traversal.
A doubly-linked list in a program can be represented by declaring two classes. They are
as follows:
„ Node class: In a doubly-linked list, each node needs to store:
z The information
z The address of the next node in sequence
z The address of the previous node
Therefore, in addition to the data elements, the Node class declares two
variables/pointers, next and prev, to hold the addresses of its next and previous
nodes respectively. The first node in the list contains NULL in its prev
variable/pointer, and the address of the next node in its next variable/pointer.
Similarly, the last node in the list contains NULL in its next variable/pointer, and the
address of the previous node in its prev variable/pointer.
Implementing a Doubly-Linked List
Representing a Doubly-Linked List 6.4 Solving Programming Problems Using Linked Lists – II  ¤NIIT
Refer to the following figure for the structure of a node in a doubly-linked list.
Structure of a Node in a Doubly-Linked List
Consider the following declaration of the Node class in C# and C++:
// Code in C#
class Node
{
public int info;
public Node next;
public Node prev;
}
// Code in C++
class Node
{
public:
int info;
Node * next;
Node * prev;
};
„ DoubleLinkedList class: This class consists of a set of operations implemented on a
linked list. In addition, it declares a variable/pointer, START, which will always point
to the first node in the list. Consider the following declaration of the
DoubleLinkedList class in C# and C++:
// Code in C#
class DoubleLinkedList
{
Node START;
DoubleLinkedList(){}
public void addNode(int element){}
public bool search(int element, ref Node previous, ref Node
current){}
public bool delNode(int element){}
public void traverse() {} ¤NIIT Solving Programming Problems Using Linked Lists – II 6.5
Just a minute:
Note
public void revtraverse(){}
}
// Code in C++
class DoubleLinkedList
{
Node *START;
public:
DoubleLinkedList();
void addNode(int element);
bool search(int element, Node *previous, Node *current);
bool delNode(int element);
void traverse();
void revtraverse();
};
In addition to the variable/pointer START that holds the address of the first node in the
list, you may also want to declare a variable/pointer LAST that holds the address of the
last node in the list. Whether or not to declare this variable/pointer would depend on
the problem at hand. If the problem requires you to frequently insert and delete
elements at the end of the list, or traverse the list in the reverse order, it would be
prudent to use a variable/pointer LAST that holds the address of the last node in the
list.
How does the representation of a node in a doubly-linked list differ from that in a
singly-linked list?
Answer:
Unlike singly-linked list, in which each node stores the address of only the next node in
the list, each node in a doubly-linked list holds the address of its previous node also. 6.6 Solving Programming Problems Using Linked Lists – II  ¤NIIT
Doubly-linked list enables you to traverse the list in forward as well as backward
direction.
The algorithm for traversing a doubly-linked list in the forward direction is as follows:
1. Mark the first node in the list as currentNode.
2. Repeat steps 3 and 4 until currentNode becomes NULL.
3. Display the information contained in the node marked as currentNode.
4. Make currentNode point to the next node in sequence.
Please note that the algorithm for traversing a doubly-linked list in the forward direction
is same as that for a singly-linked list.
The algorithm for traversing a doubly-linked list in the backward direction is as follows:
1. Mark the last node in the list as currentNode.
2. Repeat steps 3 and 4 until currentNode becomes NULL.
3. Display the information contained in the node marked as currentNode.
4. Make currentNode point to the node preceding it.
Insertion involves adding a new node to an existing list or creating a new list if one does
not already exist. Therefore, to insert a node in a doubly-linked list you need to first check
whether the list is empty or not.
If the list is empty, the following algorithm can be used to insert a node in the linked list:
1. Allocate memory for the new node.
2. Assign a value to the data field of the new node.
3. Make the next field of the new node point to NULL.
4. Make the prev field of the new node point to NULL.
5. Make START point to the new node.
Once the first node is inserted, subsequent nodes can be inserted at any of the following
positions:
„ Beginning of the list
„ Between two nodes in the list
„ End of the list
Now you will write algorithms for inserting a node at various positions in a linked list.
Traversing a Doubly-Linked List
Inserting Nodes in a Doubly-Linked List ¤NIIT Solving Programming Problems Using Linked Lists – II 6.7
Inserting a Node at the Beginning of the List
The algorithm for inserting a node in the beginning of the doubly-linked list is as follows:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. Make the next field of the new node point to the first node in the list.
4. Make the prev field of START point to the new node.
5. Make the prev field of the new node point to NULL.
6. Make START point to the new node.
Inserting a Node Between Two Nodes in the List
To insert a node between two nodes, you first need to search the nodes between which the
new node is to be inserted, and mark them as previous and current. The algorithm for
inserting a node between two nodes in a doubly-linked list is as follows:
1. Identify the nodes between which the new node is to be inserted. Mark them as
previous and current respectively. To locate previous and current, execute the
following steps:
a. Make current point to the first node.
b. Make previous point to NULL.
c. Repeat step d and step e until current.info > newnode.info or current = NULL.
d. Make previous point to current.
e. Make current point to the next node in sequence.
2. Allocate memory for the new node.
3. Assign value to the data field of the new node.
4. Make the next field of the new node point to current.
5. Make the prev field of the new node point to previous.
6. Make the prev field of current point to the new node.
7. Make the next field of previous point to the new node. 6.8 Solving Programming Problems Using Linked Lists – II  ¤NIIT
The process of inserting a node between two nodes in a doubly-linked list is illustrated in
the following table.
Operation Illustration
Allocate memory for the
new node, and assign value
to the data field of new
node.
Make the next field of new
node point to current.
Make prev field of new
node point to previous. ¤NIIT Solving Programming Problems Using Linked Lists – II 6.9
Operation Illustration
Make the prev field of
current point to the new
node.
Make the next field of
previous point to the new
node.
Inserting a Node Between Two Nodes in a Doubly-Linked List
If after the initial search operation, current is found to be NULL, it means that the node is
to be inserted at the end of the list. In this case, step 6 will give an error. This is because
NULL cannot have a prev field. Therefore, the preceding algorithm cannot be used to
insert a node at the end of the list.
However, you can modify the preceding algorithm to solve this problem. Consider the
following algorithm:
1. Identify the nodes between which the new node is to be inserted. Mark them as
previous and current respectively. To locate previous and current, execute the
following steps:
a. Make current point to the first node.
b. Make previous point to NULL.
c. Repeat step d and step e until current.info > newnode.info or current = NULL.
d. Make previous point to current.
e. Make current point to the next node in sequence. 6.10 Solving Programming Problems Using Linked Lists – II  ¤NIIT
2. Allocate memory for the new node.
3. Assign value to the data field of the new node.
4. Make the next field of the new node point to current.
5. Make the prev field of the new node point to previous.
6. If current is not NULL:
a. Make the prev field of current point to the new node.
7. Make the next field of previous point to the new node.
The preceding algorithm can now also be used to insert nodes at the end of the linked list.
The process of inserting a node at the end of the linked list is illustrated in the following
table.
Operation Illustration
Allocate memory and
assign value to the
data field of the new
node.
Make the next field of
the new node point to
current. ¤NIIT Solving Programming Problems Using Linked Lists – II 6.11
Operation Illustration
Make the prev field of
the new node point to
previous.
Make the next field of
previous point to the
new node.
Inserting a Node at the End of a Doubly-Linked List
Inserting a Node at the End of the List
The algorithm for inserting a node between two nodes in a doubly-linked list can also be
used to insert a node at the end of list. However, if you always have to insert a node at the
end of the list only, it would be better to have a variable/pointer LAST that contains the
address of the last node in the list. You can then use the following algorithm to insert a
node at the end of the list:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. Make the next field of the node marked as LAST point to the new node.
4. Make the prev field of new node point to node marked LAST.
5. Make the next field of the new node point to NULL.
6. Mark the new node as LAST. 6.12 Solving Programming Problems Using Linked Lists – II  ¤NIIT
The delete operation in a doubly-linked list is a bit different from that of a singly-linked
list. This is because, in contrast to a singly-linked list, each node in a doubly-linked list
has an additional field pointing to its previous node. Therefore, you need to adjust both
the fields while performing the delete operation.
Before performing the delete operation, you first need to check whether the list is empty.
If the list is empty, an error message is shown.
However, if the list is not empty, then you need to identify the position of the node to be
deleted in the list. You can delete a node from one of the following places in a
doubly-linked list:
„ Beginning of the list
„ Between two nodes in the list
„ End of the list
Deleting a Node from the Beginning of the List
The algorithm to delete a node from the beginning of a doubly-linked list is as follows:
1. Mark the first node in the list as current.
2. Make START point to the next node in its sequence.
3. If START is not NULL: // If the node to be deleted is not the only node in the list
a. Assign NULL to the prev field of the node marked as START.
4. Release the memory of the node marked as current.
The process of deleting a node from the beginning of a doubly-linked list is illustrated in
the following table.
Operation Illustration
Mark the first node in the list as
current.
Deleting Nodes from a Doubly-Linked List ¤NIIT Solving Programming Problems Using Linked Lists – II 6.13
Operation Illustration
Make START point to the next
node in its sequence.
Assign NULL to the prev field of
the node marked as START.
Release the memory of the node
marked as current.
Deleting a Node from the Beginning of a Doubly-Linked List
Deleting a Node Between Two Nodes in the List
To delete a node between two nodes in the list, you first need to search the node to be
deleted. Once found, mark the node to be deleted as current, and its predecessor as
previous. The algorithm to delete a node from the middle of a doubly-linked list is as
follows:
1. Mark the node to be deleted as current and its predecessor as previous. To locate
previous and current, execute the following steps:
a. Make previous point to NULL. // Set previous = NULL
b. Make current point to the first node in the linked list. // Set current = START
c. Repeat steps d and e until either the node is found or current becomes NULL.
d. Make previous point to current.
e. Make current point to the next node in sequence.
2. Make the next field of previous point to the successor of current.
3. Make the prev field of the successor of current point to previous. 6.14 Solving Programming Problems Using Linked Lists – II  ¤NIIT
4. Release the memory of the node marked as current.
The process of deleting a node between two nodes in a doubly-linked list is illustrated in
the following table.
Operation Illustration
Make the next field of
previous point to the
successor of current.
Make the prev field of the
successor of current point to
previous.
Release the memory of the
node marked as current.
Deleting a Node Between Two Nodes in a Doubly-Linked List
If after the initial search operation, the next field of current is found to have a NULL
value, it means that the node is to be deleted from the end of the list. In this case, step 3
will give an error. This is because the successor of current is NULL and therefore, it
cannot have a prev field. Therefore, the preceding algorithm cannot be used to insert a
node at the end of the list. ¤NIIT Solving Programming Problems Using Linked Lists – II 6.15
However, you can modify the preceding algorithm to solve this problem. Consider the
following algorithm:
1. Mark the node to be deleted as current, and its predecessor as previous.
2. Make the next field of previous point to the successor of current.
3. If the successor of current exists:
a. Make the prev field of the successor of current point to previous.
4. Release the memory of the node marked as current. 6.16 Solving Programming Problems Using Linked Lists – II  ¤NIIT
Consider that you are developing an action game in which a player is given a set of n
weapons. Each weapon appears on the screen after a specific time period. The player is
required to select the weapon within 10 seconds or else the weapon becomes unusable.
Once the nth
weapon is displayed, the weapon that came first is displayed again, and the
sequence continues as before.
You can store the references of these weapons in a singly-linked list. Now, when the last
weapon is displayed, the pointer needs to be shifted back to the first weapon in the list. In
a singly-linked list, once you reach the end of the list, you cannot move further.
Therefore, to move back to the first weapon, you need to reinitialize the variable/pointer
to the first node in the list.
Therefore, a better approach is to link the last node with the first node in the list. By doing
so, you do not have to reinitialize the variable/pointer every time you reach the end of the
list. Such a type of list is known as a circular linked list.
A circular linked list is different from a singly-linked list in terms of the address field of
the last node. Unlike singly-linked list, the last node in a circular linked list does not point
to NULL. Instead, the last node holds the reference of the first node in the list. This gives
the list a circular structure.
The various operations on circular linked lists are insertion, deletion, search, and
traversal.
Representation of a circular linked list is similar to a singly-linked list. To implement a
circular linked list, a variable/pointer, LAST, is maintained that always points to the last
node in the list. The next field of LAST points to the first node in the list.
The following figure depicts the structure of a circular linked list.
Circular Linked List
Implementing a Circular Linked List
Representing a Circular Linked List ¤NIIT Solving Programming Problems Using Linked Lists – II 6.17
To represent a circular linked list, you need to declare two classes, Node and List:
„ Node class: The declaration of the Node class of a circular linked list is the same as
that of a singly-linked list.
„ List class: This class consists of a set of operations implemented on a linked list.
These operations are insertion, deletion, search, and traversal. It also contains the
declaration of a variable/pointer, LAST, that always points to the last node in the list.
When the list is empty, LAST points to NULL. Consider the following declaration of
the List class in C# and C++:
// Code in C#
class List
{
private Node LAST;
List()
{
LAST = NULL;
}
public void addNode(int element)
{
// Statements
}

public bool search(int element, ref Node previous, ref Node
current)
{
// Statements
}
public bool delNode(int element)
{
// Statements
}
public void traverse()
{
// Statements
}
}
// Code in C++
class List
{
Node * LAST;
public:
List()
{
LAST = NULL;
}
void addNode(int element); 6.18 Solving Programming Problems Using Linked Lists – II  ¤NIIT
bool search(int element, Node *previous, Node *current);
bool delNode(int element);
void traverse();
};
For traversing a circular linked list, you need to keep track of a variable/pointer
currentNode, which initially points to the first node in the list. Now with the help of
currentNode, you can traverse the list until the last node is reached.
The algorithm for traversing a circular linked list is as follows:
1. Make currentNode point to the successor of the node marked as LAST, such that
currentNode points to the first node in the list.
2. Repeat step 3 and 4 until currentNode = LAST.
3. Display the information contained in the node marked as currentNode.
4. Make currentNode point to the next node in its sequence.
5. Display the information contained in the node marked as LAST.
Insertion in a circular linked list refers to the process of adding a new node in the list or
creating a new linked list if one does not already exist. Therefore, to insert a node in a
circular linked list, you need to first check whether the list is empty or not.
If the list is empty, the following algorithm can be used to insert a node in the linked list:
1. Allocate memory for the new node.
2. Assign a value to the data field of the new node.
3. Make LAST point to the new node.
4. Make the next field of new node point to the new node.
If the list is not empty, you can insert a new node at any of the following positions:
„ Beginning of the list
„ End of the list
„ Between two nodes in the list
Inserting a Node at the Beginning of the List
The algorithm for inserting a node in the beginning of a circular linked list is as follows:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
Traversing a Circular Linked List
Inserting a Node in a Circular Linked List ¤NIIT Solving Programming Problems Using Linked Lists – II 6.19
3. Make the next field of the new node point to the successor of LAST.
4. Make the next field of LAST point to the new node.
The process of inserting a node at the beginning of a circular linked list is illustrated in the
following table.
Operation Illustration
Allocate memory,
and assign value to
the data field of the
new node.
Make the next field of
the new node point to
the successor of
LAST.
Make the next field of
LAST point to the
new node.
Inserting Node in the Beginning of a Circular Linked List 6.20 Solving Programming Problems Using Linked Lists – II  ¤NIIT
Inserting a Node Between Two Nodes in the List
The algorithm for inserting a node between two nodes in a circular linked list is as
follows:
1. Identify the nodes between which the new node is to be inserted. Mark them as
previous and current. To locate previous and current, execute the following steps:
a. Make current point to the first node.
b. Make previous point to NULL.
c. Repeat step d and step e until current.info > newnode.info or previous = LAST.
d. Make previous point to current.
e. Make current point to the next node in sequence.
2. Allocate memory for the new node.
3. Assign value to the data field of the new node.
4. Make the next field of the new node point to current.
5. Make the next field of previous point to the new node.
The process of inserting a node between two nodes in a circular linked list is illustrated in
the following table.
Operation Illustration
Identify the nodes
between which the new
node is to be inserted.
Mark them as previous
and current.
Allocate memory and
assign value to the
data field of the new
node. ¤NIIT Solving Programming Problems Using Linked Lists – II 6.21
Operation Illustration
Make the next field of
the new node point to
current.
Make the next field of
previous point to the
new node.
Inserting a Node Between Two Nodes in a Circular Linked List
Inserting a Node at the End of the List
The algorithm for inserting a node at the end of the list is as follows:
1. Allocate memory for the new node.
2. Assign value to the data field of the new node.
3. Make the next field of the new node point to the successor of LAST.
4. Make the next field of LAST point to the new node.
5. Make LAST point to the new node. 6.22 Solving Programming Problems Using Linked Lists – II  ¤NIIT
The process of inserting a node at the end of a circular linked list is illustrated in the
following table.
Operation Illustration
Allocate memory
and assign value
to the data field of
the new node.
Make the next
field of the new
node point to the
successor of
LAST.
Make the next
field of LAST
point to the new
node. ¤NIIT Solving Programming Problems Using Linked Lists – II 6.23
Operation Illustration
Make LAST point
to the new node.
Inserting a Node at the End of a Circular Linked List
Before performing the delete operation, you need to first search the node that has to be
deleted. If the specified node is not found in the list, an error message is shown.
You can delete a node from one of the following places in a linked list:
„ Beginning of the list
„ End of the list
„ Between two nodes in the list
Deleting a Node from the Beginning of the List
The algorithm to delete a node from the beginning of the list is as follows:
1. If the node to be deleted is the only node in the list: // If LAST points to itself
a. Mark LAST as NULL
b. Exit
2. Make current point to the successor of LAST
3. Make the next field of LAST point to the successor of current
4. Release the memory for the node marked as current
Deleting a Node from a Circular Linked List 6.24 Solving Programming Problems Using Linked Lists – II  ¤NIIT
The process of deleting a node from the beginning of a circular linked list is illustrated in
the following table.
Operation Illustration
Make current point to
the successor of LAST.
Make the next field of
LAST point to the
successor of current.
Release the memory
for the node marked as
current.
Deleting a Node from the Beginning of a Circular Linked List
Deleting a Node from the End of the List
The algorithm for deleting a node from the end of a circular linked list is as follows:
1. Make current point to LAST.
2. Mark the predecessor of LAST as previous. To locate the predecessor of LAST
execute the following steps:
a. Make previous point to the successor of LAST.
b. Repeat step c until the successor of previous becomes LAST.
c. Make previous point to the next node in its sequence. ¤NIIT Solving Programming Problems Using Linked Lists – II 6.25
3. Make the next field of previous point to the successor of LAST.
4. Mark previous as LAST.
5. Release the memory of the node marked as current.
The process of deleting a node at the end of a circular linked list is illustrated in the
following table.
Operation Illustration
Make current point to
LAST. Mark the
predecessor of LAST as
previous.
Make the next field of
previous point to the
successor of LAST.
Mark previous as LAST.
Release the memory of the
node marked as current.
Deleting a Node at the End of a Circular Linked List 6.26 Solving Programming Problems Using Linked Lists – II  ¤NIIT
Deleting a Node Between Two Nodes in the List
The algorithm for deleting a node between two nodes in a circular linked list is as follows:
1. Locate the node to be deleted. Mark the node to be deleted as current, and its
predecessor as previous. To locate current and previous, execute the following steps:
a. Make previous point to the successor of LAST
b. Make current point to the successor of LAST
c. Repeat steps d and e until either the node is found, or previous = LAST
d. Make previous point to current
e. Make current point to the next node in sequence
2. If previous = LAST:
a. Display “Node not found”
b. Go to Step 5
3. Make the next field of previous point to the successor of current
4. Release the memory for the node marked as current
5. Exit
The process of deleting a node between two nodes in a circular linked list is illustrated in
the following table.
Operation Illustration
Locate the node to be
deleted. Mark the node to
be deleted as current and
its predecessor as
previous.
Make the next field of
previous point to the
successor of current. ¤NIIT Solving Programming Problems Using Linked Lists – II 6.27
Note
Operation Illustration
Release the memory for
the node marked as
current.
Deleting a Node Between Two Nodes in a Circular Linked List
A doubly-linked list can be made circular by:
„ Assigning the address of the first node in the next field of the last node
„ Assigning the address of the last node in the prev field of the first node 6.28 Solving Programming Problems Using Linked Lists – II  ¤NIIT
1. To which of the following does the last node in a circular linked list point?
a. NULL
b. First Node
c. START
d. There is no last node in a Circular List
2. Briefly discuss the advantage of a circular linked list as compared to a singly-linked
list.
3. Consider the following code snippet:
// Code in C#
void del()
{
node temp;
temp=START;
START=START.next;
}
// Code in C++
void del(void)
{
node *temp;
temp=START;
START=START->next;
delete temp;
}
Which of the following is correct for the preceding code snippet?
a. It deletes a node from the end of a singly-linked list.
b. It deletes a node from the beginning of a circular linked list.
c. It deletes a node from the beginning of a singly-linked list.
d. It deletes a node from the end of a circular linked list.
Practice Questions ¤NIIT Solving Programming Problems Using Linked Lists – II 6.29
4. Consider the following two statements:
Statement A: A doubly-linked list cannot be circular.
Statement B: The prev pointer is needed only for a singly-linked list.
a. Both A and B are false
b. A is false, B is true
c. Both A and B are true
d. A is true, B is false
5. List one advantage and one disadvantage of a doubly-linked list as compared to a
singly-linked list. 6.30 Solving Programming Problems Using Linked Lists – II  ¤NIIT
In this chapter, you learned that:
„ In a doubly-linked list, each node needs to store:
z The information
z The address of the next node in sequence
z The address of the previous node
„ Doubly-linked list enables you to traverse the list in forward as well as backward
direction.
„ A singly-linked list can be made circular by making the last node in the list point
back to the first node in the list.
Summary ¤NIIT Solving Programming Problems Using Linked Lists – II 6.31
Exercise 1
You are given an incomplete program that implements a doubly-linked list to store the
records of students in a class. Each record holds the following information:
„ Roll number of the student
„ Name of the student
Complete the program by including the functions for insertion and deletion of a node in a
doubly-linked list.
// Code in C#
using System;
using System.Text;
namespace Doubly_Linked_List_CSharp
{
class Node
{
/* Node class represents the node of doubly-linked list. It
consists of the information part and links to its succeeding
and preceeding nodes in terms of next and previous nodes. */
public int rollNumber;
public string name;
public Node next; /* Points to the succeeding node */
public Node prev; /* Points to the preceeding node */
}
class DoubleLinkedList
{
Node START;
public DoubleLinkedList()
{
START = null;
}
public bool Search(int rollNo, ref Node previous, ref Node
current) /* Checks wheteher the specified node is present */
{
for (previous = current = START; current != null &&
rollNo != current.rollNumber; previous = current, current
= current.next)
{ }
/* The preceding for loop traverses the list. If the
specified node is found then the function returns true,
otherwise false.*/
return (current != null);
}
public void traverse() /* Traverses the list */
Exercises 6.32 Solving Programming Problems Using Linked Lists – II  ¤NIIT
{
if (listEmpty())
Console.WriteLine(“\nList is empty”);
else
{
Console.WriteLine(“\nRecords in the ascending order
of roll numbers are:\n”);
Node currentNode;
for (currentNode = START; currentNode != null;
currentNode = currentNode.next)
Console.Write(currentNode.rollNumber + ”   ” +
currentNode.name + “\n”);
}
}
public void revtraverse() /* Traverses the list in the
reverse direction */
{
if (listEmpty())
Console.WriteLine(“\nList is empty”);
else
{
Console.WriteLine(“\nRecords in the descending order
of roll numbers are:\n”);
Node currentNode;
for (currentNode = START; currentNode.next != null;
currentNode = currentNode.next)
{ }
while (currentNode != null)
{
Console.Write(currentNode.rollNumber + ”   ” +
currentNode.name + “\n”);
currentNode = currentNode.prev;
}
}
}
public bool listEmpty()
{
if (START == null)
return true;
else
return false;
}
static void Main(string[] args)
{
DoubleLinkedList obj = new DoubleLinkedList();
while (true)
{
try
{
Console.WriteLine(“\nMenu”);
Console.WriteLine(“1. View all records in the
ascending order of roll numbers”);
Console.WriteLine(“2. View all records in the
descending order of roll numbers”); ¤NIIT Solving Programming Problems Using Linked Lists – II 6.33
Console.WriteLine(“3. Search for a record in the
list”);
Console.WriteLine(“4. Exit\n”);
Console.Write(“Enter your choice (1-4): “);
char ch = Convert.ToChar(Console.ReadLine());
switch (ch)
{
case ‘1’:
{
obj.traverse();
}
break;
case ‘2’:
{
obj.revtraverse();
}
break;
case ‘3’:
{
if (obj.listEmpty() == true)
{
Console.WriteLine(“\nList is
empty”);
break;
}
Node prev, curr;
prev = curr = null;
Console.Write(“\nEnter the roll
number of the student whose record
you want to search: “);
int num =
Convert.ToInt32(Console.ReadLine());
if (obj.Search(num, ref prev, ref
curr) == false)
Console.WriteLine(“\nRecord not
found”);
else
{
Console.WriteLine(“\nRecord found”);
Console.WriteLine(“\nRoll number: ” +
curr.rollNumber);
Console.WriteLine(“\nName: ” +
curr.name);
}
}
break;
case ‘4’:
return;
default:
{
Console.WriteLine(“\nInvalid
option”);
}
break;
} 6.34 Solving Programming Problems Using Linked Lists – II  ¤NIIT
}
catch (Exception e)
{
Console.WriteLine(“Check for the values
entered.”);
}
}
}
}
}
// Code in C++
#include<iostream.h>
class Node
{
/* Node class represents the node of doubly-linked list. It
consists of the information part and links to its succeeding and
preceeding nodes in terms of next and previous nodes.*/
public:
int rollNumber;
char name[20];
Node * next; /* Points to the succeeding node */
Node *prev; /* Points to the preceeding node */
};
class DoubleLinkedList
{
Node *START;
public:
DoubleLinkedList();
bool Search(int rollNo, Node **previous, Node **current);
bool listEmpty();
void traverse();
void revtraverse();
};
DoubleLinkedList :: DoubleLinkedList()
{
START=NULL;
}
bool DoubleLinkedList :: Search(int rollNo, Node **previous, Node
**current) /* Checks wheteher the specified node is present */¤NIIT Solving Programming Problems Using Linked Lists – II 6.35
{

for(*previous=*current=START;*current !=NULL && rollNo !=
(*current)->rollNumber;*previous=*current,*current=(*current)
->next){}
return(*current!=NULL);
}
bool DoubleLinkedList :: listEmpty()
{
if (START == NULL)
return true;
else
return false;
}
void DoubleLinkedList :: traverse() /* Traverses the list */
{
if(listEmpty())
cout<<“\nList is empty.\n”;
else
{
cout<<“\nRecords in the ascending order of roll numbers
are:\n”<<endl;
Node * currentNode;
for(currentNode=START;currentNode!=NULL;
currentNode=currentNode->next)
{
cout<<currentNode->rollNumber<<”   “<<
currentNode->name<<“\n”;
}
}
}
void DoubleLinkedList :: revtraverse() /* Traverses the list in the
reverse direction */
{
if(listEmpty())
cout<<“\nList is empty.\n”;
else
{ 6.36 Solving Programming Problems Using Linked Lists – II  ¤NIIT
cout<<“\nRecords in the descending order of roll numbers
are:\n”<<endl;
Node * currentNode;
for(currentNode=START;currentNode
->next!=NULL;currentNode=currentNode->next)
{}
while(currentNode!=NULL)
{
cout<<currentNode->rollNumber<<”   “<<currentNode->name<<“\n”;
currentNode=currentNode->prev;
}
}
}
void main()
{
DoubleLinkedList obj;
int rollNo;
char ch;
while(1)
{
cout<<endl<<“Menu”;
cout<<“\n1. View all records in the ascending order of roll
numbers”<<endl;
cout<<“2. View all records in the descending order of roll
numbers”<<endl;
cout<<“3. Search for a record in the list”<<endl;
cout<<“4. Exit”<<endl;
cout<<“\nEnter your choice (1-4): “;
cin>>ch;
switch(ch)
{
case ‘1’:
{
obj.traverse();
}
break;
case ‘2’:
{
obj.revtraverse(); ¤NIIT Solving Programming Problems Using Linked Lists – II 6.37
}
break;
case ‘3’:
{
if(obj.listEmpty()==true)
{
cout<<“\nList is empty\n”;
break;
}
Node *prev,*curr;
cout<<“\nEnter the roll number of the student whose
record you want to search: “;
cin>>rollNo;
if(obj.Search(rollNo, &prev, &curr)==false)
cout<<“\nRecord not found”<<endl;
else
{
cout<<“\nRecord found”<<endl;
cout<<“\nRoll number: “<<curr->rollNumber;
cout<<“\n\nName: “<<curr->name;
cout<<“\n”;
}
break;
case ‘4’:
{
exit(0);
}
break;
default:
{
cout<<“\nInvalid option\n”;
}
break;
}
}
}
} 6.38 Solving Programming Problems Using Linked Lists – II  ¤NIIT
Exercise 2
You are given an incomplete program that implements a circular linked list to store the
records of a student in a class. Each record holds the following information:
„ Roll number of the student
„ Name of the student
Complete the program by including the functions for insertion and deletion of a node in a
circular linked list.
// Code in C#
using System;
using System.Text;
namespace Circular_List_CSharp
{
class Node
{
/* Creates nodes for the circular nested list */
public int rollNumber;
public string name;
public Node next;
}
class CircularList
{
Node LAST;
public CircularList()
{
LAST = null;
}
public bool Search(int rollNo, ref Node previous, ref Node
current) /* Searches for the specified node */
{
for (previous = current = LAST.next; current != LAST;
previous = current, current = current.next)
{
if (rollNo == current.rollNumber)
return (true); /* Returns true if the node is
found */
}
if (rollNo == LAST.rollNumber) /* If the node is  present
at the end */
return true;
else
return (false); /* Returns false if the node is not
found*/
}
public bool listEmpty() ¤NIIT Solving Programming Problems Using Linked Lists – II 6.39
{
if (LAST == null)
return true;
else
return false;
}

public void traverse() /* Traverses all the nodes of the list
*/
{
if (listEmpty())
Console.WriteLine(“\nList is empty”);
else
{
Console.WriteLine(“\nRecords in the list are:\n”);
Node currentNode;
currentNode = LAST.next;
while (currentNode != LAST)
{
Console.Write(currentNode.rollNumber + ”    ” +
currentNode.name + “\n”);
currentNode = currentNode.next;
}
Console.Write(LAST.rollNumber + ”    ” + LAST.name +
“\n”);
}
}
public void firstNode()
{
if (listEmpty())
Console.WriteLine(“\nList is empty”);
else
Console.WriteLine(“\nThe first record in the list
is:\n\n ” + LAST.next.rollNumber + ”    ” +
LAST.next.name);
}
static void Main(string[] args)
{
CircularList obj = new CircularList();
while (true)
{
try
{
Console.WriteLine(“\nMenu”);
Console.WriteLine(“1. View all the records in the
list”);
Console.WriteLine(“2. Search for a record in the
list”);
Console.WriteLine(“3. Display the first record in
the list”);
Console.WriteLine(“4. Exit”);
Console.Write(“\nEnter your choice (1-4): “);
char ch = Convert.ToChar(Console.ReadLine());
switch (ch) 6.40 Solving Programming Problems Using Linked Lists – II  ¤NIIT
{
case ‘1’:
{
obj.traverse();
}
break;
case ‘2’:
{
if (obj.listEmpty() == true)
{
Console.WriteLine(“\nList is
empty”);
break;
}
Node prev, curr;
prev = curr = null;
Console.Write(“\nEnter the roll
number of the student whose record is
to be searched: “);
int num =
Convert.ToInt32(Console.ReadLine());
if (obj.Search(num, ref prev, ref
curr) == false)
Console.WriteLine(“\nRecord not
found”);
else
{
Console.WriteLine(“\nRecord
found”);
Console.WriteLine(“\nRoll number:
” + curr.rollNumber);
Console.WriteLine(“\nName: ” +
curr.name);
}
}
break;
case ‘3’:
{
obj.firstNode();
}
break;
case ‘4’:
return;
default:
{
Console.WriteLine(“Invalid option”);
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
} ¤NIIT Solving Programming Problems Using Linked Lists – II 6.41
}
}
}
// Code in C++
#include<iostream.h>
class Node
{
/* Each node consists of the information part and a link to the next
node.*/
public:
int rollNumber;
char name[20];
Node * next;
};
class List
{
Node *LAST;
public:
List();
void addNode();
bool Search(int rollNo, Node **current, Node **previous);
bool listEmpty();
bool delNode(int rollNo);
void traverse();
void firstNode();
};
List :: List()
{
LAST=NULL;
}
bool List :: listEmpty()
{
if (LAST == NULL)
return true;
else 6.42 Solving Programming Problems Using Linked Lists – II  ¤NIIT
return false;
}
bool List :: Search(int rollNo, Node **previous, Node **current)
/* Checks whether the specified node is present in the list or not */
{
for (*previous = *current = LAST->next; *current != LAST;
*previous = *current, *current = (*current)->next)
{
if (rollNo == (*current)->rollNumber)
return true; /* Returns true if the node is found */
}
if (rollNo == LAST->rollNumber) /* If the node is present at
the end */
return true;
else
return false; /* Returns false if the node is not  found*/
}
void List :: traverse() /* Traverses the list */
{
if(listEmpty())
cout<<“\nList is empty.\n”;
else
{
cout<<“\nRecords in the list are:\n\n”;
Node *currentNode;
currentNode = LAST->next;
while (currentNode != LAST)
{
cout<<currentNode->rollNumber << ”   “<<currentNode->
name<<“\n”;
currentNode = currentNode->next;
}
cout<<LAST->rollNumber<<”    “<<LAST->name<<“\n”;
}
}
void List :: firstNode()
{
if(listEmpty())
cout<<“\nList is empty.\n”;
else
cout<<“\nThe first record in the list is:\n\n “<<LAST-> ¤NIIT Solving Programming Problems Using Linked Lists – II 6.43
next->rollNumber<<”    “<<LAST->next->name<<endl;
}
void main()
{
List obj;
int rollNo;
char ch;
while(1)
{
cout<<“\nMenu”;
cout<<“\n1. View all the records in the list”<<endl;
cout<<“2. Search for a record in the list”<<endl;
cout<<“3. Display the first record in the list”<<endl;
cout<<“4. Exit”<<endl;
cout<<“\nEnter your choice (1-4): “;
cin>>ch;
switch(ch)
{
case ‘1’:
{
obj.traverse();
}
break;
case ‘2’:
{
if(obj.listEmpty()==true)
{
cout<<“\nList is empty\n”;
break;
}
Node *prev,*curr;
cout<<“\nEnter the roll number of the student whose
record is to be searched: “;
cin>>rollNo;
if(obj.Search(rollNo, &prev, &curr)==false)
cout<<“\nRecord not found”<<endl;
else
{
cout<<“\nRecord found”<<endl; 6.44 Solving Programming Problems Using Linked Lists – II  ¤NIIT
cout<<“\nRoll number: “<<curr->rollNumber;
cout<<“\n\nName: “<<curr->name;
cout<<“\n”;
}
}
break;
case ‘3’:
{
obj.firstNode();
}
break;
case ‘4’:
{
exit(0);
}
break;
default:
{
cout<<“Invalid option.”<<endl;
}
break;
}
}
}

Create your own website, free on WordPress.com.Create your own website.
Start free