0% found this document useful (0 votes)
13 views248 pages

Laptop and Portable Devices Overview

The document provides a comprehensive overview of laptop and portable devices, detailing their definitions, types, features, and common uses. It covers the evolution of these devices, comparisons between laptops and desktops, and cleaning procedures for maintaining their functionality. Additionally, it discusses the characteristics and applications of smartphones, PDAs, and tablets in various fields.

Uploaded by

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

Laptop and Portable Devices Overview

The document provides a comprehensive overview of laptop and portable devices, detailing their definitions, types, features, and common uses. It covers the evolution of these devices, comparisons between laptops and desktops, and cleaning procedures for maintaining their functionality. Additionally, it discusses the characteristics and applications of smartphones, PDAs, and tablets in various fields.

Uploaded by

irakozevanessa21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SAINT IGNATIUS

HIGH SCHOOL

COMPUTER SCIENCE SUBJECT


SENIOR FIVE CONTENT
SUMMARY

ACADEMIC YEAR 2021-2022

STUDENT’S NAME:
[Link]:

Prepared by [Link] de Dieu HATANGIMANA


Email:jdhatangimana@[Link]
Tel:+250785900106
UNIT 1. FUNDAMENTALS OF LAPTOP AND PORTABLE DEVICES
1.1. PORTABLE DEVICES
1.1.1. Portable devices definition
A portable device is a small form of a computing device that is designed to be held and used in the
hands.
A portable device may also be called a handheld device or mobile device.
1.1.2. Types of portable devices
a. Laptops
A laptop computer is a portable personal computer powered by a battery, or an Alternating Current (A.C) cord
plugged into an electrical outlet, which is also used to charge the battery.
The memory and storage capacity of laptop computer is almost equivalent to the PC or desktop computer. It also
has the hard disk, DVD/CD optical disk drive, different connectors etc.
b. Smartphones
A smart phone is a handheld personal computer with a mobile operating system and an integrated mobile broadband network
connection for voice, SMS, and Internet data communication and they are typically pocket-sized, as opposed to tablets, which
are much larger.
The Smartphone characteristics/features include:
 Media players
 Internet access
 Global Positioning System(GPS)
 Wireless Fidelity (Wi-Fi)
 Camera
 Sensor
c. Mobile phones (cell phones)
A mobile phone or cell phone (is a long-range, electronic device used for mobile telecommunications (mobile
telephony, text messaging or data transmission) over a cellular network.
d. PDAs
A Personal Digital Assistant (PDA), also known as a palmtop computer, or Personal Data Assistant, is a mobile
device that functions as a personal information manager.
e. Tablets
A tablet computer, or simply tablet, is a mobile computer with a large screen, circuitry and battery in a single
unit with no built in keyboard.
Tablets are very similar to smartphones. They have an Internet connection via a wireless connection including
3G/4G. Applications can be downloaded and installed.
Comparison between laptop, Smartphone, Cell phone, PDA and Tablet
Feature Laptop Smartphone Cell phone PDA Tablet
Operating system yes Yes No yes yes
Wireless Fidelity yes Yes No yes yes
Expandable memory yes Yes No yes yes
QWERTY Keyboard yes Yes No yes yes
GPS no Yes No no yes
Internet access yes Yes No yes yes
High resolution display yes Yes No yes yes
Media players Yes Yes No yes yes
Camera Yes Yes No yes yes
Sensor No Yes No no yes
Touch Technology Yes Yes No yes yes
-1-
SIM Card function No Yes Yes no no
Bluetooth Yes Yes Yes yes yes
Battery Yes Yes Yes yes yes

Notice: Modern PDAs have GPS and sensor features and modern tablets can use a SIM card. Due to
improvement of technology and manufacturers some cell phone may contains one or more features found
in other portable devices.

1.2. LAPTOP COMPUTER FUNDAMENTALS


1.2.1. Common uses
The first laptops were used primarily by business people who needed to access and enter data when they were away
from the office. The use of laptops was limited due to expense, weight, and limited capabilities compared to less
expensive desktops.
Some common uses for laptops
Laptop is used in:
• Education field (example: Laptops are used by teachers in preparation of teaching and learning
materials)
• Medicine field (example: Laptops are used by doctors to keep patient records)
• Business field (Electronic commerce uses Laptops for example in marketing and selling products or
good and services.)
• Accessing online services (example: Online Learning at [Link]
• Entertainment field (example: Playing games and watching movies while traveling)
• Communication field (example: when you send and receive an email in a public place)
• Security field (example: Laptop can be used to fight against hackers: people who access personal
information without authorization of the owner.)
1.2.2. Laptop features
The most significant feature of a laptop is its compact size. The design of the laptop places the keyboard, screen,
and internal components into a small portable case.
Common Characteristics/features of Laptops:
• Small and portable;
• An integrated display screen in the lid;
• An integrated keyboard in the base;
• They run on AC power or a rechargeable battery;
• Laptops support hot-swappable drives and peripherals.
1.2.3. Evolution (History) of laptops
In 1983, Gavilan SC is the first machine marketed as a “laptop”
In 1990, Intel introduces 80386SL processor which uses low power; quickly incorporated into many laptops.
In 1991, Apple PowerBook introduces First laptop Ethernet port. Modem speeds reach 14,400 bits/sec.
In 1996, First Pentium laptop with USB, first “three spindle” machine, with floppy, hard disk, CD- ROM.
In 1999, Laptop manufacturers use PCI slot to enable Wi-Fi connectivity. Apple brands WiFi as AirPort, incorporates a
slot into all of its laptops.
In 2005, Laptop computers outsell desktops for the first time.
In 2010, HDMI ports become common on laptops.
1.2.4. The components of a laptop
Components may be located in different places on different models.
-2-
a. The external components of a laptop
The Laptop and the desktop computers use the same types of ports so that peripherals can be interchangeable. Ports,
connections, and drives are located on the front, back, and sides of the laptop due to the compact design.

i. The left side of the following laptop has the following components:
1) AC power port
2) Ethernet port
3) VGA port
4) Ventilation
5) HDMI port
6) USB ports

Note:a)Comparison between HDMI port and USB port

port HDMI USB


characteristics
Number of devices It supports one device at time It can support one device to 127 devices at a time
Transport of power It does not transport electricity It transport both data and electricity at time
Stand for High Definition Multimedia Universal Serial Bus
Interface
b) Comparison between HDMI port and VGA port

port characteristics HDMI VGA

Stand for High Definition Multimedia interface Video graphics array


Transport of audio and video Digital audio and video signal Analog video signal
General specification Hot pluggable,19 or 29 pins Not hot pluggable,15 pins
Signal through cable digital Analog
compatibility Compatible with DVI and VGA with VGA to DVI or to HDMI converters
converters available

ii. The right side of the following laptop contains the components below:
1) Sound in(Microphone) port
2) Sound out (speaker) port
3) USB port

iii. The bottom of the laptop has the components listed here below:
1) Battery
2) Battery latch

-3-
iv. The components found on user view
Typically, the laptop is closed when not in use. By opening the lid of the laptop, you can access a variety of
input devices and a display screen.
There are several input devices available when the laptop lid is open:
1) Web camera 4) Keyboard 7) Left Click button
2) LCD 5) Touch pad
3) Power button 6) Right Click button
Note that a desktop monitor can be connected to a laptop. Using the function key, you can toggle the screen
from the laptop to the desktop monitor or view both at the same time.

b. The internal components of a laptop


The central circuit board (motherboard) makes up a complex electronic system. A motherboard provides the
electrical connections by which the other components of the system communicate. It includes many components
such as Central Processing Unit (CPU), Random Access memory(RAM), etc. Laptop motherboards and other
internal components installation vary by manufacturer and are proprietary.
i. Top and bottom internal components of laptop
Under the top cover, there is access to the following internal components:
• Speakers
• Power board
• Cooling fan
• Wireless card
• CMOS battery
• Audio board
ii. Under the bottom cover, there is access to the following internal components:
1. Hard drive
2. RAM Modules
1.3. Compare and contrast laptop and desktop components
Both desktop and laptop computers can perform most of the same functions. The following table summarizes the
specifications between a laptop and desktop computers.
Comparison of laptop and desktop
Feature/Component Laptop Desktop

Motherboard form Specialized components (specific Standardized components (Universal


factor form factors) form factors)
Processors use less power Processors use great electricity quantity
Processors create less heat Processors create great heat quantity

Processor Processors don’t require large Processors require large cooling devices
cooling devices
Power management laptop takes electricity from the Desktops remain plugged into a power
battery source
Expansion capability Expansion devices are attached to A desktop attaches these devices with USB
laptop devices with USB ports, ports and parallel ports.
parallel ports, and PC Cards.
RAM slot type SODIMM DIMM
Physical Size of Hard Disk 2.5-inch drives 3.5-inch drives

-4-
1.4 SMARTPHONES, PDAs, TABLETS
The Smartphones, PDAs, tablets are new types of small personal computing devices that have been introduced
in the mid-1990s and these are referred to as handheld computers. This type of computer is named handheld
computer because it can fit in one hand while you can operate it with the other hand. Because of its reduced size,
the screen of handheld computer is quite small.

1.4.1. Common uses and standard services of Smartphones, PDAs and tablets
They are used in different fields like the following:
• Communication (example: - when you send and receive an email
- Voice over Internet Protocol (VoIP) – voice/video calls.
- Instant text message ex: chatting using WhatsApp
- Streaming music/video content
- Communication via social networking applications).
• Entertainment (example: when you play games and watch movies while traveling)
• Business (Electronic commerce uses these computers for example in marketing and selling products or
goods and services.)
• Education field (Smartphones, PDAs and tablets are teaching and learning tools. They are used in
performing calculations, note taking etc.)
• Smartphones, PDAs and tablets have storage which can store information like contact information
(names, addresses, phone numbers, e-mail addresses)
• Smartphones, PDAs and tablets can remind you the appointments (clock, alarm functions)
1.4.2. Common features of Smartphones, PDAs and tablets
i. Operating system
Smartphones, PDAs, tablets have operating systems which allows them to run multiple applications.
Their Operating systems have features like contacts, email, calendar, appointments, tasks, games, media etc.
Examples of mobile operating systems:
a) Apple’s iOS
b) Android OS
c) Windows Phone OS
d) BlackBerry OS

ii. Wi-Fi
With Wi-Fi, users can lower their data charges and have a fast Internet connection wherever there is a wireless signal.
iii. Expandable memory
Expandable memory is always a good feature in your PDA, Smartphone and Tablet because the built in
memory is not always enough.
iv. Display
Has a high resolution display, with touch Technology to select options on a menu or to select particular icons.
v. QWERTY keyboards

-5-
1.4.3. Evolution of Smartphone, PDA and Tablet
a. Evolution of Smartphone
 Mid 1995, The term ‘smartphone’ is first used but the original smartphone was introduced three years
earlier. It was called the Simon Personal Communicator by IBM created in 1992. This was the first
phone to combine functionality from both a cell phone and PDA.
 July 1999, Blackberry’s first wireless handheld computer, RIM 850, is announced. The device gained
popularity in the business world with its ability to connect people to their corporate emails, address
books, task lists, and calendars.
 Later in 2003, the Nokia 1100 is released, and ultimately becomes the best-selling mobile phone of all
time with over 250 million units sold worldwide, the Nokia 1100 also went on to become the best-
selling consumer electronics device in the world, ever.
 In January 2007, Apple unveiled the iPhone at the Macworld Expo in San Francisco.,. The iPhone was
officially released in the U.S. five months later in June.
 In November 2008, the first-ever Android phone, the G1, is released. It was capable of accessing over
500 Apps from the Apps Store.
 In December 2011, Windows Mobile was dropped and Windows Phone was created. After finding
challenges in competing with iPhone and Android, Microsoft decides to retire Windows Mobile and
develop a completely new operating system for Windows smartphones (Windows Phone).
 In January 2016, Samsung leads the smartphone vendor market with their momentum still in full- swing.
b. Evolution of PDA
The first PDA, the Organizer, was released in 1984 by Psion, followed by Psion's Series 3, in 1991. The term
PDA was first used on January 7, 1992 by Apple Computer CEO John Sculley at the Consumer Electronics
Show in Las Vegas, Nevada, referring to the Apple Newton.
In 1994, IBM introduced the first PDA with full telephone functionality Then
in 1996, Nokia introduced a PDA with telephone functionality.
c. Evolution of Tablet PCs
The first patent attributed to the development of tablet computing was issued in 1888 to Elisha Gray, who
developed an electrical stylus device that would capture handwriting. Later, in 1915, a second U.S. patent was
granted for an invention that recognized handwritten characters based on handwriting motion.
The first demonstration of a tablet using a handwriting text recognition device to input data rather than a
keyboard occurred in 1956.
The arrival of consumer tablets began with Bill Gates and his introduction of the Microsoft Tablet PC in 2000
to address business needs and later Apple announced their iPad in 2010.
1.4.4. Standards Service of Smartphone, PDA and Tablet
Some of the services that can be found in smartphones, PDA, and tablets include;
• Appointment calendar
• MP3 player
• Web browser
• E-mail access, in addition to text messaging
• Mini-keyboards or onscreen keyboards
• Bluetooth
• Character recognition (allowing for handwritten input)
• Synchronization of information with desktop or laptop computers
• Voice recording
• Digital camera
• Video recording
• Location tracking through GPS(Global Positioning System)

-6-
• Wi-Fi
• Microsoft Office (MS) compatible applications (Native with Pocket PC operating systems; Palm
operating systems may require third-party software)
1.5. LAPTOP AND PORTABLE DEVICES CLEANING PROCEDURES
It is important to keep a laptop clean and to ensure that it is being used in the most optimal environment possible. It
is very important to use the right products, cleaning materials and procedures when cleaning a Laptop. Always read
all warning labels on the cleaning products.
Before starting to clean any part of a laptop, do the following:
1. Turn off the laptop;
2. Disconnect all attached devices;
3. Disconnect laptop from the electrical outlet;
4. Remove installed battery.

1.5.1Laptop Keyboard Cleaning Procedures:


 Blow compressed air between the keys.
 Slide a soft cloth over laptop keyboard in order to remove dirt
 Use compressed air to clean out the dust from the vents and the fan behind the vent.
 Use tweezers to remove any debris.

1.5.2 LCD screen cleaning procedure


 Slide a soft cloth with water or LCD cleaner over laptop display.
CAUTION: Use products specifically designed for cleaning LCD displays.

1.5.3 Touch Pad Cleaning Procedure:


 Slide a soft cloth over surface of touch pad gently with an approved cleaner.  Never use
a wet cloth.
CAUTION: Use a soft cloth with an approved cleaning solution to avoid damaging laptop surfaces.
Notice: How do I take good care of my personal Laptop Computer?
• Keep liquids away from your laptop, spilled liquids may damage the internal microelectronic components or
cause electrical damage. Short circuits can corrupt data or even permanently destroy some parts of the laptop.
• Having antivirus software available is the best defense against a virus. Even if you know what you download, it
could still contain a virus. The virus may also slow down the system operations and performance.
• Keep food away from your laptop. Don't eat over your laptop, the crumbs can fall between the keys and provide
an invitation to small bugs or damage the circuitry. Worse yet, the laptop will look dirty if there are crumbs on it.
• Do not use your computer in a room where animals are. Their fur and hair can get into the internal workings
and damage them. Ideally keep the computer in a clean and dust free room.
• Always have clean hands when using your laptop. Clean hands make it easier to use your laptop touchpad and
there will be less risk of leaving dirt and other stains on the computer. In addition, if you clean your hands before
you use the laptop, you will reduce wear and tear on the coating caused by contact with sweat and small particles
that can act upon the laptop's exterior.
• Protect the LCD display monitor. When you shut your laptop, make sure there are no small items, such as a
pencil or small ear-phones, on the keyboard. These can damage the display screen if the laptop is shut on them; the
screen will scratch if the item is rough. Close the lid gently and holding it in the middle.
• Hold and lift the computer by its base, not by its LCD display (the screen). If you lift it by the screen alone,
you could damage the display or the hinges attaching the display to the base. The display is also easily scratched or
damaged by direct pressure – avoid placing pressure on it.

-7-
• Don't pull on the power cord. Tugging your power cord out from the power socket rather than pulling directly on
the plug can cause the cord to break off from the plug or damage the power socket.
• Don't roll your chair over the computer cord. Stick the cord onto your desk with tape or a special computer cord
tie which can easily be undone when you've finished using the laptop. Always try to keep the cord away from the
floor and your legs.
• Be sure to plug accessory devices into their proper slots. Always look at the symbols on the laptop carefully
before inserting devices. Jamming a phone line into an Ethernet port or vice versa could damage the sockets,
making it impossible to use them again. It is very important to observe this step.
• Handle any removable drives with care. CD drives that have been removed from your laptop could easily be
crushed or dropped; do not be careless. If you are not putting them back into the laptop, put them straight into a
storage box or case for safekeeping.
• Insert drives into their slots carefully and at the correct angle. Pushing the drive too forcefully into its slot
could jam it.
• Check to see if labels are affixed securely before inserting media into your laptop. CDs, DVDs, or floppy disks
should not have any loose labels that may jam inside the laptop. Never insert undersized CDs, as these can damage
the disk player permanently.
• Don't expose your laptop to rapid temperature changes. When bringing your laptop indoors during winter, don't
turn it on immediately. Instead, let it warm to room temperature first. This will avoid any potential for damage to
the disk drive from condensation forming inside the machine. Avoid heat from sunlight as well.
• Don't leave your laptop in a car. Not only do the insides of cars experience large temperature swings that could
damage a laptop, but a laptop (or laptop bag) is an inviting target for a smash and grab thief.
• Have the unit cleaned annually to remove internal dust. Get this done by a computer professional, or do it
yourself if you can. If dust accumulates, the system will not be able to cool itself correctly. Heat can destroy the
motherboard.
• Avoid placing heavy materials, such as books, on top of your laptop. This can push the LCD screen into the
keyboard, and will eventually damage it. Also, the CD-ROM insert will be squished and, eventually, will break.
• Use a properly-sized laptop case. Whatever you use to carry your laptop around, make sure that the case(or bag)
is large enough to hold the laptop. This will help avoid scratching, squeezing or potentially dropping it.
• Only use and store your laptop in a well-ventilated area. When you are using your laptop, do so in a place that
has a constant air-circulation. Lots of people run their laptops by using them in enclosed areas and thus cause the
laptop to overheat.
• Use an old toothbrush to clean the area around the exhaust fan screen. If that gets plugged up, air flow is
diminished and overheating can occur.
• Try to keep the laptop on a flat, clean surface. This prevents damage to the laptop. This can be hard to do,
particularly if you are outside with your laptop, but if there is a flat surface available then put your laptop on it.
• Don't use your laptop on the bed. Repeated use of a laptop on the bed will cause the fans to suck up the dust and
debris in the bed, ultimately blocking the fan.
• Always check that your laptop does not have too much of software and bloat-wares running around as they
keep eating the precious memory which is required for playing games or doing other high-end tasks.
• Use a cleanup software like tune up utilities or c cleaner etc. for keeping your computer under constant
surveillance from the unnecessary programs installed during various activities.
• If possible, do a clean install of the operating system you use once every 2 to 3 years. This will really help the
laptop to start from the scratch and maintain everything in a very organized and effective manner.
• If you are already on a device with low RAM then do not trouble the device with programs which accelerate
the processor, it is better if you switch over to another hard drive or pen drive to provide a bit of external ram and
provides a bit of breathing space to the computers internals.
• Do not try to run large or unsupported multimedia files over your computer if your computer does not meet
the specifications as it usually damages the computer in the long run.
• Take care that if you use a laptop not to use it in places full of dust flying around as it may block the heat escape
routes over a period of time and thereby make your laptop much hot faster than usual.
-8-
UNIT 2: COMPLEX DATA STRUCTURE AND ALGORITHM
2.1. Introduction to Data Structures
Data Structure is a way of collecting and organizing data in such a way that we can perform operations on these
data in an effective way.
A data structure is a systematic way of organizing and accessing data.
Example: Library is composed of elements (books) to access a particular book requires knowledge of the
arrangement of the books.
2.1.1. Basic types of Data Structures
Anything that can store data can be called as a data structure, hence Integer, Float, Boolean, Char etc., all are data
structures. They are known as Primitive Data Structures. And we also have some complex Data Structures, which
are used to store large and connected data and are called non primitive data structure or Abstract Data
Structure.
Example: Array, Linked List, Tree, Graph, Stack, Queue etc.

All these data structures allow us to perform different operations on data. We select these data structures based on
which type of operation is required.

2.1.2. Importance of data structures


The data structures have the following importance for programming:
• Data structures study how data are stored in a computer so that operations can be implemented efficiently
• Data structures are especially important when there is a large amount of information to deal with.
• Data structures are conceptual and concrete ways to organize data for efficient storage and manipulation
2.1.3. Data Structure Operations
Beside the simple operations performed on data (unary operators, binary operators and precedence operators) seen
in Senior Four, the data appearing in our data structures are processed by means of other operations.
The following are some of the most frequently used operations.
• Traversing: Accessing each record exactly once so that certain items in the record may be processed.
• Searching: Finding the location of the record with a given key value or finding the locations of all records
which satisfy one or more conditions
• Inserting: Adding a new record to the structure.
• Deleting: Removing a record from the structure.
• Sorting: Arranging the records in some logical order (e.g., in numerical order according to some NUMBER

1
key, such as social security number or account number).
• Merging: Combining the records of two different sorted lists into a single sorted list.
If we arrange some data in appropriate sequence, then it forms a Structure and gives us a meaning(information).

2.2 Array of elements in data structure


Arrays hold a series of data elements, usually of the same size and data type. Individual elements are accessed by
their position in the array. The position is given by an index, which is also called a subscript.
Some arrays are multi-dimensional, meaning they are indexed by a fixed number of integers, for example by a
tuple of four integers.
In computer programming, a group of homogeneous elements of a specific data type is known as an array, one of
the simplest data structures.
2.2.1. Arrays dimensions:
A dimension of array is a direction in which you can vary the specification of an array's elements. An array can
be of one or many dimensions.
a) One-dimensional array.
Example: a [3];
It is an array called a with 3 elements. The elements of the array are logically represented by the name of the array
with in brackets its index or positions.
For the one dimensional array a with 3 elements, elements are written like a[0], a[1] and a[2].
Note that the indexes start always by 0. Graphically, it is

b) Multi-dimensional arrays
Example:
• Two dimensional array ex: a[2][7]as integer
• Three dimensional array ex: a[3][2][5]as Integer

2.2.2. Two dimensional array


A Two dimensional Array is a collection of a fixed number of elements (components) of the same type
arranged in two dimensions.
The two dimensional array is also called a matrix or a table. The intersection of a column and row is called a
cell. The numbering of rows and columns starts by 0.
Example:
The array a[3][4] is an array of 3 rows and 4 columns.
In matrix representation, it looks like the following:

Note that a[i][j] means that it is an element located at the intersection of row i and column j.

2
2.2.3. Two dimensional array declaration
The syntax for declaring a two-dimensional array is:
Variable ArrayName [row size][column size] of Data type

Where row size and column size are expressions yielding positive integer values, the two expressions row size
and column size specify the number of rows and the number of columns, respectively, in the array.
Examples:
1. Variable a[2][7] as Integer
2. Variable b[4][3] as integer
In c++ program,the syntax is:
Data Type arrayName[row size][column size];
E.g:int marks[4][3];
Float marks[3][3];

Notice that the number of elements =row size*column size


The examples above defines respectively arrays named a and b with 14 (2*7) elements and 12 (4*3) elements.
The expression marks [0] [0] will access the first element of the matrix marks and marks [1] [6] will access the last
row and last column of array a.
If the array marks if filled with the elements 80, 75, 76, 75, 55, 70, 55, 70, 65, 85, 35 and 59, we get the following
table:

2.2.4. Two dimensional array initialization


When a two-dimension array has been declared, it needs to be assigned values for its elements. This action of
assigning values to array elements is called initialization.
Two-Dimensional array is initialized by specifying bracketed values for each row.
For the case of array of integers, the default values of each element is 0 while for others the default values for
other types is not known.
For the case of an array of 3 rows and 4 columns, if the name is A and the type of elements is integer, the
initialization is:
int A[3][4]=
{
{A[0][0], A[0][1], A[0][2], A[0][3]}, /* initializers for row indexed by 0 */

3
{A[1][0], A[1][1], A[1][2], A[1][3]}, /* initializers for row indexed by 1*/
{A[2][0], A[2][1], A[2][2], A[2][3]} /* initializers for row indexed by 2 */
};
The following initialization is equivalent to the previous initialization.
int A[3][4]={A[0][0], A[0][1], A[0][2], A[0][3], A[1][0], A[1][1], A[1][2], A[1][3], A[2][0], A[2][1],
A[2][2], [2][3]};

Example: Marks for 3 students in 4 courses. The array will look like this:
col 0 col 1 col 2 col 3
Row 0 18 16 14 19
Row 1 10 20 12 15

Row 2 15 17 18 16

If the table is called marks, marks [1][3]=15; where the row position is 1 and the column position is 3.
The expression marks [0] [0] will access the first element of the matrix marks and marks [2] [3] will access the last
row and last column.

2.2.5. Accessing two dimensional array elements


 Reading (storing) two dimensional array elements
There exist two ways of accessing the elements of an array. The elements’ values of the array can come from the
input devices or from a given file so that these elements are written into the array.
The function used is READ or other versions of it, depending on the programming languages used for programs
writing.
For example READ marks[1][2] stores a value in second row, third column location of the array marks.
Note:To store multiple values into array you must use a FOR loop.
Syntax
for i←initial value to upperlimit do
for j←initial value to upperlimit do
read arrayname[i][j]
i←1+1
j←j+1
end for
end for
Where i refers to the row position and j refers to the column position and Initial value=lower limit
Example: Write an algorithm of a program that allows the user to enter (store) two dimensional array elements
of 3 row and 4 columns.
Variable i,j,marks[3][4]as integer
start
for i←0 TO 2 DO
for j← 0 TO 3 DO
READ (marks[i] [j] )
i←i+1
j←j+1
end for

4
end for
end

 Writing (displaying) two dimensional array elements


The elements of a two dimensional array can be displayed by the following syntax:
Write ArrayName [i][j]
Where i refers to the row position and j refers to the column position.

Example: Write an algorithm of a program that displays stored two dimensional array marks’ elements
variable i,j,marks[3][4] as integer
start
write (“stored two dimensional array elements are:” )
for i←0 to 2 do
for j←0 to 7 do
write ( a[i][j])
i←i+1
j←j+1
end for
end for
End
Example1: Write an algorithm that allows the user to enter(store) two dimensional array elements and
displays those stored elements.
Algorithm
Variable i,j,m,n,a[10][10] as integer
Start
Write(“Enter the number of rows and columns”)
Read(m,n)
write(“Enter the elements of matrix”)
for i←1 to m
for j←1 to n
read(a[i][j])
i←i+1
j←j+1
write(“the entered elements of a matrix are:”)
for i←1 to m
for j←1 to n
write(a[i][j])
i←i+1
j←j+1
end
C++ Program
#include<iostream>
using namespace std;
int main( )
{
int i,j,m,n,a[10][10];
cout<<"Enter the number of rows and columns of a matrix"<<endl;
cin>>m>>n;
cout<<"Enter the elements of a matrix"<<endl;
for(i=0;i<m;i++)

5
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
cout<<""<<endl;
}
cout<<"The entered matrix is:"<<endl;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
Example2: Write a c++ program to find the sum of two matrices
// C++ program to find sum of two matrix
#include <iostream>
using namespace std;
int main(){
int rows, cols, i, j;
int one[50][50], two[50][50], sum[50][50];
cout <<"Enter Rows and Columns of Matrix\n";
cin >> rows >> cols;
cout <<"Enter first Matrix of size "<<rows<<" X "<<cols;
// Input first matrix
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
cin >> one[i][j];
}
}
// Input second matrix
cout <<"\nEnter second Matrix of size "<<rows<<" X "<<cols;
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
cin >> two[i][j];
}
}
/* adding corresponding elements of both matrices sum[i][j] = one[i][j] + two[i][j] */
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
sum[i][j] = one[i][j] + two[i][j];
}
}
cout <<"Sum Matrix\n";
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
cout << sum[i][j] << " ";

6
}
cout << "\n";
}
return 0;
}
Output
Enter Rows and Columns of Matrix
33
Enter first Matrix of size 3 X 3
123
456
789
Enter second Matrix of size 3 X 3

987
654
321
Sum Matrix
10 10 10
10 10 10
10 10 10

Example3: Write a c++ program to display a matrix and its transpose


#include <iostream>
using namespace std;
int main(){
int rows, cols, i, j;
int A[50][50],B[50][50];
cout << "Enter Rows and Columns of Matrix" << endl;
cin >> rows >> cols;
cout << "Enter Matrix of size "<< rows << " X " << cols << endl;
for(i = 0; i< rows; i++){
for(j= 0; j < cols; j++){
cin >>A[i][j];
}
}
// B[j][i] =A[i][j]
for(i = 0; i< rows; i++){
for(j = 0; j < cols; j++){
B[j][i] = A[i][j];
}
}
cout << "Transpose Matrix" << endl;
// Transpose Matrix of MXN = NXM Matrix
for(i = 0; i < cols; i++){
for(j = 0; j < rows; j++){
cout << B[i][j] << " ";
}
cout << endl;

7
}
return 0;
}
Output
Enter Rows and Columns of Matrix
33
Enter Matrix of size 3 X 3
123
456
789
Transpose Matrix
147
258
369

Example4: Write a c++ program to find the product of two matrices


// C++ program to find sum of two matrix
#include <iostream>
using namespace std;
int main(){
int rows1, cols1, rows2, cols2, i, j, k;
int one[50][50], two[50][50], product[50][50];
cout <<"Enter Rows and Columns of First Matrix\n";
cin >> rows1 >> cols1;
cout <<"Enter first Matrix of size "<<rows1<<" X "<<cols1;
// Input first matrix
for(i = 0; i < rows1; i++){
for(j = 0; j < cols1; j++){
cin >> one[i][j];
}
}
cout <<"Enter Rows and Columns of Second Matrix\n";
cin >> rows2 >> cols2;
if(cols1 != rows2){
cout<<"Matrices cannot be multiplied\n";
}
// Input second matrix
cout <<"\nEnter second Matrix of size "<<rows2<<" X "<<cols2;
for(i = 0; i < rows2; i++){
for(j = 0; j < cols2; j++){
cin >> two[i][j];
}
}

for(i = 0; i < rows1; i++) {


for(j = 0; j < cols2; j++) {
for(k = 0; k < cols1; k++) {
product[i][j] += one[i][k]*two[k][j];
}
}
}

8
cout <<"Product Matrix\n";
for(i = 0; i < rows1; i++){
for(j = 0; j < cols2; j++){
cout << product[i][j] << " ";
}
cout << "\n";
}
return 0;
}
Output
Enter Rows and Columns of First Matrix
33
Enter first Matrix of size 3 X 3
123
456
789
Enter Rows and Columns of Second Matrix
33
Enter second Matrix of size 3 X 3
101
011
111
Product Matrix
4 5 6
10 11 15
16 17 24

2.3. ABSTRACT DATA STRUCTURE


2.3.1. Definition of Abstract Data type in data structure.
Abstract Data structure is a mathematical model of a data structure that specifies the type of data stored, the
operations supported on them and the types of parameters of the operations with no implementation. Each
program language has its own way to implement abstract data type.
2.3.2 Importance of abstract data type in data structures
• Data structures study how data are stored in a computer so that operations can be implemented efficiently;
• Abstract Data structures are especially important when you have a large amount of information;
• Conceptual and concrete ways to organize data for efficient storage and manipulation
2.3.3. Abstract Data type Operations
The data appearing in our data structures are processed by means of certain operations. Following are some of
the most frequently used operations.
• Searching: Finding the location of the record with a given key value or finding the locations of all
records which satisfy one or more conditions;
• Sorting: Arranging the records in some logical order .
2.4. List
2.4.1. Introduction
A list is a collection of data in which each element of the list contains the location of the next element.
In a list, each element contains two parts: data and link to the next element.
The data parts of the list hold the value information and data to be processed and the link part of the list is
used to chain the data together and contains a pointer (an address) that identifies the next element in the list.

9
In the list you can do the following operations:

1)LIST: Creates an empty list;


2)INSERT: inserts an element in the list;
3)DELETE: deletes an element from the list;
4)RETRIEVE: retrieves an element from the list;
5)TRAVERSE: traverses the list sequentially;
6)EMPTY: checks the status of the list.
Example of a list:
A bank has 10 branches created one after another at different dates. The Bank Inspector who wants to visit all of
them can follow the order of their creation. He/she will be informed only about the name and location of the first
branch. When he reaches that branch, the Branch Manager will tell him/her the address of the next branch, and so
on.
After visiting all branches, the Bank Inspector will realize that he/she has a list of the bank branches.
Graphically, it will be represented like a list where each branch is considered as a node containing the names of
the branch and the address of the next branch.
Difference between Arrays and Lists
A list is an ordered set of data. It is often used to store objects that are to be processed sequentially while an
array is an indexed set of variables or It is like a set of boxes that hold things.
So a list is a set of items but an array is a set of variables that each store an item.
Note:In a list, the missing spot is filled in when something is deleted.
In an array, an empty variable is left behind when something is deleted.
2.4.2 Linked list
This is a dynamic table/ data structure used to hold a sequence.
Its characteristics are follows:
 Items forming a sequence are not necessarily held in contiguous data location or in the order in which
they occur in the sequence.
 Each item in the list is called a node and contains an information field and a new address field called a
link or pointer field.
 Information field holds actual data for list item; link field contains the address of the next item.
 The link field in the last item indicates that there are not further items. E.g. has a value of 0.
 Associated with the list is a pointer variable which points to the first node in the list.
 We use linked list in linking files, for example, in a hard disk.
 It can grow or shrink in size during execution of a program.
 It can be made just as long as required
 It does not waste memory space.
Types of linked lists
Linked list is classified into three types as shown below:
 Single linked lists
 Double linked lists
 Circular linked list
1) Single linked lists
Single linked list is a sequence of elements in which every element has link to its next element in the sequence.
In any single linked list, the individual element is called as "Node". Every "Node" contains two fields,
data and next.

10
.

In a single linked list, the address of the first node is always stored in a reference node known as "front"
(Sometimes it is also known as "head").Always next part (reference part) of the last node must be NULL.

2) Double linked lists


Double linked list is a sequence of elements in which every element has links to its previous element and next
element in the sequence. So, we can traverse forward by using next field and can traverse backward by using
previous field.

3) Circular Linked List


In circular linked list, every node points to its next node in the sequence but the last node points to the first
node in the list

11
2.5. Queue
A queue is a linear list in which data can only be inserted at one end, called the REAR, and deleted from the other
end, These restrictions ensure that the data is processed through the queue in the order in which it is received. In
an other words, a queue is a structure in which whatever goes first comes out first (first in, first out(FIFO)
structure).

2.5.1 Types of queues


There exist two types of queues:
• Linear queue
• Circular queue
a. Linear Queue
Queue data structure is a linear data structure in which the operations are performed based on FIFO principle.
b. Circular Queue
Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First
Out) principle and the last position is connected back to the first position to make a circle.

2.5.2. Queue operations


There are two main operations related to queues.
 Enqueue: the enqueue operation insert an items at the rear of the queue
 Dequeue: the dequeue operation deletes the item at the front of the queue
 Display: show elements in the array
2.6 Stack
A stack is a restricted linear list in which all additions and deletions are made at one end, the top. If we insert
a series of data items into a stack and then remove them, the order of the data is reversed. Data input as 5, 10, 15,
20, for example would be removed as 20, 15, 10, and 5. Stacks are known as Last in, First out (LIFO) data
structures.
The following charts illustrates cases of stack

12
A Stack is a Last in First out (LIFO) dynamic table or data structure. It has the following characteristics:
• List of the same kind of elements;
• Addition and deletion of elements occur only at one end, called the top of the stack;
• Computers use stacks to implement method calls;
• Stacks are also used to convert recursive algorithms into non recursive algorithm.
push pop

2.6.1 Operations performed on stacks


The different operations performed on stacks are as follows:
• Push: adds an element to the stack
• Pop: removes an element from the stack
• Peek: display at top element of the stack
2.6.2 Stack exceptions
Adding an element to a full stack and removing an element from an empty stack would generate errors or
exceptions:
• Stack overflow exception: it occurs if you try to add an item to stack or queue which is already full.
• Stack underflow exception: it occurs if you try to remove an item from an empty queue or stack.
Notice 1: Stack and Queue data structures can be implement in two ways:
 Using Array
 Using Linked List

Notice 2: When stack or Queue is implemented using array, that stack or Queue can organize only a limited
number of elements. When stack or Queue is implemented using linked list, that stack or Queue can organize an
unlimited number of elements.
2.7 Tree
Tree data structure is a collection of data (Node) which is organized in hierarchical structure and this is a
recursive definition
In a tree data structure, if we have N number of nodes then we can have a maximum of N-1 number of links.
Example

2.7.1Tree Terminology
In a tree data structure, we use the following terminology:
a. Root
In a tree data structure, the first node is called as Root Node. Every tree must have root node..

13
b. Edge
In a tree data structure, the connecting link between any two nodes is called an Edge. In a tree with 'N' number of
nodes there will be a maximum of 'N-1' number of edges.

c. Parent
In a tree data structure, the node which is predecessor of any node is called a PARENT NODE. In simple
words, the node which has branch from it to any other node is called as parent node.

[Link]
In a tree data structure, the node which is descendant of any node is called a CHILD Node. In a tree, any parent
node can have any number of child nodes. In a tree, all the nodes except root are child nodes.

14
e. Siblings
In a tree data structure, nodes which belong to same Parent are called SIBLINGS.

f. Leaf
In a tree data structure, the node which does not have a child is called a LEAF Node. In a tree data
structure, the leaf nodes are also called a External Nodes or Terminal node.

g. Internal Nodes
In a tree data structure, the node which has at least one child is called INTERNAL Node. In a tree data
structure, nodes other than leaf nodes are called Internal Nodes.
The root node is also said to be Internal Node if the tree has more than one node. Internal nodes are also called
as 'Non-Terminal' nodes.

h. Degree
In a tree data structure, the total number of children of a node is called as DEGREE of that Node. In simple
words, the Degree of a node is total number of children it has. The highest degree of a node among all the
nodes in a tree is called as 'Degree of Tree'

15
i. Level
In a tree data structure, the root node is said to be at Level 0 and the children of root node are at Level 1 and the
children of the nodes which are at Level 1 will be at Level 2 and so on... In simple words, in a tree each step from
top to bottom is called as a Level and the Level count starts with '0' and incremented by one at each level (Step).

j. Height
In a tree data structure, the total number of edges from leaf node to a particular node in the longest path is called
as HEIGHT of that Node. In a tree, height of the root node is said to be height of the tree. In a tree, height of
all leaf nodes is '0'.

k. Depth
In a tree data structure, the total number of edges from root node to a particular node is called DEPTH of
that Node. In a tree, the total number of edges from root node to a leaf node in the longest path is said to be
Depth of the tree. In a tree, depth of the root node is '0'.

16
l. Path
In a tree data structure, the sequence of Nodes and Edges from one node to another node is called as PATH
between those two Nodes. Length of a Path is total number of nodes in that path. In below example the path A

- B - E - J has length 4.

Figure: path representation


Note:Sub Tree
In a tree data structure, each child from a node forms a sub tree recursively. Every child node will form a sub-
tree on its parent node.

2.7.2. Binary Tree Representations


A binary tree data structure is represented using two methods. Those methods are as follows:
 Linked List of Binary Tree representation
 Array Representation
Let T be a Binary Tree. There are two ways of representing T in the memory as follow:
a. Linked List of Binary Tree representation

Consider a Binary Tree T. T will be maintained in memory by means of a linked list representation, which uses
three parallel arrays; INFO, LEFT, and RIGHT pointer variable ROOT as follows. In Binary Tree, each node N of
T will correspond to a location k such that:
1. LEFT [k] contains the location of the left child of node N.
2. INFO [k] contains the data at the node N.

17
3. RIGHT [k] contains the location of right child of node N.
Representation of a node:

In this representation of binary tree, root will contain the location of the root R of T. If any one of the sub
tree is empty, then the corresponding pointer will contain the null value if the tree T itself is empty, the ROOT
will contain the null value.
Example:
Consider the binary tree T in the figure of Binary Tree

Linked Representation of the Binary Tree

b. Array Representation of Binary Tree

Let us consider that we have a tree T. let our tree T is a binary tree that us complete binary tree. Then
there is an efficient way of representing T in the memory called the sequential representation or array
representation of T. This representation uses only a linear array TREE as follows:

1. The root N of T is stored in TREE [1].


2. If a node occupies TREE [k] then its left child is stored in TREE [2 * k] and its right child is stored
into TREE [2 * k + 1].
For Example:
Consider the following Tree:

18
Fig:Array representation in binary tree.

Its sequential representation is as follow:

2.7.3. Binary Tree Traversals


When we wanted to display a binary tree, we need to follow some order in which all the nodes of
that binary tree must be displayed. In any binary tree displaying order of nodes depends on the
traversal method.
Note:Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.
There are three types of binary tree traversals.
 In - Order Traversal
 Pre - Order Traversal
 Post - Order Traversal
Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all
nodes are connected via edges (links) we always start from the root (head) node. That is, we cannot
randomly access a node in a tree.

Generally, we traverse a tree to search or locate a given item or key in the tree or to print all the
values it contains.

a. In-order Traversal
In this traversal method, the left sub tree is visited first, then the root and later the right sub-tree. We
should always remember that every node may represent a sub tree itself.
If a binary tree is traversed in-order, the output will produce sorted key values in an ascending
order.

Figure : In-order Traversal

We start from A, and following in-order traversal, we move to its left subtree B. B is also traversed in-
order. The process goes on until all the nodes are visited. The output of inorder traversal of this tree
will be −
D→B→E→A→F→C→G
Algorithm:
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.

19
b. Pre-order Traversal
In this traversal method, the root node is visited first, then the left subtree and finally the right
subtree.

Figure: Pre-order Traversal

We start from A, and following pre-order traversal, we first visit A itself and then move to its left subtree
B. B is also traversed pre-order. The process goes on until all the nodes are visited. The output of pre-
order traversal of this tree will be −
A→B→D→E→C→F→G
Algorithm:
Until all nodes are traversed −
Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.

c. Post-order Traversal
In this traversal method, the root node is visited last, hence the name. First we traverse the left sub tree,
then the right sub tree and finally the root node.

Figure 2.34.: Post-order Traversal


We start from A, and following Post-order traversal, we first visit the left sub tree B. B is also traversed
post-order. The process goes on until all the nodes are visited. The output of post-order traversal of
this tree will be :
D→E→B→F→G→C→A
Algorithm:
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.
Note:Binary Search tree exhibits a special behavior. A node’s left child must have a value less than
its parent’s value and the node’s right child must have a value greater than its parent value.

20
Figure:Binary tree search.

2.7.4. Basic Operations on binary tree


A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties
 The left sub-tree of a node has a key less than or equal to its parent node’s key.
 The right sub-tree of a node has a key greater than to its parent node’s key.
Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree and can be
defined as
left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)

Representation
BST is a collection of nodes arranged in a way where they maintain BST properties. Each node has a
key and an associated value. While searching, the desired key is compared to the keys in BST and if
found, the associated value is retrieved.
Following is a pictorial representation of BST

Figure : Binary Search Tree


We observe that the root node key (27) has all less-valued keys on the left sub-tree and the higher valued
keys on the right sub-tree.
Basic Operations
Following are the basic operations of a tree −
Search − Searches an element in a tree.
Insert − Inserts an element in a tree.
Pre-order Traversal − Traverses a tree in a pre-order manner.
In-order Traversal − Traverses a tree in an in-order manner.
Post-order Traversal − Traverses a tree in a post-order manner.

2.8. Searching and sorting using complex data structure.


Definition
Searching is the process of finding the location of a given element in a set of elements.
Searching means to find whether a particular value is present in an array or not. If the value is present in the
array, then searching is said to be successful and the searching process gives the location of that value in the array.
There are two simple approaches to searching:
Linear search: This method traverses a list sequentially to locate the search key.
Binary search: This method works on sorted lists by progressively making better guesses to find the
location of a search key.

21
[Link] search Algorithms
The linear search is also called sequential search. It is a simple method used for searching an array for a
particular value. It works by comparing the value to be searched with every element of the array one by one in a
sequence until a match is found.
Notice that the linear search is mostly used to search in an unordered list of elements

[Link] Search
You search an array by repeatedly dividing the search interval in half. While dividing you begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow
the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or
the interval is empty. This kind of search is also called the dichotomy method or bisection method.
Schematically, it looks like the following:

2.9. Sorting using complex data structure

[Link]:
Sorting is the process of arranging elements in some logical order either in ascending or descending order.
Methods for sorting include Bubble sort, Insertion sort and Selection sort.
[Link] sort
Bubble Sort is a simple-minded algorithm based on the idea that we look at the list, and wherever we find two
consecutive elements out of order, we swap them. This is done as follows: Repeatedly traverse the unsorted part of
the array by comparing consecutive elements, and interchange them when they are out of order.
See below demonstration:

22
Figure : Process of |Bubble Sort
[Link] sort
The Insertion Sort is a comparison-based algorithm that builds a final sorted array one element at a time. It
iterates through an input array and removes one element per iteration, finds the place if the element belongs in
the array, and then places it there.
The illustration is given here below:

Figure: process of insertion sort

The Insertion Sort traverses the array and inserts each element into the sorted part of the list where it belongs. It
involves pushing down the larger elements in the sorted part.

[Link] sort
The Selection Sort is a simplicity sorting algorithm. Here are basic steps of selection sort algorithm:Find the
minimum element in the list
[Link]. Swap it with the element in the first position of the list
[Link]. Repeat the steps above for all remainder elements of the list starting at the second position.

23
The idea of Selection Sort is that we repeatedly find the smallest element in the unsorted part of the array and
swap it with the first element in the unsorted part of the array.
2.10. Apply algorithm to solve complex mathematical functions
2.10.2. Understanding quadratic equation
Quadratic equation is any mathematical equation having the form ax2+bx+c=0 where x represents an unknown,
a, b, and c are constants.

Algorithm
Variable a,b,c,x1,x2,delta as double
Start
Write (Enter the value of a )
Read(a)
Write (Enter the value of b )
Read(b)
Write (Enter the value of c )
Read(c)
if(a==0 && b==0)
write(the equation is invalid)
else if(a==0 && b!=0)
x1=-(c/b)
write(“The root="x1)
else if ((b*b-4*a*c)>=0)
delta=(b*b)-(4*a*c);
x1←(-b+sqrt(delta))/(2*a);
x2← (-b-sqrt(delta))/(2*a);
write("roots are:"x1"and"x2)
else
write("Equation does not have a real root")
endif
endif
endif
End

24
C++ Program
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a,b,c,x1,x2,delta;
cout<<"Enter the value of a=";
cin>>a;
cout<<"Enter the value of b=";
cin>>b;
cout<<"Enter the value of c=";
cin>>c;
if(a==0 && b==0)
{
cout<<"The equation is invalid";
}
else if(a==0 && b!=0)
{
x1=-(c/b);
cout<<"The root="<<x1<<endl;
}
else if ((b*b-4*a*c)>=0)
{
delta= (b*b)-(4*a*c);
x1= (-b+sqrt(delta))/(2*a);
x2= (-b-sqrt(delta))/(2*a);
cout<<"roots are:"<<x1<<"and"<<x2<<endl;
}
else
{
cout<<"Equation does not have a real root"<<endl;
}
return 0;
}
2.10.3. Recursive function
Definition: A recursive function is a function that calls itself during its execution.
The Recursive function repeats itself several times, outputting the result at the end of each iteration. In this section
we are going to discuss the following recursive functions:
- Factorial function;
- Summing a list of numbers;
- Fibonacci series function;
- Sorting;
- Palindrome.
- Euclid’s GCD(Greatest Common Denominator).
a. Factorial function
In mathematics, the factorial of a non-negative integer n, denoted by n! is the product of all positive integers
less than or equal to [Link] that the value of 0! is 1, according to the convention for an empty product.
The factorial function (symbol: !) means to multiply a series of descending natural numbers.

25
Examples:
n!=n*(n-1)*(n-2)*(n-3)*……..*3*2*1
4! = 4 * 3 * 2 *1 = 24
Algorithm
Variable i,n,fact as integer
Start
Write(“Enter a positive number”)
Read(n)
i←1
fact←1
while(n>=i)
do
fact←fact*i
i←i+1
write(“The factorial is”fact)
End
C++Program
#include<iostream>
using namespace std;
int main() {
int i=1,n;
long double fact=1;
cout<<"Enter a positive number"<<endl;
cin>>n;
while(n>=i)
{
fact=fact*i;
i++;
}
cout<<n<<"! is:"<<fact<<endl;
return 0;}
b. Summing a list of numbers
 Algorithm which calculate the sum of numbers between 0 and 100
Variable i,sum as integer
Start
sum←0
for i←0 to 100
sum←i+1
write(“The sum of numbers is:”sum)
end for
End
 Write an algorithm which read the marks of n sudents in mathematics course and calculate the sum
Variable i,sum,n,marks[100]as integer
Start
Write(“Enter the number of students”)
Read(n)
Write(“Enter the marks of students”)
For i←1 to n
Read (marks[i])
i←i+1
For i←1 to n

26
Write (marks[i])
i←i+1
sum←0
sum←sum+mark[i]
i←i+1
write(“The sum is “sum)
End
Corresponding c++
#include<iostream>
using namespace std;
int main () {
int i,sum,n,marks[100];
Cout<<“Enter the number of students”<<endl;
Cin>>n;
Cout<<“Enter the marks of students”<<endl;
for (i=0;i<n;i++){
cin>>marks[i];
}
Cout<<”The entered elements are:”
for (i=0;i<n;i++){
cout<<marks[i]<<” “;
Sum=0;
Sum=sum+marks[i];
}
Cout<<”The sum of numbers is:”<<sum<<endl;
return 0;
}
c. Fibonacci series
Fibonacci series is defined as a sequence of numbers in which the first two numbers 0 and 1 and each
subsquent number is the sum of the previous two.
Algorithm:
Variable first,second,third,i,n as integer
START
first←0,second←1
Write(“Enter how many elements:”
Read(n)
Write(first)
For i←2 to n do
third←first+second
Write(third)
first←second
second←third
i←i+1
End for
END
C++ Program:
 Fibonnacci series of n terms
#include <iostream>
using namespace std;
int main()
{

27
int first=0,second=1,third,i,n;
cout<<"Enter how many elements?"<<endl;
cin>>n;
cout<<"The fibonnacci serie is:"<<first<<" , "<<second<<" ";
for(i=2;i<n;++i)
{
third=first+second;
cout<<third<<" , ";
first=second;
second=third;
}
return 0;
}
 Use of array
// Fibonnacci Serie of ten terms
#include <iostream>
using namespace std;
int main()
{
float k[10],i,a,b,c,n;
k[0]=0;
k[1]=1;
cout<<k[0]<<";";
for(i=1;i<10;i++)
{
k[0]=k[1];
k[1]=k[2];
k[2]=k[0]+k[1];
cout<<k[2]<<";";
}

return 0;
}
d. Palindrome
A palindrome number is a number that is the same when written forward or backward.
It is the number that remains the same when its digits are reversed.
Example:12621,121,2345432,…..
Palindrome words are characters read the same backward as forward.
Examples: redivider,civic,rotor,madam,refer,….
 Algorithm:Algorithm for Palindrome number
BEGIN
Variable n, num, dig, rev = 0 as integer
PRINT ”Insert number”
READ num
n = num
while (num != 0)
{
dig = num % 10
rev = (rev * 10) + dig

28
num = num / 10
}
if (n == rev)
PRINT ”This is palindrome”, rev
else
PRINT ”This is not palindrome “ rev
END IF
END
 Corresponding C++ Program:
//Palindrome number
#include <iostream>
using namespace std;
int main( ){
int inputNumber, reverseNumber = 0, rightDigit, temp;
cout << "Enter a number\n";
cin >> inputNumber;
temp = inputNumber;
// reverse inputNumber and store it in reverseNumber
while(temp != 0){
rightDigit = temp % 10;
reverseNumber = (reverseNumber * 10) + rightDigit;
temp = temp/10;
}
// If input Number and reverse Number are same,then palindrome othrwise not
if(reverseNumber == inputNumber){
cout << inputNumber << " is Palindrome Number";
}
else {
cout << inputNumber << " is not a Palindrome Number";
}
return 0;
}

//Palindrome string
#include <iostream>
using namespace std;
int main(){
char inputString[100];
int l, r, length = 0;
cout << "Enter a string for palindrome check\n";
cin >> inputString;
// Find length of string
while(inputString[length] != '\0')
length++;
// Initialize l(left) and r(right) to first and last character of input string
l = 0;
r = length -1;
// Compare left and right characters, If equal then continue otherwise not a palindrome
while(l < r){
if(inputString[l] != inputString[r]){

29
cout<<inputString<<" is Not a Palindrome"<< endl;
return 0;
}
l++;
r--;
}
cout <<inputString<<" is a Palindrome\n" << endl;
return 0;
}
e. Euclid’s GCD
The GCD is the greatest common divisor between two or many numbers which is the largest number that
divides the numbers without leaving a remainder.
Euclid’s algorithm is the method for efficintly finding the greatest common divisor(GCD)of two numbers.
Note: C++ program to find GCD of two numbers
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
int num1, num2, i, GCD;
cout<<"Enter first integer: "<<endl;
cin>>num1;
cout<<"Enter second integer: "<<endl;
cin>>num2;
for(i=1; i<=num1 || i<=num2; ++i)
{
if(num1%i==0 && num2%i==0)
GCD=i;
}
cout<<"G.C.D of "<<num1<<"and "<<num2<<" is "<<GCD<<endl;;
system("PAUSE");
return 0;
}

f. Sorting
A sorted array is an array in which each of the elements are sorted in some order such as numerical,alphabetical
etc.
There many algorithms to sort numrical array such as bubble sort,insertion sort,selection sort,merge sort,quick
sort.
A C++ program that implements a sorted array using selection sort is given as follow:
#include <iostream>
using namespace std;
void SelectionSort(int a[],int n){
int i,j,min,temp;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
if(a[j]<a[min])
min=j;
temp=a[i];

30
a[i]=a[min];
a[min]=temp;
}
}
int main() {
int a[ ]={22,91,35,78,10,8,75,99,1,67};
int n=sizeof(a)/sizeof(a[0]);
int i;
cout<<"Given Array is:"<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
SelectionSort(a,n);
cout<<"Sorted Array is:"<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
Output:
Given Array is:
22 91 35 78 10 8 75 99 1 67
Sorted Array is:
1 8 10 22 35 67 75 78 91 99

31
UNIT 3: INTRODUCTION TO COMPUTER NETWORK
3.1. Fundamental of computer Network
3.1.1. Computer Network Definition
A computer network is a system of interconnected computers for the purpose of sharing data and resources.
A computer network is two or more computer system which linked by some form of transmission medium that
enable them to share information.
E.g: hard disk space, printers, programs, modems, scanners etc.
Computers on a network are called nodes and Nodes can include hosts such as personal computers, phones, servers
as well as networking hardware.
Two devices are networked together when one device is able to exchange information with the other device.
The computer can be connected to another in the two ways.
Wired network: Computers are connected using cable media. Most commonly Ethernet Cable, coaxial cable
and optic fiber.
Wireless network: Computers are connected using wireless media. Radio waves are used in wireless mode.

3.1.2 Properties of Computer Network


● Easy Sharing of Resources: Computers are able to share various resources easily over a network. Shared
resources can be Internet, files, printer, storage and others.
● Performance: It is achieved by measuring the speed of data transmission with number of network users,
connectivity used and the software used. The commonly measured qualities in the network performance are
Bandwidth and Latency.
● Reliability: It means that computer network provides assurance of the delivery of data to the intended recipient.
● Scalability:The possibility of adding new computer without affecting the network performance.
● Security: computer network must be secured for the benefit of the user and data protection. The security is
achieved by protecting data from unauthorized access.
● Quality of Service (QoS): Quality of Service refers to the mechanism that manage congested network traffic.
● Fault tolerant: A fault tolerant network limits the impact of hardware or software failure and recovers quickly
when a failure occurs
3.1.3 Advantages and Disadvantage of Computer Networking
a) The common advantages of computer network
1. Enhanced communication and availability of information: It allows access to a vast amount of useful
information.
Example: Population data, newsletters, online businesses, contents, Applications.
2. Allow resource sharing: Fewer resources are needed when an organization uses a computer network.
Example: only one printer is needed instead of buying a printer for each office.
3. File sharing made easy: computer network allows people to share files, which helps to save more time and
effort.
Example: A teacher can share homework to all students through school network
4. Improve storage capacity: since you are going to share information, files and resources to other people, you
have to ensure that all data and content are properly stored in the system.
5. Cost efficiency: on computer network, you can share software license installed on the server and can then be
used by various workstations.
6. Security of information and resources: users cannot see other users' files unlike on stand-alone machines.
7. Backup of data is easy as all the data is stored on the file server.
b) The common disadvantages of computer networking
1. Lack of independence: people rely on computer network and when the system is down, people get stack.
Most of organizations depend on the computer networks.
2. Security issues: huge number of people use a computer network to get and share their files and resources, a
certain user’s security would be always at risk. There might even be illegal activities that would occur,which you
need to be careful about and aware of.
3. Lack of robustness: When computer network’s main server breaks down, the entire system would become

- 34 -
useless.
To deal with these problems, huge networks should have a powerful computer to serve as a file server to make
setting up and maintaining the network easier.
4. It allows for more presence of computer viruses and malware
There would be instances that stored files are corrupt due to computer viruses,thus,network administrators should
conduct regular check-ups on the sysrtem and the the stored files at the same time.
5. Its light policing usage promotes negative acts
It has observed that providing users with internet connectivity has fostered undesirable behavior among
[Link] that the web is a minefield of distractions including online games,humor sites and even porn sites.
6. It requires an efficient handler(controller)
For a computer network to work efficiently and optimally,it requires high technical skills and know how of its
operations and administration.a person just having basic skills cannot do this job.
7. It requires an expensive set-up
Its initial set up cost can still be high depending on the number of computers to be [Link] devices
such as routers,swithes,hubs,etc,can add up to the cost.
3.1.4 Types of computer networks
A computer network is classified by the following specific characteristics:
1. Size of the area covered
2. Number of users connected
3. Number and types of services available
4. Area of responsibility
The followings are type of computer networks:
1. Personal Area Network (PAN)
A personal area network (PAN) is a network that connects devices, such as mice, keyboards, printers, Smartphone,
and tablets within the range of an individual person. PAN has connectivity range up to 10 meters. PAN may include
wireless computer keyboard and mouse, Bluetooth enabled headphones, wireless printers and TV remotes. All of
these devices are dedicated to a single host and are most often connected with Bluetooth technology.
Bluetooth is a wireless technology that enables devices to communicate over short distances. A Bluetooth device can
connect up to seven other Bluetooth devices.

2. Local Area Network (LAN)


Traditionally, a LAN is defined as a network that covers a small geographical area. However, the distinguishing
characteristic for LANs today is that they are typically owned by an individual, such as in a home or small business,
or wholly managed by an IT department, such as in a school or corporation.
Note: LAN uses Ethernet IEEE 802.3 as its standard.

- 35 -
A Wireless LAN (WLAN) is a LAN that uses radio waves to transmit data between wireless devices. In a traditional
LAN, devices are connected together using copper cabling. In some environments, installing copper cabling might
not be practical, desirable, or even possible. In these situations, wireless devices are used to transmit and receive data
using radio waves. As with LANs, on a WLAN, you can share resources, such as files, printers, and Internet access.
Note: WLAN uses Ethernet IEEE 802.11 as its standard.

3. Metropolitan Area Network (MAN)

A metropolitan area network (MAN) is a network that spans across a large organization like campus or a city. The
network consists of various buildings interconnected through wireless or fiber optic backbones.
A backbone is the part of the computer network infrastructure that interconnects different LAN networks and
provides a path for exchange of data between these different networks
The communication links and equipment are typically owned by a network service provider who sells the service to
the users. A MAN can acts as a high-speed network to enable sharing of regional resources.

4. Wide Area Network (WAN)


A WAN connects multiple networks that are in geographically separated locations. The distinguishing characteristic
of a WAN is that it is owned by a service provider. WAN network provides connectivity to MANs and LANs. The
most common example of a WAN is the Internetwork or Internet in short. The Internet is a large WAN that is
composed of millions of interconnected networks.
Example: Kigali and Nairobi networks are connected through the Internet
3.2Computer Network Concept and Technology
3.1.1 Network metrics
Network metrics are defined as standards of measurement by which efficiency, performance, progress, or quality of a
plan, process can be assessed. Network metric are used by a router to make routing decisions.
When data is sent over a computer network, it is broken up into small chunks called packets.
Each packet contains source and destination address information. Packets are sent across a network one bit at a time.
a. Bandwidth
Bandwidth is the amount of data that can be transmitted in a fixed amount of time. Bandwidth is measured in the
number of bits that can be sent every second.
It can be measured in b/s(bits per second),kb/s(kilobits per second),…
b. Latency
Latency is the time between requesting data and receiving data. More simply put, the time it takes to establish a
connection between your computer and the server hosting the website you requested.
c. Throughput:
Throughput is the actual rate at which information is transferred. It measures the amount of completed work against
time consumed and may be used to measure the performance of a processor, memory and/or network
communications.

d. Error rate:
Error rate is the number of corrupted bits expressed as percentage or fraction of the total sent.

- 36 -
e. Jitter:
Jitter is variation in packet delay at the receiver of information. For measuring the capacity of all of these metrics
above, we focus on capacity of message and this one change into different form depending on the network devices
where this message is located.
3.2.2 Data Transmission model
The term transmission mode is used to define the direction of signal flow between two linked devices. The data that
is transmitted over the network can flow using one of three modes: simplex, half-duplex and full-duplex.

1. Simplex: it is a single one-way transmission. In a simplex transmission mode, the communication between
sender and receiver occurs only in one direction. That means only the sender can transmit data, and receiver can
receive that data. The receiver cannot transmit any information back to the sender.

Picture: Keyboard to monitor is an example of simplex transmission mode.


Example of simplex transmission:
 Communication between a computer and a printer

 Listening to the radio


 The signal that is sent from a TV station to your home TV
2. Half-Duplex: data flows in one direction at a time. In half-duplex, the channel of communications allows
alternating transmission in two directions, but not in both directions simultaneously.

- 37 -
Picture : Example of Half-duplex is the Talkie- Walkie used by the police.
3. Full-Duplex: data flows in both directions at the same time. In a full duplex transmission mode, the
communication between sender and receiver can occur simultaneously. Sender and receiver both can transmit and
receive simultaneously at the same time.
e.g: A telephone conversation is an example of full-duplex communication. Both people can talk and be heard at the
same time.
Basis for Simplex Half Duplex Full Duplex
Comparison
Direction of Communication Communication is two- directional Communication is two
Communication is unidirectional. but, one at a time. directional and done
simultaneously.
Send/Receive A sender can send data A sender can send as well as A sender can send as well as
but, cannot receive. receive the data but one at a time. receive the data
simultaneously.
Performance The half-duplex and full The full duplex mode produces Full duplex has better
duplex produces better higher performance than half performance as it doubles the
performance than the duplex. utilization of bandwidth.
Simplex.
Example Keyboard and Walkie-Talkies, internet Telephone.
monitor. chart

3.2.3. Internetwork (Internet, Intranet, Extranet)


A network of networks is called an internetwork, or simply the Internet. The Internet, extranets, and intranets all
rely on Transport Control Protocol / Internet Protocol (TCP/IP).
However, they are different in terms of the levels of access they allow to various users inside and outside the
organization and the size of the network.
1 .An Intranet is a private computer network that uses Internet Protocol to securely share any part of an
organization's information or operational systems within that organization. Only users inside the organization are
only allowed to access it.
2 .An Extranet is a private network that uses Internet protocols, network connectivity. An extranet can be viewed
as part of a company's intranet that is extended to users outside the company, the connectivity is made possible by
the Internet.
3 .The Internet is a global system of interconnected computer networks that use the standard Internet Protocol
suite (TCP/IP) to serve billions of users worldwide.
The difference between the Internet and Extranets is that while the extranet allows limited access to non-members
of an organization, the Internet generally allows everyone to access all network resources.
3.3 Local Area Networks (LANs)
3.3.1 Definition
Local Area Networks (LANs) are networks usually confined to a geographic area, such as a single building or a
college campus. LANs can be small, linking as few as three computers, but often link hundreds of computers used by
thousands of people.
3.3.2 LAN Categories
1. Peer-to-Peer Network
A peer-to-peer (P2P) network is created when two or more computers are connected and share resources without
going through a separate server computer.
In a peer-to-peer network, there is no hierarchy among the computers, nor are there any dedicated servers.

Each device on the network, also called a client, has equivalent capabilities and responsibilities.
A user is responsible for its own resources and can decide which data and devices to be shared with other computers.

- 38 -
Because individual users are responsible for the resources on their own computers, the network has no central point
of control and no central administration. Peer-to-peer networks work best in environments with ten or fewer
computers.

Advantages of peer to peer network are as follows:


● The main advantage of peer to peer network is that it is easier to set up
● In peer-to-peer networks all nodes are act as server as well as client therefore no need of dedicated server
● The peer to peer network is less expensive
● Peer to peer network is easier to set up and use ,this means that you can spend less time in the configuration and
implementation of peer to peer network.
Disadvantages of peer to peer network
● A computer can be accessed anytime
● Network security has to be applied to each computer separately
● Backup has to be performed on each computer separately
● No centralized server is available to manage and control the access of data.
2. Client-Server Network
In a client-server network, the client requests information or services from the server and the server provides the
requested information or service to the client.

In a client-server network, resources are controlled by a centralized network administration. The network
administrator implements data backups and security measures. The network administrator also controls user access to
the server [Link] at the same time.
Advantages of Client-Server Network
● Centralization of control: access, resources and integrity of the data are controlled by the dedicated server so
that a program or unauthorized client cannot damage the system.
● Scalability: You can increase the capacity of clients and servers separately. Any element can be increased (or
enhanced) at any time, you can add new nodes to the network (clients or servers).
● Easy maintenance: distribute the roles and responsibilities to several standalone computers, you can replace,
repair, upgrade, or even move a server, while customers will not be affected by that change (or minimally affect).

- 39 -
Disadvantage of Client Server Networks
● There is a reliance on the central server, if it fails, no work can be done
● A network manager is required and this costs money
● The server costs money, as does the network operating system
● Servers are powerful, thus expensive
● Lots of network traffic.
Notes:Advantages of Client Server Networks over Peer to Peer Networks
● Centralization: Unlike Peer to Peer, where there is no central administration, Client Server Networks have a
centralized control.
● Proper Management : All the files are stored at the same place. Therefore, management of files becomes easy
and it is easier to find files.
● Back-up and Recovery possible: As all the data is stored on server it is easy to make a back-up of it. Also, in case
of some break-down if data is lost, it can be recovered easily and efficiently. While in peer to peer network, we
have to take back-up at every workstation.
● Upgrade and Scalability in Client-server set-up: Changes can be made easily by just upgrading the server. Also
new resources and systems can be added by making necessary changes in server.
● Accessibility: From various platforms in the network, server can be accessed remotely.
● Security: Rules defining security and access rights can be defined at the time of set-up of server.
Disadvantages of client server network over the Peer to peer network
● Congestion in Network: Too many requests from the clients may lead to congestion, which rarely takes place in
Peer to Peer network. Overload can lead to breaking-down of servers. In peer-to-peer, the total bandwidth of the
network increases as the number of peers increase.
● Client-Server network is not as robust as a Peer to Peer network and if the server fails, the whole network goes
down.
● Cost: It is very expensive to install and manage client server network.
3.4. Physical Components
i. Nodes/hosts
A network host or a node is a computer or any other device that is directly connected to a computer network. A
network host may offer information resources, services, and applications to users.
ii. Network Interface Card (NIC)
Network Interface card is a component that allows the computer to communicate across a network. This component is
frequently built into the motherboard of today's computers, but it can also be a separate card for use in a PCI slot.
Network Interface cards be either wired or wireless.
However, some cards do support both wireless and wired networking
Note: A wireless NIC has an antenna connected to the back of the card or attached with a cable so that it can be
positioned for the best signal reception. You must connect and position the antenna.

Picture: Wireless Network Interface Card


iii. Media Access Control Address(MAC adress)
Media Access Control Address (MAC address) of a device is a unique identifier assigned to network interfaces for
communications at the data link layer of a network segment. MAC address is a physical address of Network
Interface Card. In other words MAC addresses are linked to the hardware of network adapters.
Example of a MAC address: [Link].

- 40 -
To find the Mac address of your computer,do the following:
Step1: Click the Run button in the windows 10 Start Menu
Step 2: Type cmd in the Open prompt of the Run menu and click OK to launch a command prompt window
Step 3: Type ipconfig /all at the command prompt to check the network card settings.

Step4: MAC address is listed by ipconfig under Physical Address

iv. Modem
A modem is a hardware device that enables a computer to send and receive data over a telephone line or a cable or
satellite connection. Modem is used to transmit digital information via analog systems. The word "modem" is
derived from the term "Modulator - Demodulator."
The essential functions of a modem are:
● Modulate: an analog carrier signal to carry digital information, it means to convert the analog signal to digital
signal.
● Demodulate: a similar signal so as to decode the digital information from the analog carrier signal and it means to
convert the same signal back to the analog signal then transmitted through telephone line.
Note:They are two types of modem:
 Internal modem: Internal modems are circuit boards that plug into a computer's motherboard
 External Modem: An external modem is a discrete unit housed in a separate case. Typically, an external modem
is connected to the telephone line and the computer via cables or USB.

v. RJ 45 Connector and Port


A registered jack (RJ) is a standardized physical network interface for connecting telecommunications or data
equipment.
The RJ45 port is the network port on a computer and this socket has many names. It is also known as the Ethernet
port, the network adapter, the network jack or the RJ45 jack.
3.5. Network Devices
3.5.1 Hub
A hub is a network hardware device for connecting multiple devices together and making them act as a single network
segment.
Definition:
A network segment is a portion of a computer network that is separated from the rest of the network by a
network device.
Hub receives message on one port and then send it out to all other ports, this means that when hub receives message,
the received message is regenerated or duplicated and sent to all computers connected to the hub, each computer on
the network receives the message, if it is not the destination message is destroyed, if it is the destination it reads the
message.

- 41 -
Picture : HUB
Note: Hub are used less often today because of the effectiveness and low cost of switch.
Hub do not segment network [Link] one device sends traffic,hub bloods that traffic to all other devices
connectewd to [Link] devices are sharing the bandwidth.
3.5.2. Switches
Switch filters and segments network traffic by sending messages only to the device to which it is sent.
This means that when a switch receives a message do not duplicated it, it sends it directly to the destination
computer. This provides higher dedicated bandwidth to each device on the network.

Picture : SWITCH
A switch maintains a switching table, the switching table contains a list of all MAC addresses of computers on the
network and a list of switch port which are used to reach a computer with a given MAC address.
When message arrives that is destined for a particular MAC address, the switch uses the switching table to determine
which port to use to reach the MAC address. Then message is forwarded to the destination.
3.5.3. Bridge
A network bridge is a computer networking device that creates a single aggregate network from multiple
communication networks or network segments. This function is called network bridging

Picture : Two network segments connected via a bridge


Notice that Bridges were introduced to:
 divide LANs into segments.
 keep a record of all the devices on each segment.
 filter network traffic between LAN segments.
3.5.4. Access point
The Access Point is connected to a switch using UTP cable, therefore it can provide access to the rest of the network.
The range (radius of coverage) for Access Point indoors is 98.4 ft (30 m) and too much greater distances outdoors
depending on the technology used.

- 42 -
Picture : Linksys access point
3.5.5. Router
It is a network device that serves two primary functions:
[Link] connects multiple computers,phones,tablets or other devices to form a managed local area network
ii. it providesinternet access to all of the compatible devices that are connected to the router
So a Router is a device like a switch that routes or forwards data packets based on their IP [Link],in
order for the router to distribute and deliver data to the devices within the LAN,it must be connected to an internet
service provider’s customer premises equipment(CPE).
It is like a traffic police man,this inelligent device directs network traffic.
Routers normally connect LANs and WANs together to allow trtansfer of data packets from source to destination
and have a dynamically updating routing table based on which they make decisions on routing the data packets.
Note:
Router operates between different networks and routes traffic between them whereas an Access point will
operate in a single network and is used to wiressly extend your existing network.
Routing is the process of moving data signals across network from the source node to the destination node.
3.5.6. Gateway
A gateway, as the name suggests, is a passage to connect two networks together that may work upon different
networking models. They basically works as the messenger agents that take data from one system, interpret it, and
transfer it to another system.
Gateways are also called protocol converters and can operate at any network layer. Gateways are generally more
complex than switch or router.
3.5.7. Repeaters
A repeater is a network device that accepts a network cable in one end amplifies the signal and sends the signal out
the other end. A repeater strenghens the signals so that cable can run large distance.
A reapeater receives a signal from one segment of a network,cleans itto remove any distortion,boots it and then sends
it to another segment.
3.6. Network Transmission Medium
This is the physical mean of communication between network computers.
Data transmission media are the physical materials used to transmit data between computers.
Packet of data can be transmitted on network as electrical signals in electric wire, light signal in fiber optic cables
or as electromagnetic waves through space.
There are two main types of data communication media used in network:
 Bounded or Guided media: which transmit signals by sending electricity or light over a cable wire.
Common examples of bounded media are twisted cables, Coaxial cables and fiber optic cables.
 Unbounded media: which transmit data through the air, radio waves, layer or infrared signal and satellite
based microwaves, etc.
3.6.1. Guided transmission media
A wide variety of networking cables are Coaxial, Fiber optic and twisted-pair cables which use electrical signals
over copper to transmit data while Fiber-optic cables use light signals to transmit data. These cables differ in
bandwidth, size, and cost.

- 43 -
[Link] cable

It is used by both cable television companies and satellite communication systems and it carries data in the form of
electrical signals. There are several types of coaxial cable:
● Thicknet(thickwire) or 10BASE5 - used in networks and operated at 10 Mb/s with a maximum length of 1640.4
ft. (500 m)
● Thinnet(thinwire) or 10BASE2 - used in networks and operated at 10 Mb/s with a maximum length of 607
ft.(185 m).
i) Advantages of coaxial cable
 Broadband system coax has a sufficient frequently range to support multiple channel,which allows for much
greater throuput
 Greater bandwidth
 Lower error rate
 Coaxial cable shielding reduces Attenuation,noise and crosstalk
ii) Disadvantages
 High installation costs and difficult
 Succeptible to damage from lighting strickers
 Reconfiguration is difficult.

b. Twisted-pair copper cabling


Twisted-pair is a type of copper cabling used for telephone communications and most Ethernet networks. The pair is
twisted to provide protection against crosstalk, which is the noise generated by adjacent pairs of wires in the cable.
The use of this cable is limited by two factors:
i) Attenuation: the strength of signal reduces as the distance increases i.e the cables loose signals strength when they
exceed their maximum length stated in network specification.

Note:There exist three main sources of attenuation:


 Resistance or impedance: this refers to the loss resulting from the wire resistance. The loss is minimized with
the choice of the metal with low resistivity (copper and Gold for example)
 Dielectric losses: are caused by the heating effects when a varying electric field passes through an insulator
 Radiation losses: occurs because the cable acts as an antenna.
ii) Crosstalk: this refers to interference generated by cables when they are too close to each other. Signals from one
line get mixed with signals from another.
b.1. Types of twisted pair cables
There are two types of twisted pair cables: unshielded and shielded cables
b.1.1. Unshielded twisted-pair (UTP)
Unshielded twisted-pair (UTP) cabling is the most common variety of twisted-pair cabling.
There are two different wiring schemes called T568A and T568B. Using the T568A and T568B wiring schemes, two
types of cables can be created: a straight-through cable and a crossover cable.

- 44 -
1. A straight-through cable is the most common cable type. It maps a wire to the same pins on both ends of the
cable. The order of connections (the pin out) for each color is the exact same on both ends.
Two devices directly connected and using different pins for Transmit and Receive are known as unlike devices. They
require a straight-through cable to exchange data. For example, connecting a PC to a switch requires a straight-
through cable.
Summary:
The straightthrough cable has the following pins correspondence:
Pin Side A Side B
1 Pin 1 Pin 1
2 Pin 2 Pin 2
3 Pin 3 Pin 3
4 Pin 4 Pin 4
5 Pin 5 Pin 5
6 Pin 6 Pin 6
7 Pin 7 Pin 7
8 Pin 8 Pin 8

2. A crossover cable uses both wiring schemes. T568A on one end of the cable and T568B on the other end of the
same cable.
Devices that are directly connected and use the same pins for transmit and receive, are known as like devices. They
require the use of a crossover cable to exchange data. For example, connecting a PC to another PC requires a
crossover cable.
Note: The most used cable standards are below:
● 100Base-TX: known as Fast Ethernet, it uses category 5, 5E, or 6 UTP cable and it wires u to 100 meters long.
● 1000Base-T means that the speed of the network is up to 1000 Mbps, baseband signaling is sed, T stands for
twisted-pair as UTP cable used
Notice that the crossover cable can also connect the following devices:
• Workstation to workstation
• Switch to hub
• Switch to switch
• Hub to hub
• Router to router
• Router to PC
The crossover cable has the following pins correspondence:
Pin Side A Side B
1 Pin 1 Pin 3
2 Pin 2 Pin 6
3 Pin 3 Pin 1
4 Pin 4 Pin 4
5 Pin 5 Pin 5
6 Pin 6 Pin 2
7 Pin 7 Pin 7
8 Pin 8 Pin 8
Summary of cables used to connect network devices
Hub Switch Router Workstation
Hub crossover crossover straight straight
Switch crossover crossover straight straight
Router straight straight crossover crossover
Workstation straight straight crossover crossover

- 45 -
b.1.2. Shielded twisted-pair (STP)
The STP type similar to UTP cable except that there is a metal foil or braided metal-mesh cover that encases each
pair of insulated wires.
The basic difference between UTP and STP is that UTP is a cable with wires that are twisted together to
reduce noise and crosstalk. On other hand, STP is a twisted pair cable confined in foil or mesh shield that guards
the cable against electromagnetic interference.
Note: Advantages of twisted pair cables
It is easy to install
STP cables yield maximum bandwidth regardless of the external [Link] shielding,however makes the
cable heavier and more difficult to bend.
Cost of installation is low since the cables are readily available in the market
STPs are commonly used by large-scale companies in high-end applications that require the maximum
bandwidth.
It can carry up to a maximum of 100 Mbps.
Disadvantages of twisted pair cables
It is very dsensitive to electromagnetic interference compared to other cables.
UTP has a limited bandwidth,which restricts long distance transmission with low error rates.
c. Fiber optic cables
An optical fiber cable, also known as a fiber optic cable, is an assembly similar to an electrical cable, but containing
one or more optical fibers that are used to carry light signals.
The electric signals from the computing nodes are converted to light signals using the light emitting diode(LED) or
lasers and then they are transmitted through the [Link] the receiver,the light signals are converted back to
electrical signals by a photosensitive device(photodiode)
c.1. Advantages of fiber optic
 The fiber optic is immune to electromagnetic interference(EMI) , therefore they are not affected by radio
interference or cross talk.
 They have become the standard for connecting networks between buildings due to their immunity the effects of
moisture and lighting.
 Fiber optic can transmit signal over much longer distance than coaxial cable and twisted cables
 They can carry information at high rate speed.
 The distance can be up to 2000 meters without repeater.
 Security: it is difficult to tap into optical fiber line. If this is happen it will be noticed immediately.
 Low transmission loss.
 Data can be transmitted digitally.
 They are not affected by weather conditions such as changes in the temperature,rain,cld or other environment
conditions.
c.2. Disadvantages of fiber optics
 They require expensive connectivity devices and media.
 Their installation is a delicate process because the cables must be handled carefully.
 They relatively complex to configure.
 A broken fiber optic cable is difficult and expensive to repair.

3.6.2. Unguided transmission media


Unguided media transport electromagnetic waves without using a physical conductor. This type of communication is
often referred to as wireless communication. The mediums used in wireless communications are air, vacuum and
even water. Air is the most commonly used as medium.
a. Wireless Transmission
Wireless transmission can be categorized into three broad groups namely radio waves,microwaves, infrared.

- 46 -
a.1. Radio waves

Radio waves are normally omnidirectional. When an antenna transmits radio waves, they are propagated in all
directions. This means that the sending and receiving antennas do not have to be aligned. The omnidirectional
characteristics of radio waves make them useful for multicasting, in which there is one sender but many receivers.
Our FM radio stations, cordless phones and televisions are examples of multicasting.

a.2. Infrared
Infrared is used in devices such as the mouse, wireless keyboard and printers. Some manufacturers provide a special
port called the IrDA port that allows a wireless keyboard to communicate with a PC.
Infrared signals have frequencies between 300 GHz to 400 THz. They are used for short-range communication

The disadvantages of using infrared


● Infrared signals cannot be used for long distance communication.
● Infrared waves can not be used outside of a building because sun's rays contain infrared waves that can interfere
with communication.

a.3. Bluetooth
Bluetooth technology is designed to serve as a new way of connecting devices. Bluetooth technology has an
advantage of being low investment and low energy consumption demanding. The difference between Bluetooth and
infrared is that Bluetooth allows communication when there is a barrier or a wall.

- 47 -
a.4. Wi-Fi (Wireless Fidelity)
Wi-Fi (Wireless Fidelity) is a standard that certifies that wireless devices in Wireless LAN to work together.
WI - FI uses radio signals to transmit high speed data over the wireless network, the Access Point is used to connect
devices and it acts as the central device for Wireless LAN. Wireless devices can be: smartphones, PDAs, IPad,
laptop and notebook.
APPLICATION
General steps to connect to a WI-FI network near you
The following steps run through the general steps that anyone needs to take to get connected to the internet via WI-FI.
Step 1: Locate yourself in a property or public space that has a wireless router.
Step 2: Make sure that the device you're going to use is:
• Capable of connecting to the internet and
• Capable of connecting to WI-FI.
Step 3: Find out the name of the WI-FI network that the router in your location is transmitting.
Step 4: Once you know the name of the WI-FI network, use your chosen device to find it.
Note: Following are steps to follow: navigate to Wi-Fi settings > turn Wi-Fi on > click on the name of your Wi-Fi
network > click "connect".
Step 5: Many WI-FI networks are made private, with access restricted via a password. If your chosen WI-FI network
is password protected, at this point it will ask you enter that password.

b. Cellular technology
Cellular technology enables mobile communication because they use of complex two-way radio system between
mobile unit and the wireless network.
Cell phones network use one of the following computing technology:
 Global System for Mobile Communication(GSM)
 Time Division Multriple Access(TDMA)
 Code Division Multiple Access(CDMA)
Note: Cellular network generations
The G in 1G,2G, 3G and 4G stands for Generation, and they refer to 2nd, 3rd and 4th Generation of wireless
technology. The newer generation is faster, more secure and more reliable. Briefly the difference between
generations is expressed in terms of speed
Features found in each cellular network generation are the following:
1stGeneration:
 Offered in analog technology
 Enabled one user per channel(half duplex)
2nd Generation:
● Digital cellular telephony
- 48 -
● Mobile 2G digital technologies increased voice capacity Delivering mobile voice services to the masses – more
people, in more places.
● Enabled more users per channel.
3rd Generation:
● High-speed digital cellular telephony (including video telephony).
● Mobile 3G evolved mobile for data introducing high-speed internet access for the first time.
● Data enabling mobile broadband.
4thGeneration:
 4G delivers up to 100Mbps for mobile access, and up to 1Gbps for wireless access.
 Most wireless carriers offering HSPA (High Speed Packet Access).
 IP-based “anytime, anywhere” voice, data, and multimedia telephony at faster data rates than 3G
 Evolving to provide more data capacity Delivering faster and better mobile broadband experience
 Download, browse, stream, and game faster than ever with faster and better connectivity 4G LTE – LTE (Long
Term Evolution) is one of the two standards offered within 4G, the 4G LTE is a type of 4G technology, and it
delivers the best performance and speeds available today.

c. Location tracking through GPS


1. What is GPS?
GPS (Global Positioning System) is the U.S. satellite-based navigation system that uses a network of 24 satellites to
provide 3-D locating data to GPS receivers on Earth.
2. How Does GPS Work?
All 24 GPS satellites circle the planet twice a day in a very specific orbit. During their travels, the satellite sends
signal information to Earth. A GPS receiver receives the information from all available satellites and calculates the
GPS receiver’s exact location by comparing the time that a signal was transmitted by the satellite to the time the
receiver receives the signal.
3.7. IP Address
3.7.1 Understand IP Addresses
An IP address is an address used in order to uniquely identify a device on a computer network.
3.7.2 IP Versions
There are two versions of IP addressknown as IP version 4 and IP version 6
a. IP version 4
IP version 4 is the common used IP address,
i. Structure of IP address
 An IP address is simply a series of 32 binary bits. Because it is difficult for human to read a binary IP address, the
32 bits are grouped into four-8-bits bytes called octets.
 When a computer is configured with an IP address it is entered as doted decimal number such as [Link]
 When a host receives an IP address , it looks at all 32 bits as they are received by the NIC
 Each octet is made up with 8 bits an each bit has a value. The four groups of 8 bits have same set of value.
ii. Parts of the IP address
The logical 32 bits IP address is made up two parts which are network part or network address
and the second one is host address . Both parts are needed in IP address.
E.g. Having the IP address [Link] the three first octets identify the network address and the last octet
identifies the host address.
This is known as hierarchical addressing because the network portion indicate the network on which each unique
host address is located.

- 49 -
The table below shows the network and host ID for class A,B and C IP adressing.
Class IP adress Network ID Host ID
A w.x.y.z w x.y.z
B w.x.y.z w.z y.z
C w.x.y.z w.x.z Z
iii. Classes of IP version 4
There are five classes of available IP ranges: Class A, Class B, Class C, Class D and Class E, while only A, B, and C
are commonly used classes D and E are reserved.
Here is a listing of these addresses:
 Class A
A class A adresses are designed to network with very large number of hosts.
In class A the first bit of the first byte is always 0 (or 0xxxxxxx) where x stand for any value (either 0 or 1)
Minimum: 00000000
Maximum: 01111111
Note:The valid range in class A =[𝟏 − 𝟏𝟐𝟔]

The range of IPs 127.x.x.x is reserved for the loopback or localhost, for example, [Link] is the common loopback
address. Range [Link] broadcasts to all hosts on the local network.
The first byte in class A represent Network address while the three remaining represent the host address.
Thus class A=Network- Host-Host-Host

 Class B
In class B the first bit of first byte is always 1 and the second bit of first byte is always 0 means 10xxxxxx.
Minimum: 10000000=128
Maximum: 10111111=191
Note: Valid range:128-191
The two first byte in class B represent Network address while the two remaining represent the host address.
Thus class B=Network-Network-Host-Host

 Class C
The first bit of first byte is always 1, the second bit of first byte is always 1 and the third bit of first byte is always 0 i.e
11xxxxxx.
Minimum: 11000000= 192
Maximum: 11101111= 223

Note: Valid range: 192-223

The three first bytes in class C represent Network address while the last byte remaining represent the host address.
Thus class C=Network-Network -Network –Host

Note: Subnet Masks


A subnet mask help to know which portion of the address identifies the network and which portion of the address
identifies the host. Class A, B, and C networks have default masks, also known as natural masks, as shown here:
Class A: [Link]
Class B: [Link]
Class C: [Link]
Table below shows classes of IP addresses

- 50 -
IP Address Total number First octet of IP Number of Usable Number of Number of host
Class of bits for address network ID number of possible IDs per network
network ID / bits used to network network IDs ID
host ID identify class ID bits
Class A 8 / 24 0xxx xxxx
1
8-1 = 7 27-2 = 126 224-2 =16,277,214
Class B 16 / 16 10xx xxxx
2
16-2 = 14 214=16,384 216-2 = 65,534
Class C 24 / 8 110x xxxx
3
24-3 = 21 221=2,097,152 28-2 = 254
Class D and Reserved for multicasting
Class E

Note:Devices that are attached to a network have two addresses such as Media Access Control (MAC) address and the
IP address.
The MAC address is hard coded onto the network interface card (NIC) by the manufacturer and it does not change.
The IP address is assigned to a host to the network and may change.

b. Internet Protocol Version 6 (IPv6)

IPv6 (Internet Protocol Version 6) also called IPng (Internet Protocol next generation) is the newest version of the
Internet Protocol reviewed to replace the current version of IPv4. IPv6 is designed to allow the Internet to grow
steadily, both in terms of the number of hosts connected and the total amount of data traffic transmitted.

IPv6 shows a 128-bit address in eight 16-bitblocks separated by colons


Example: [Link] [Link]
Note: IPv4 Vs IPv6: What’s The Exact Difference
The IPv4 version of the internet protocol has a 32-bit addressing space of about 4.3 billion IP addresses.
But due to the prompt use of the Internet, wireless technology, and the implementation of LTE technology, the
range of IP addresses is exhausted to a great extent.

To overcome this shortage of the IP pool, Internet protocol version 6 (IPv6) which enhances the address
capabilities of IPv4 by deploying 128 bits addressing instead of 32 bits, was introduced.
Difference Between IPV4 Vs IPV6
IPV4 IPV6

1) It stands for Internet Protocol version 4. It stands for Internet Protocol version 6.

2) It is having 32-bit addressing space It is having a 128-bit addressing scheme which implies
which implies that 2^32 = 4.3 billion that it supports 2^128 devices which is itself a very
devices can be connected with it. huge number .

3) It is a numeric addressing method. For It is alpha-numeric based addressing scheme and for
example, the IP address to allocated user example, the IP address of a host will be like
will be like [Link] [Link]

4) IPV4 supports manual and the DHCP The IPV6 has the feature of auto-configuration and the
configuration method and it doesn’t IPV6 hosts can itself configure themselves to the IPV6
support the feature of auto configuration. network using ICMPv6 messages.

- 51 -
IPV4 IPV6

5) It supports the broadcast addressing It supports multicast features as the single packet data
scheme as the data packet is sent to all can be sent to multiple destination hosts at a time.
the host devices available in the network.

6) The IPV4 doesn’t support any security All the sessions of IPV6 are first authenticated by using
protocols for the secure transmission of the various security protocols like IPSec etc. then the
data between hosts. communication between the hosts on a secure network
will initiate.

7) The IPV4 header length is variable and The IPV6 header has a fixed header length of 40 bytes
thus routing process is bit complex as thus offers a simplified routing process.
compared to IPV6.

8) The checksum error is detected and The checksum error is not computed in IPV6.
computed in IPV4.

9) It doesn’t support any IP host mobility It supports the IP host mobility feature which enables
function. the moving node to temporarily change its location in a
network with maintaining the ongoing connections at
the same time.

10) The quality of service QoS feature is not It is having an in-built QoS feature and is very
very efficient. efficient.

What Is IPv4
The Internet Protocol version 4 is working at the Internet layer of the TCP/IP model and is accountable for
recognizing the hosts given upon the IP addresses and to route the data packet accordingly in the network or
among various networks.

Most of the elements of the Internet use IPv4 addressing scheme. An IPv4 address has a 32-bit addressing
space, which means 2^32 = 4.3 billion devices.

IPv4 Header

 Version: The IPv4 has version number 4.


 Header length: It shows the size of the header.

- 52 -
 DSCP: It stands for a differentiated services code field and is deployed for constructing packets.
 Total length: It denotes the size of the header plus the size of the data packet.
 Identification: If the data packet is fragmented for the period of transmission, the field is used to allocate
each, and the same number so that it helps in constructing the original data packet.
 Flags: It is used to denote the fragmentation procedure.
 Fragment offset: It indicates the fragment number and source host which uses them for re-arranging the
fragmented data in the correct order.
 Time to leave: To elude the chances of looping in the network, each packet is transmitted with some TTL
value set, which indicates the number of hops that it can go across. At every hop, the TTL value is degraded by 1
and when it attains zero, then the packet is abandoned.
 Protocol: It denotes the protocol that it is using for transmitting data. TCP has protocol number 6 and UDP
has protocol number 17.
 Header Checksum: This field is used for error detection.
 Source IP address: It saves the IP address of the source end host. The length is 32-bit.
 Destination IP address: It saves the IP address of the destination host. The length is 32-bit.
IPv4 Addressing Modes
There are three kinds of Addressing Modes:
(i) Unicast Addressing Mode: In this mode, the sender can send the IP packet only to one destined end host.
The IP address of the destination host is contained in the 32-bit destination address IP field of the header.
(ii) Broadcast Addressing Mode: In this mode, the data packet is broadcast or sent to all the host’s end
devices present in the network. The broadcast IP address is [Link]. When the receiver host analyzes this
address, then all will entertain the data packets.
(iii) Multicast Addressing Mode: In this mode, the source host can send packets, not to all, but more than
one which means several destination hosts. The host determines the destination address for delivery from the
destination header field which is having a special range of network addresses that are allowed to deliver the data
packet.
Hierarchical Addressing Scheme:
The 32-bit IP address contains the IP address information of the network, the sub-networks and the hosts
connected with it. This permits, the IP address scheme to be hierarchical as it can serve several sub-networks and
in turn the hosts.

Private IP addresses in IPv4:


Each class of the IP has some of the IP range reserved for private IP addresses. These can be deployed within
a network like the LAN network of an office but can’t be used to route traffic on the Internet. Thus network
devices like routers and switches will drop packets of this below-mentioned range during transmission.

IP Range Subnet mask

[Link] to [Link] [Link]

[Link] to [Link] [Link]

[Link] to [Link] [Link]


We can’t waste this huge range of IP addresses just to be used for Intranet. Thus IP translation process which is
known as NAT is used to convert these into public IPs, so that can it be used for communication with the far end.

- 53 -
Loopback IP addresses in IPv4:
The range of the IP from [Link] to [Link] is reserved for loopback purposes which means host
node self-addressing. The loopback IP has a big significance in the client-server communication model.

It is used for testing the proper connectivity between two nodes. For Example, A client and a server within
the same system. If the destination address of the host in a system is set as the loopback address, then the system
sends it back to itself and there is not any requirement of NIC.
By ping [Link] or any IP of the loopback IP range, it has been cleared that the connectivity is established
between two systems in a network and they are working property.

Need For A New IP Version


Following are some of the key points for which we need a new IP version:
 The address space provided by IPv4 is limited to 4.3 billion users, which is exhausted due to an increase in
the use of the Internet these days.
 IPv4 doesn’t provide a secure mode of transmission.
 IPv4 doesn’t support auto-configuration features.
 QoS feature is not up to the mark.

What Is IPv6
IPv6 provisions a straightforward and long-term solution to address the space problem. The addresses defined
in IPv6 are huge. IPv6 allows the network devices, big organizations, and even each and every person in the
world to connect to each router, switch, and end device to be connected directly to the global Internet.

Features of IPv6
The Advanced features are as follows:
(i) A large number of Addresses: The main reason for designing IPv6 is the shortage of addresses in IPv4. IPv6
has 128-bit addressing. This address space supports a total of 2^128 (nearby 3.4*10^38) addresses, which is
potentially enough to connect to an enormous number of devices in many more years to come.
(ii) Address Auto-configuration: IPv6 hosts can automatically configure themselves when connected with an
IPv6 network by using ICMPv6 messages. This is in stark contrast to IPv4 networks where a network
administrator has to manually configure the hosts.
(iii) Multicast: The capability of sending a single packet data to several destination hosts is one of the IPv6
specifications.
(iv) Mandatory security in network Layer: IPv4 was build up when security was not an uppermost concern.
Authenticating protocols like Internet protocol security (IPsec) is a part of IPv6 based protocol suite. All
conforming IPv6 sessions can, therefore, be authenticated.
(v) Simplified Router processing: To generalize the routing process, the headers have been redesigned and
made smaller in IPv6 for fast processing.
In IPv4, the header length is variable but in IPv6 it is fixed to 40 bytes. Optional functions have been moved to
separate the extension headers. TTL is replaced by a hop limit. The checksum is not computed.
(vi) IP Host Mobility:
Mobile IPV6 enables a mobile node to arbitrarily change its location on an IP network while maintaining the
existing connections.
One of the extension headers is the mobility header, which is used for implementing this function in IPv6.
(vii) Flow Lebel QoS: All the differential services and integrated services, quality of service attributes from
IPv4 are carried over into IPv6. In addition, IPv6 exclusively has a 20-byte flow label field. This is developed to
provide a rich set of QoS attributes for the growing IPv6 world.

- 54 -
IPv6 Header

The IPv6 header is of 40 bytes and consists of the following fields:


 Version: It is of 4 bits and contains the version of IP which is 6.
 Traffic class: It is of 8 bits and denotes the type of service used for routing packets.
 Flow label: It is of 20 bits. It is used to ensure the sequential flow of traffic. The source device labels the
sequences to the data packets so that it is easier for the router to route the packets in sequence. This field is very
helpful in real-time streaming.
 Payload length: It is of 16 bits. This field will pass on the information to a router about how much data a
particular packet can carry in its payload.
 Next header: This field is of 8 bits and it denotes the presence of an extension header and if it doesn’t
exist then it denotes the upper-layer PDU.
 Hop limit: This is of 8 bits and is used to prohibit the data packet to loop in infinity in the system. This
works similarly to TTL as in the IPv4 header. At each hop, the value of the hop limit is degraded to 1 and when
it reaches zero, the packet is disowned.
 Source address: It is of 128 bits and denotes the address of the source host of the network.
 Destination address: It is also of 128 bits and denotes the address of the receiver host of the packet of the
network.
 Extension headers: The IPv6 fixed header consists of only those fields which carry a piece of essential
information and elude those which are not used on a regular basis. Such information is set in between the fixed
header and upper-layer header and is known as extension headers. Each extension header has some value and is
assigned a task.
IPv6 Addressing Modes
IPv6 offers many addressing modes that are the same as defined in IPv4 and a new mode i.e. anycast
addressing mode is introduced.
IPv6 has three types of addresses, which can be categorized by type and scope:
 Unicast addresses: a packet is delivered to one interface.
 Multicast addresses: a packet is delivered to multiple interfaces.
 Anycast addresses:a packet is delivered to the nearest of multiple interfaces (in terms of routing distance).
3.7.2. IP address assignment
1. Static IP assignment
The manual configuration of a host in a network, allows to assign the static IP address and the following information
has to be specified:
● IP address - identifies the computer on the network
● Subnet mask - is used to identify the network on which the computer is connected
● Default gateway - identifies the device that the computer uses to access the Internet or another network
● Optional values - such as the preferred Domain Name System (DNS) server address and the alternate DNS
server address
Note that host on the same network should have the same Network ID
- 55 -
Steps of Static IP assignment
Step 1: right-click on the start button, then go to network connections.
Step 2: right-click on the network connection your computer is currently using, then select properties.
Step 3: select internet protocol version 4 (ipv4) from the list, then click the properties button
Step 4: select the use the following ip address option.
Note: when assigning a static ip address, make sure to set a value that will not conflict with others on your network.
You may refer to your router documentation for the range of ip address that it assigns to its devices.
Step 5: next to the ip address field, enter the ip address value you want to assign on the computer.
Note: if the dhcp range of your router is from let’s say, [Link]-200, you can use any range from [Link]-
99 for example.
Step 6: in the subnet mask field, enter “[Link].”
Step 7: in the default gateway field, enter the ip address of your router or gateway device.
Note: usually, the default gateway address for most routers is [Link]. Again, you may refer to your device
documentation to determine the correct ip address of your router.
Step 8: for the preferred dns server and alternate dns server fields, you can take a look for the exact dns values that
your router is getting from your isp, which can be usually found by accessing your router’s configuration page.
Step 9: click ok on all windows to save your changes.
2. Dynamic IP configuration

A DHCP (Dynamic Host Configuration Protocol) server automatically assigns IP address to host. It simplifies the
addressing process. DHCP server can automatically assign to a host an IP addres, Subnet mask, Default gateway and
Optional values, such as a DNS server address
Steps of assigning a computer IP address using DHCP are the following:
Step 1: Assign a computer IP address using DHCP
Step 2: Select “View network connections”.
Step 3: locate” the network connection” you want to view
Step 4: After locating connection,right click on it and select “properties”.
Step 5: Double-click “Internet Protocol Version (TCP/IPv4)”
Step 5: Double-click “Internet Protocol Version (TCP/IPv4)”
Step 6: Select the followings:
a. Obtain an IP address automatically
b. Obtain DNS server addresses automatically
c. OK
Step 7: Select “OK” and restart your computer
3.7.4 Some common protocols
A protocol is defined a set of rules and procedures that control communication between computers or other network
devices on a network.
A. Internet control message protocol (ICMP)
Internet Control Message Protocol (ICMP) is used by devices on a network to send control and error messages to
computers and servers. There are several different uses for ICMP, such as announcing network errors, announcing
network congestion, and troubleshooting.
B. HTTP(Hypertext Transfer Protocol)
e.g. [Link]
http:stands for hypertext transfer protocol used to connect computer to the server. It provides a standard web
browser to communicate with a server .
C. FTP (File Transfer Protocol)
This protocol allows you to transfer files between two computers on internet.
D. TCP and UDP
Transmission Control Protocol and User Datagram Protocol are most common transport layer both protocols that
manage the communication of multiple applications. The difference between the two are the specification function
- 56 -
that each protocol implements.
 SMTP (Simple mail Transfer protocol)
The SMTP stands for Simple mail Transfer protocol is a TCP/IP used in sending and receiving e- mails. However,
since it is limited in its ability to queue message at the receiving end, it is used with one of two other protocols POP
or IMAP that let users to save messages in server mailbox and download them from the server once needed.
 POP (Post Office Protocol)
Post Office Protocol is a protocol designed to allow single user computer to retrieve electronic mail from a POP
server via TCP/IP.
3.7.5 Commands used to verify computer connection on a network
[Link] Ping
The command Ping is commonly used to test connections between computers. Ping is a simple but highly useful
command-line utility used to determine whether a specific IP address is accessible.
e.g: ping [Link]
[Link] ipconfig
The ipconfig command is used to find out your current local IP address, default gateway, TCP/IP settings and more.
All Ipconfig commands explained include:
1. ipconfig/all: it displays all current IP information for all adapters.
2. ipconfig /release: Used to release current IP information and obtain a new IP Address from the DHCP server.
3. ipconfig /renew: it is used to renew IP Address if you have it set to obtain IP Address automatically.
3.7.6. IP packet
A network packet is a formatted unit of data carried by a packet-switched network. A packet consists of control
information(head) and user data, which is also known as the payload.
A packet normaly represents the smallest amount of data that can traverse over a network at a single time.
Most network data transmission technologies use packets to transmit data from a source device to a destination
device IP packets are the most important and fundamental components of the protocol. They are structures that
carry data during transmission.
a) Header
The header of IP packets has the following fields:
 The identification tag is used to help reassemble the packet from several eventual fragments. When data is sent
over a network, it is broken down into small sections which are enveloped in these packets. IP networks, such as the
internet, are normally not secure, so packets can be lost, can be delayed, and can arrive in the wrong order. Once
they arrive at the destination, the identification tag helps to identify the packet and to reassemble the data back to its
original form.
 The fragmented flag states whether the packet can be fragmented or not.
 The fragment offset is a field to identify which fragment this packet is attached to.
 Time to Live (TTL) is a number that indicates how many hops (router passes) the packet can make before it dies.
Normally, at each router, a packet is analyzed and based on the information present at that router on other
neighboring routers, a choice is made as to which route is best. The packet is then forwarded to that next router. In
this configuration, a packet may well go round. There is also flooding as another method, which implies sending a
copy of the packet to each neighboring router; then only the target machine consumes the packet. Other packets will
keep roaming. TTL is a number, normally 255, which decreases each time a packet passes a router. This way,
redundant packets will ultimately die once the TTL reaches zero.
 The header checksum is a number used for error detection and correction during packet transmission. The data in
the packet is fed into a mathematical algorithm that results in a sum, which is sent along with the data in the packet.
Upon reception, this sum is calculated again using the same algorithm. If it is the same as the original sum, the data
is good, else it is considered corrupt and the packet discarded.

- 57 -
b) Payload
The payload is the actual data being carried. Notice that data payload can be up to 64 KiloBytes, which is huge
compared to the totality of the header bits.
c) Trailer(footer)
Refers to supplementary data(metadata) placed placed at the end of a block of data being stored or transmitted.
It contains information concerning the destination of a packet being sent over network so for instance in the case of
emails,the destination of the email is contained in the trailer.

3.8. Data and device sharing


3.8.1 Workgroup
A workgroup is a collection of computers and servers on a LAN that are designed to communicate and exchange data
with one another. Each individual workstation controls its user accounts, security information, and access to data
and resources.
Application1: Create a WorkGroup
Step 1: Open the Start menu, do a search for HomeGroup and press Enter.
Step 2: Click Create a HomeGroup.
Step 3: Click Next.
Step 4: Choose what to share on the network. By default Windows sets Pictures, Videos,Music, and Printers &
Devices as Shared.
However, the Documents folder is marked as not shared.
Note: The sharing options you choose will only apply to devices connecting with different accounts. If you sign-in
with the same user account on another computer, you will have access to all files regardless of what you choose to
share.
Step 5: Once you've decided what content to share, click Next.
Step 6: The wizard will complete the setup, and you'll be presented with a HomeGroup password, which is needed to
allow other computers to access files and printers. Write down or click the link to print the password.
Step 7: Click Finish to complete the task
Application 2: How to add computers to a HomeGroup
Step 1: Open the Start menu, do a search for HomeGroup and press Enter.
Step 2: Click the Join now button.
Note: If you don't see the Join now button, there is something wrong, make sure you're connected to the network and
restart your computer.
Step 3: Click Next.
Step 4: Select the content you want to share on the network by using the drop down menu for each folder and click
Next.
Step 5: Enter your HomeGroup password and click Next.
Note: If you're signed into another computer, but you're using your Microsoft Account, then you won't be prompted
to enter a password.
Step 6: Click Finish to complete the task.
3.8.2 Network Resource Sharing
First determine which resources will be shared over the network and the type of permissions users will have to the
resources. Any device which is connected to a host /node is called a Network Peripheral.
In other word network peripheral is any device that is indirectly connected to the network.
Examples of network peripheral are: printer, scanner,storage devices.
Application 3: Add new folders to shared HomeGroup libraries
Step 1: Use the Windows key + E keyboard shortcut to open File Explorer.
Step 2: On the left pane, expand your computer's libraries on HomeGroup.
Step 3: Right-click Documents.
Step 4: Click Properties.
Step 5: Click Add.
- 58 -
Step 6: Select the folder you want to share and click Include folder.
Step 7: Click Apply.
Step 8: Click OK.
Application [Link] new folder via Windows network share to your HomeGroup
Step 1: Right-click the folder you want to share.
Step 2: Select Share with and click the Homegroup (view) option.
Users can access the newly shared folder by:
Step 3: Using the Windows key + E keyboard shortcut to open File Explorer.
Step 4: Clicking Network on the left pane.
Step 5: Double-clicking the computer name with shared content, and browsing the folder location.
By default, every HomeGroup folder shared on the network are set with read only permissions. It has to be this way
to prevent accidental deletions and modification to your files by other users.
3.9. Network Topology
The network topology describes the configuration of network, the physical and logical arrangement of nodes that
form a network. Network topologies are classified as physical, logical and signals topologies.
 Physical topology describes the mapping of network nodes and physical connection between them.
 Signal topology describes the paths which signals take while they pass over network that mapping of the paths
taken by data as they travel over network.
 Logical topology is the way data signals pass from one device to another.
There exist different types of network topologies which are Bus topology, Ring topology, Star topology, Mesh
topology, Tree topology and Hybrid topology.
3.9.1 BUS Topology
Bus topology is a network type in which every computer and network device is connected to single cable.
When it has exactly two endpoints, then it is called Linear Bus topology.
It is the most used and employed in LAN architecture. All devices are connected to a central cable, called the bus or
backbone. This topology is relatively inexpensive and easy to install for small networks.

Advantages and disadvantages of Bus topology


Features of Bus Topology
1. It transmits data only in one direction.
2. Every device is connected to a single cable

- 59 -
Advantages of Bus Topology Disadvantages of Bus Topology
1. It is cost effective. 1. Cables fails then whole network fails.
2. Cable required is least compared to other 2. If network traffic is heavy or nodes are more the
network topology. performance of
3. Used in small networks. the network decreases.
4. It is easy to understand. 3. Cable has a limited length.
5. Easy to expand joining two cables together. 4. It is slower than the ring topology.
3.9.2 RING Topology
It is called ring topology because it forms a ring as each computer is connected to another computer, with the last one
connected to the first. Exactly two neighbors for each device. In a Ring topology each device is connected directly to
two other devices, one on either side of it, to form a closed loop. This topology is relatively expensive and difficult
to install, but it offers high bandwidth and can span large distances

A ring topology is a computer network configuration in which computer connections create a circular data path. Each
networked computer is connected to two others like points on a circle.
. Advantages and disadvantages of Ring topology
Disadvantages Advantages
1. Troubleshooting is difficult in ring topology. 1. Transmitting network is not affectewd by
2. Adding or removing the computers disturbs the high traffic or by adding more nodes.
network activity. 2. Cheap to install and expand
3. Failure of one computer disturbs the whole network.

3.9.3 STAR Topology


In this type of topology all the computers are connected to a single hub or a switch through a cable. This hub or switch
acts as the central device and all others nodes are connected to the central device.

So, in a Star topology all devices are connected directly to a central computer or server. Such networks are relatively
easy to install and manage.

- 60 -
Features of Star Topology
1. Every node has its own dedicated connection to the hub.
2. Hub acts as a repeater for data flow.
3. Can be used with twisted pair or coaxial cable.
Advantages and disadvantages of Star topology

Advantages of Star Topology Disadvantages of Star Topology


[Link] performance with few nodes and low 1. Cost of installation is high.
network traffic. 2. Expensive to use.
[Link] can be upgraded easily. 3. If the hub fails then the whole network is stopped
[Link] to troubleshoot. because all the nodes depend on the hub.
[Link] to setup and modify 4. Performance is based on the hub that is it depends
[Link] that node is affected which has on its capacity
failed, rest of the nodes can work
smoothly.

3.9.4 MESH Topology


● It is a point-to-point connection to other nodes or devices. All the network nodes are connected to each other. A
Mesh topology can be either a full mesh or a partial mesh. In the former, each computer is connected directly to
each of the others.

Types of Mesh Topology


i. Partial Mesh Topology: In this topology some of the systems are connected in the same fashion as mesh
topology but some devices are only connected to two or three devices.

[Link] Mesh Topology: all devices are connected to each other which is very expensive but provides the best
redundancy as a failure of a single does not affect the network connectivity.

- 61 -
Features of Mesh Topology
1. Fully connected.
2. Robust.
3. Not flexible.

Advantages and disadvantages of Mesh topology

Advantages of Mesh Topology Disadvantages of Mesh Topology


1. Each connection can carry its own data load. [Link] and configuration is difficult.
2. It is robust. [Link] cost is more.
3. Fault is diagnosed easily. [Link] wiring is required
4. Provides security and privacy.

3.9.5 Tree Topology


It has a root node and all other nodes are connected to it forming a hierarchy. It is also called hierarchical topology.
It should at least have three levels of hierarchy.

Picture : Tree Topology


Features of Tree Topology
1. Ideal if workstations are located in groups.
2. Used in Wide Area Network
Advantages and disadvantages of Tree topology

Advantages of Tree Topology Disadvantages of Tree Topology


1. Extension of bus and star topologies. 1. Heavily cabled.
2. Expansion of nodes is possible and easy. 2. Costly.
3. Easily managed and maintained. 3. If more nodes are added maintenance is difficult.
4. Error detection is easily done. 4. Central hub fails, network fails.

3.9.6 Hybrid Topology


This is a type of topology that integrates two or more different topologies to form a resultant topology which has good
points (as well as weaknesses) of all the constituent basic topologies rather than having characteristics of one specific
topology.
- 62 -
For example, if there exists a ring topology in one office department while there is a bus topology in another
department, connecting these two will result in hybrid topology. However, connecting two similar topologies cannot
be termed as Hybrid topology.

Advantages and disadvantages of Hybrid topology

Advantages of hybrid Topology Disadvantages of hybrid Topology

1. Reliable: Unlike other networks, fault detection 1. Complexity of Design: One of the biggest
and troubleshooting is easy in this type of drawbacks of hybrid topology is its design.
topology. 2. Costly Infrastructure: As hybrid
2. Scalable: It’s easy to increase the size of architectures are usually larger in scale,
network by adding new components, without they require a lot of cables; cooling
disturbing existing architecture. systems, sophisticate network devices, etc.
3. Flexible: Hybrid Network can be designed
according to the requirements of the organization
and by optimizing the available resources.
4. Effective: Hybrid topology is the combination of
two or more topologies, so we can design it in
such a way that strengths of constituent
topologies are
maximized while there weaknesses are neutralized.
Notice that the cost of technology, network devices, and transmission mediums to be used in the computer network
has to be considered while choosing the network topology to use.

- 63 -
UNIT4. INTRODUCTION TO DATABASE
4.1. Definitions of key terms
i. Data
Data is commonly referred to as ‘raw’ data – a collection of text, numbers and symbols, images with no
meaning. Data therefore has to be processed, or provided with a context, before it can have meaning.
ii. Information
Information is the result of processing data, usually by computer. This results in facts, which enables the
processed data to be used in context and have meaning. Information is data that has meaning.
iii. Database
Database is an organized collection of related data. It is considered to be organized because the data is
stored in categories that are accessible in a logical manner.
A database is a collection of one or more relations, where each relation is a table made of rows and
columns.
Note: An information system is a combination of computer hardware and software that is designed to create,
store, process and present information. The heart of all information systems is a database.
In general data management consists of following tasks:
Data capture, Data classification, Data storage, Data arranging, Data retrieval, Data maintenance, Data
verification, Data coding, Data editing, Data transcription, Data transmission.
4.2. Different area where database can be applied
Databases touch all aspects of our lives such as:
1. Human resources: to track information about employees
2. Banking: to keep customer information, accounts, and loans, and banking transactions.
3. Airlines: to keep for reservations and schedule information. Airlines were among the first to use
databases in a geographically distributed manner
4. Universities: to keep student information, course registrations, and grades.
5. Credit card transactions: to keep purchases on credit cards and generation of monthly statements.
6. Telecommunication: to keep records of calls made, generating monthly bills, maintaining balances on
prepaid calling cards, and storing information about the communication networks.
7. Finance: to keep storing information about holdings, sales, and purchases of financial instruments such
as stocks and bonds.
8. Manufacturing: to keep management of supply chain and for tracking production of items in factories,
inventories of items in warehouses / stores, and orders for items. etc.
4.3. Database approaches
4.3.1 Traditional File Processing Systems (TFPS) approach
This is an approach which was used earlier, prior to DBMS. With this approach, users had to write their
application programs to store data in form of files on the computer permanent storage device (Hard Disk). A
user must have knowledge of programming languages but this is not easy for a common computer user, even
an experienced programmer would find it difficult to write a program each time a new database was to be
createdAdvantages of the Traditional File Processing.
Compared to manual management of information, the Traditional File Processing presents the following
advantages:
● Simplicity: the design of file processing is more simple than designing Database
- 61 -
● Efficiency: file processing cost less and can be more speed than Database
● Customization: you can customize file processing more easily and efficiently than Database because
files are related with the application and it have all the data needed for that application.
Disadvantages of Traditional File Processing System
o Separation and Isolation of Data: In file-based approach, data is stored in separate files, hence it is
difficult to access it.
o Duplication of Data: Duplication of data means same data being stored more than once. This can also be
termed as data redundancy.
o Misuse of storage space: Duplication of data leads to misuse of storage space. If the storage space is not
properly it will have a direct impact on cost. The cost will increase.
o Loss of data integrity: Data integrity means that the data contained in the database is both accurate and
consistent (Data inconsistency means different copies of the same data will have different values).
o Data Dependence: In traditional file processing, the structure of data files is embedded in the application
programs, so any changes to the structure of a file may require changing all programs that access this file.
o Security problems: File based approach is not secured because different files are stored in different
locations.

4.3.2 Database Management System (DBMS)


Database Management system (DBMS) is referred to as a software system that is used to store, access,
manage, organize, maintain, modify and delete data from databases. Some of the most popular software
include, Microsoft Access, Oracle, Microsoft SQL Server, MySQL
MySQL is, one of the most popular database management systems used when there is a need to have access
to information online.

Figure : DBMS approach


[Link] advantages of database management system
There are many advantages of database management system.
1. Reduce data redundancy: Data redundancy refers to the duplication or repetition of data. The database
system is used to eliminate the problems of data redundancy and data inconsistency.
2. Data integration: Data integrity means that the data contained in the database is both accurate and
consistent(valid).
3. Data Independence: Data independence means that if data is changed at a level,it does not impact the
data view at the high levels.
4. Reduce data inconsistency: Actually, data redundancy and data inconsistency are inter- related. If data
redundancy is controlled, then data inconsistency will also be controlled automatically.
Data inconsistency means different copies of the same data will have different values.
5. Data sharing: Due to the fact that data is centralized, many different users from different locations can
share data.
- 62 -
6. Data recovery after a crash (a break down): DBMS allows to recover data after a crash. The crash may
depend on power failure or hardware failure.
7. Concurrent transaction control: A transaction means a collection of operations that perform a single
action in a database.
8. Increased Data security and safety: DBMS allows data to be highly protected against unauthorized
access.

b. Disadvantages of DBMS
The disadvantages of the database approach are summarized as follows
1. Complexity: The provision of the functionality that is expected of a good DBMS makes the DBMS an
extremely complex piece of software. Database designers, developers, database administrators and end-
users must understand this functionality to take full advantage of it.
Failure to understand the system can lead to bad design decisions, which can have serious consequences for
an organization.
2. Size: The complexity and breadth of functionality makes the DBMS an extremely large piece of software,
occupying many megabytes of disk space and requiring substantial amounts of memory to run efficiently.
3. Performance: Typically, a File Based system is written for a specific application, such as invoicing. As a
result, performance is generally very good.
However, the DBMS is written for general purpose, to cater for many applications rather than just one. The
effect is that some applications may not run as fast as they used to.
4. Higher impact of a failure: The centralization of resources increases the vulnerability of the system.
Since all users and applications rely on the availability of the DBMS, the failure of any component can
bring operations to a halt.
5. Cost of DBMS: The cost of DBMS varies significantly, depending on the environment and functionality
provided. There is also the regular maintenance costs.
6. Additional Hardware costs: The disk storage requirements for the DBMS and the database may
necessitate the purchase of additional storage space.
Furthermore, to achieve the required performance it may be necessary to purchase a specicalised computer
(server), dedicated to running the DBMS. The procurement of additional hardware results in further
expenditure.
7. Cost of Conversion:This cost also includes the cost of training staff to use these new systems and
possibly the employment of specialist staff to help with conversion and running of the system.
This cost is one of the main reasons why some organizations feel tied to their current systems and cannot
switch to modern database technology.
Notice:In general,data management consists of the following tasks:
 Data capture:which is a task associated with gathering the data.
 Data classification: captured data has to be classified based on the nature and intended usage.
 Data storage: the segregated data has to be stored [Link] mode of storing will depend on the type
of [Link] storing may be on a piece of paper or in a ledger,register etc.
 Data arranging:it is very important to arrange the data properly for example:arranging the purchase
orders according to order number or date,for easy retrieval of data.
 Data retrieval:data will be required frequently for further processing,hence it is very important to
createsome indexes so that data can be retrieved easily.
 Data maintenance:maintenance is the task concerned with keeping the data up-to-date.
 Data verification:before storing the data,it must be verified for any error.
 Data coding:data will be coded for easy reference,coding also help in reducing amount of storage.
 Data editing:editing means re-arranging the data or modifying the data for presentation.
 Data transcription:this is the activity where the data is converted from one form into [Link]
- 63 -
process involves the change of medium.
 Data transmission:this is a function where data is forwarded to the place where it would be used
further.
4.4 Database access levels and users
4.4.1. Database access levels
A major purpose of a database system is to provide users with an abstract view of the data. That is, the
system hides certain details of how the data are stored and maintained. There are three- levels that form the
basis of modern database architectures:
a) The internal level has an internal schema, which describes the physical storage structure of the database.
The internal schema uses a physical data model and describes the complete details of data storage and access
paths for the database.
b)The conceptual level has a conceptual schema, which describes the structure of the whole database for a
community of users.
The conceptual schema hides the details of physical storage structures and concentrates on describing
entities, data types, relationships, user operations, and constraints.
c) The external or view level: The external view level is closest to the users. It is concerned with the way
the data is viewed by individual users. A user can either be an application programmer or an end-user. The
purpose of the three-level architecture is to separate the user application and the physical database.
Different users need different views of the same data.
1. Users should not have to deal directly with the physical database storage details.
2. The database administrator should be able to change the database storage structure or storage device
without affecting other user's views.
4.4.2 Database users
When considering users of a Database system, there are three broad classes to consider:
[Link] administrator (DBA):
Responsible for authorizing access to the database, for coordinating and monitoring its use, acquiring
software and hardware resources, controlling its use and monitoring efficiency of operations.
b. The database designer:
Responsible to define the content, the structure, the constraints, and functions or transactions against the
database. They must communicate with the end-users and understand their needs.
c. The end-user:
End-users, They use the data for queries, reports and some of them update the database content.
4.4.3. Data Independence
Data Independence: The ability to modify a scheme definition in one level without affecting a scheme
definition in a higher level is called data independence.
There are two kinds of data independence:
a. Logical data independence
o The ability to modify the conceptual scheme without causing application programs to be rewritten.
o Immunity of external schemas to changes in the conceptual schema usually done when logical structure of
database is altered.

b. Physical data independence


o The ability to modify the internal scheme without having to change the conceptual or external schemas.
o Modifications at this level are usually to improve performance.

- 64 -
4.4.4. Database models
A data model is a collection of concepts and rules for the description of the structure of the database.
Structure of the database means the data types, the constraints and the relationships for the description or
storage of data respectively.
The most often used data models are:
o Hierarchical model
o Network model
o Relational model
1. Hierarchical Model
The hierarchical model organizes its data using a tree structure. The root of the tree is the parent followed by
child nodes. A child node cannot have more than one parent, though a parent can have many child nodes.

Examples: IMS (Information Management System) by IBM


Advantages
 Easily shows one-to-one & one-to-many relationships
 More efficient than the flat file model b/c less need for redundant data

Disadvantages
No support for many-to-many relationships; user must know how the tree is structured to find anything;
cannot add a record to a child table until it has been incorporated into the parent table; still creates data
duplication
2. Network Model
In the network model, entities are organized in a graph, in which some entities can be accessed through
several paths.

Examples
Satellite communications, airline reservations;
Advantages
 Network model solves problem of data redundancy by representing relationships in terms of sets rather
than hierarchy.
- 65 -
 Allowed complex data structures to be built; very efficient in storage & fast; better job with many-to-many
relationship

Disadvantages
 More difficult to navigate and visualize compared to the hierarchical model.
 Model difficult to implement and maintain.
 Most implementations were used by programmers rather than end- users; had to have an understanding of
how the database was structured in order to retrieve, insert, update or delete records.
 Required a lot of programming to use successfully
3. Relational Model
In this model, data is organized in two-dimensional tables called relations. The tables or relation are related to
each other.
A relational database is a collection of relational tables.
The following is a graphical representation of entities and their relationships in a database structure.

They are hence called relational Database Management Systems (RDBMS).


The database systems in their differences and similarities all serve to manage databases.
Examples
Oracle, DB2, MS Access, SQL Server, MySQL (free),
Advantages
 More easily visualize data organization & relationships ease of design & user-friendly GUI interfaces.
 No duplicate data which reduces errors & improves consistency & eases database maintenance.
 Relationships increase data integrity; more information from same data due to file integration; new &
one-time requests easily accommodated.
 Increased productivity; application code generators; referential integrity controls; transactional integrity
ensures that incomplete transactions do not occur.
 Database users don’t corrupt each other’s work; scalable (can spread load across multiple CPUs or
servers).
 Best for data collection & querying; allows built-in validation; define & store schema (DB structure),
 Load initial data, provide a variety of access methods, add, modify & delete data, provide multiple views
of the data, provide security features, facilitate backup and recovery

Disadvantages
 Initially, had slow performance in 70’s & 80’s, but today’s more powerful machines speed up

- 66 -
performance
 Wide price range, can be expensive
 High impact of failure due to centralization and non-duplication of data.
 Sophisticated design and programming required for some products; additional user training may be
needed due to added system capabilities.
 Backup and recovery are more difficult due to concurrency and complexity; security is more critical and
complicated due to shared usage of central database.

- 67 -
UNIT 5: DATABASE DESIGN
5.0 INTRODUCTION.
Nowadays, well-designed database arises to overcome the risks for information of being lost, damaged,
corrupted and not well organized and saves the time in the long run for the user. The design of such database
presents 3 main levels called “Database design levels”.
Those levels are the following:
* Conceptual level
* Logical level
* Physical level
These levels help to make easy the understanding and the management of a database.
5.1 DATABASE DESIGN LEVELS
5.1.1 The conceptual level
The conceptual level is concerned with concept(abstract), an idea of what something is or how it works;
something formed in the mind; a mental image.
There exist different models used for the conceptual level to represent all the data elements likely to belong to
the database but the most used is the Entity- Relationship Model (ERM). It uses the main concepts like entities,
attributes and relationships.
An entity represents a real-world object such as an employee or a project and has attributes that represent
properties such as EmpId, FirstName, Surname, Address and Birthdate.
For example, when an employee works on many projects, a relationship exists between the employee and
each project.
If an employee is identified by EmpId, FirstName, Surname, Address and Birthdate while a project is identified
by its ProjectId and ProjectName, the diagram representing the Entity Relationship is the following.

Figure : Entity Relationship model having employees and projects as entities


5.1.2 The logical level
The logical level makes it possible to create relational structures enabling us to put into practice the
conceptualization by imagining a relational Database Management System (DBMS).
It is characterized by clear and sound reasoning. At this level there exist different models like network data

models and hierarchical data models and relational model.


5.1.3 Physical level
The physical level is concerned with how data will be encoded and stored. It consists of the practical
application (Database Management Systems - DBMS) of all the preceding theories by using computers
together with its software to create a database. It deals with storage and processing performance, volumetric
(time & space), partitioning and distribution.
The most known development tools to use are MS Access, MySQL (My Structured Query Language), SQL
- 68 -
(Structured Query Language) and NoSQL.

Example: SCHOOLS Database


 A View for registrar office
Course info (coursid:string,enrollment:integer)
 The conceptual schema:
Students(studid: string, name: string, login:string, age: integer, gpa:real) Courses(coursid: string,
ccoursname:string, courcredits:integer) Enrolled(sstudid:string, coursid:string, grade:string)
 The physical schema:
Relations stored as unordered files. Index on first column of Students.
5.2. DATABASE DESIGN STEPS
A well-designed database performs well and adapts to future needs by giving users access to essential
information. Poor planning often results in a database that fails to meet overlooked needs. In planning the
database, regardless of its size and complexity the following basic steps are used:
1. Investigate the information.
2. Identify the objects.
3. Model the objects.
4. Identify the types of information for each object.
5. Identify the relationships between objects.
6. Database optimization through normalization.
7. Data entry and manipulation.
5.2.1. Investigate information.
During investing information, there is a need to work with everyone involved in the existing system to see what
is needed from the new database. Gathering techniques include collect copies of customer information,
management reports, and any other documents that are part of the existing system, because these will be useful
in designing the database and the interfaces.
5.2.2. Identifying the important entities and their attributes
During the process of gathering/investigating information, the key objects or entities that will be managed
by the database must be identified.
5.2.3. Identifying the Relationship Between entities
One of the strengths of an E-R database is the ability to relate or associate information about various items in
the database.
Identifying the relationship between entities in the design process requires looking at the entities, determining
how they are logically related, and adding relational columns that establish a link from one table to another.
5.2.4. Modeling the objects
As the objects in the system and their attributes are identified, they are recorded in a way that represents the
system visually.
To record them the database model including Relational model and Entity Relational model
5.2.5. Identifying the types of information for each object
After identifying the primary objects/entities in the database as candidates for tables, the next step is to
identify the types of information that must be stored for each object.
These are the columns in the table of the object.
The columns in a database table contain a few common types of information:
 Raw data columns
These columns store tangible pieces of information, such as names.

- 69 -
 Categorical columns
These columns group the data and store a limited selection of data such as true/false,
married/single/divorced/widowed, Male/Female, etc.
 Identifier columns
These columns provide a mechanism to identify each item stored in the database table. These columns
frequently have an id or number in their name, for example, EmployeeId, StudentId, PersonIdNo and
InvoiceNumber. The identifier column is the primary component.
 Relational or referential columns
These columns establish a link between information in one entity and related information in another entity.
For example, an entity that tracks sales transactions will generally have a link to the customer’s entity so that
the complete customer information can be associated with the sales transaction.
5.2.6. Database optimization through normalization
One of the most important step to consider when designing a database is database [Link] tables are not
setup properly,it can cause a lot of headaches down the road the time of extracting/retrieving required data.
Understanding the rules of normalization enforces redundancy elimination and inconsistent dependency in
database designs.
5.2.7. Data entry and manipulation
The goal of data entry is to create data that are valid and well organized to assure their quality during
[Link] stored data leads to data consistency.
5.3. RELATIONAL MODEL
5.3.1. Introduction
The relational data model was introduced by C. F. Codd in 1970. Currently, it is the most widely used data
model.
The relational data model describes the world as “a collection of inter-related relations (or tables).”
 Relation
A relation, also known as a table or file, is a subset of the Cartesian product of a list of domains characterized
by a name. You can also think of it this way: an attribute is used to define the record and a record contains a set
of attributes.
The following are the key component to know when we are talking about relation: Relation, Tuple, Attribute,
Cardinality, Degree, Primary key, Domain…
Equivalent Database Concepts
• Relation <=> Table
• Tuple <=> Row or record
• Attribute <=> Column or field
• Cardinality <=> Number of rows
• Degree <=> Number of columns
• Primary key <=> Unique identifier
• Domain <=> Pool of legal values(all values which a data element may contain)
 Table
Data is stored in rows and columns. Each Row is known as record and the data items are known as fields.
Tables contain data about one type of item, person or event, for example:
a table of patients
a table of a student
a table of teacher
a table of books
a table of doctor’s appointment
For a book the fields could include:
 title
 author
 ISBN
- 70 -
 Publication house
 Column
A database stores pieces of information or facts in an organized way. The principal storage units are called
columns or fields or attributes. These house the basic components of data into which your content can be
broken down.
 Records
Each row represents a group of related data values, such as a customer or an employee. A row, or record, is
also known as a tuple
 Cell
The link/intersection between column and record is known as cell.
It also needs to be available so that they can be reconstituted into their whole form, the basis of all databases.
A simple table below gives us the clearest picture of how records and fields work together in a database
storage project.
Columns/Fields/Attributes

RegNo FirstName LastName Combinations


1 Bruce MIGAMBI PCB
2 Rehema UWIMANA MCE
3 Carine UWIMPUHWE HEG Rows/Tuples/Recor
4 Kevin MUGABO MCE ds
5 Diane BEZA MCB
6 Patrick MIZERO MCB

Attribute Cells/Values

 Null value
In many situations every row and column will contain data, but there cases where it makes sense for some
columns to not contain a value.
In our example StudentId cannot be null because it is unique but Sex can be null because it is optional field
 Degree
The degree is the number of attributes in a table. In our example above the degree is 4.
 Domain
A domain is the original sets of atomic values used to model data. A domain is a set of acceptable values that
a column is allowed to contain.
For example:
• The domain of Marital Status has a set of possibilities: Married, Single, Divorced, Widowed.
• The domain of Shift has the set of all possible days: {Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday and Sunday}.
• The domain of Salary is the set of all floating-point numbers greater than 0 and less than 200,000 FRW.
• The domain of First Name and Surname is the set of character strings that represents names of people.

 Datatype
Each field in a record has its own data type. The data types in the fields can be text, alphanumeric, numeric,
and Boolean or date/time.
Examples:
 StudentId can be Numeric or alphanumeric of any size:it is numeric because it can be sorted on numerical
order or alphanumeric because it can not be used for calculation(e.g:S12019)
 FullName can be character(text) of any size
 Sex can be Boolean because it has only two choices(M or F)

- 71 -
5.3.2 Queries in design view
Data in a Microsoft Access database is stored in various interlinked tables. A database also has forms for data
entry though you could enter data directly in tables and queries for manipulating your data and permitting
information to be retrieved from a table.
It also allows filtering so only the required records and fields are seen.
Querry is a request for data or information from a database tables or a combination of tables.
Steps for creating database in Microsoft Access
 Open Microsoft Access
 Click on Blank database in the task pane
 Name your database file (Eg; Company) and click the Create button to create the database.
Steps for creating a table in Microsoft Access-Design View
 Open an created database in access DBMS
 Click on create tab from menu bar
 In table group click on table design icon
 Fill field names, data type and their descriptions
Data in an Access table is stored in various fields. Those fields have different properties such as fieldname,
size and data types.
Steps for creating relationship between created tables
 Open a created database in access DBMS
 Click on database tools tab from menu bar
 In relationships group click on relationships icon then the relationships panel will be displayed
 Select a table name and click on add button
 Repeat step 4 to all table you want to use
 Click on design tab from menu bar
 In tools panel click on edit relationship icon
 On opened window click on create new button
 Select the table names and their columns that you want to join
 Click on ok button
 Repeat 8, 9, and 10 to all pair table to be joined.
After creating a table, enter the data. Note that there are various methods to create tables in Access, such as by
using Table Wizard, Datasheet view or by importing tables, but this Unit restricts only to Design view.

EMPLOYEE
EmpId FullName Designation Salary Doj D Country City
ob
101 KAREKEZI Ange Accountant 240000 3/23/2003 1/13/1980 RWANDA HUYE
102 GANZA Kevin Head-IT 320000 12/2/2010 7/22/1987 UGANDA KAMPALA
103 MUTONI Rehma Customer Care 200000 6/24/2009 2/24/1983 BURUNDI BUJUMBURA
105 NKUSI Anicet Marketting officer 310000 11/8/2006 3/3/1984 BURUNDI BUJUMBURA
108 KARENZI Abdul CEO 560000 12/29/2004 1/19/1982 RWANDA KIGALI

Steps for creating a query using design view-Query by example(QBE)


Query By Example(QBE) in DBMS refers to a method of forming quries in which the database program
displays a blank record with a space for each field.
You can then enter conditions for each field that you want to be included in the query.
Creation of a query in design view has three rows, one to sort the fields, the other to specify whether or not to
display a field, and the last to specify some criteria to select the records.
1. Click on Create tab of menu from bar
2. In queries grout click on query Design icon
3. Select tables to use then click on Add button
4. In Query Type group select a query commend to be used, Example Select
5. In query panel select the table names and field names you want to select in different tables
- 72 -
6. Check in show row ender the select item if you want to display them on output at run time
7. Rename the created query
8. In Result group of menu bar ,click on Run icon
After the above steps you will get a table containing the selected items as shown in the examples below:
Query 1: Company leader wants to display onlyEmpId, Fullname (sorted is ascending order) and salary for
all employees.
 Select EmpId, EmpId, FullName, Salary and check them
 Select Sort by Ascending on FullName

Figure . Query by example Grid displaying salary of all employees Output:


EmpIdEmpId FullName Salary

102 GANZA Kevin 320000


101 KAREKEZI Ange 240000
108 KARENZI Abdul 560000
103 MUTONI Rehma 200000

105 NKUSI Anicet 310000

Table : Output for Salary of all employees


Query2: The CEO wants to see only EmpId and FullNames where Salary is less or equal to 240000.
 Select EmpId, EmpId , FullName and check them
 Set criteria and uncheck Salary field

Figure : Query by example grid displaying EmpId and FullNames where Salary<=240000 Output:
EmpIdEmpId FullName
101 KAREKEZI Ange
103 MUTONI Rehma

Table . Output for QBE displaying EmpId and FullNames where Salary<=240000

Query 3: The following search condition was entered using a query design view (Query by example) grid:

- 73 -
Figure. QBE grid displaying FullName and Doj where Doj>=11/8/2006 What will be displayed?
Output:
FullName Doj
GANZA Kevin 12/2/2010
MUTONI Rehma 6/24/2009
5.3.3 . Dynamic queries using parameter
A parameter is a piece of information you supply to a query right as you run it.
Create a parameter query
Creating a parameter is similar to adding a normal criterion to a query:
1. Create a select query, and then open the query Design view.
2. In the Criteria row of the field you want to apply a parameter to, enter the text that you want to display in
the parameter box, enclosed in square brackets.
For example, [Enter the Doj:]
3. Repeat step 2 for each field you want to add parameters to.
When you run the query, the prompt appears without the square brackets.

Figure . Prompt window for adding value


Fill in the value you’re looking for, and then click OK.
Specify parameter data types
To specify the data type for parameters in a query:
1. With the query open in Design view, on the Design tab, in the Show/Hide group, click Parameters.
2. In the Query Parameters box, in the Parameter column, enter the prompt for each parameter you want to
specify a data type for.
Make sure that each parameter matches the prompt that you used in the Criteria row of the query design grid.
3. In the Data Type column, select the data type for each parameter.

- 74 -
5.4. ENTITY-RELATIONSHIP MODEL
5.4.1. Introduction
ER models are readily translated to relations. ER models, also called an ER schema, are represented by ER
diagrams.
ER modelling is based on two concepts:
• Entities is defined as tables that hold specific information (data)
• Relationships, defined as the associations or interactions between entities
5.4.2. Entity Relationship Diagram
The ER diagram is used to represent the conceptual database schema. In ER diagram:
Entity, Attributes and Relationships form the components of ER Diagram and there are defined symbols and
shapes to represent each one of them.
 Entity
A rectangle represents an entity set.

 Relationships between Entities


A diamond represents a relationship.

 Entity Types
 Entity types ->boxes
 Weak entity type -> double box

EMPLOYEE DEPENDENT
Entity Weak Entity
 Entity types are similar to classes; they describe potential objects (entities) that will appear in the database
 Weak entity types describe dependent entities, entities that depend on other entities for identity.
 Attribute
An ellipse represents an attribute (Property).

 Link between attribute and entity set


Lines represent linking of attributes (properties) to entity sets.

5.4.4. Entities and entity sets


An entity set is a set of entities of the same type that share the same properties. A noun is used to represent an
entity set.
An entity is an instance of an entity set. For example, an entity can be:
1. Concrete (TEACHER or STUDENT)
2. Insubstantial (GRADE)

- 75 -
3. An occurrence (EXAM)
5.4.5. Attributes
A characteristic of an entity, for example First name, Last name and Age. An attribute is a data item that
describes a property of an entity set. Attributes determine, explain, or categorize an entity set. Attributes have
values, which can be of different data types such as numbers, character strings, dates, images, sounds, and so on.
In a physical model, an attribute is a named column in a table. Each table has a list of attributes (or columns).

Figure: How attributes are represented in an ERD.


The types of attributes are:
 Simple (atomic) attribute – This type of attribute has a single component. It is called single- valued
attribute.
For example, the Gender attribute has a single component with two values.
In the COMPANY database, an example of this would be: Name = {John} ; Age = {23}
 Composite attribute – A composite attribute consists of many components.
For example, the Name attribute has the components Last name and First name. So this would be written as
→ Name = {KAGABO+Peter}
Address may consist of Province and District, Number, Avenue. So this would be written as → Address =
{KG +‘14’ + ‘Av’}

Figure . Composite Attribute


 Single valued attribute – This type of attribute has one value for one entity. For example, the Title
attribute has a single value for each teacher.
 Multi-valued attribute – A multi-valued attribute has many values for one entity.
An example of a multivalued attribute from the COMPANY database, as seen in Figure below, are the
degrees of an employee: BSc, MSc., PhD.

- 76 -
Figure. Multi valued attribute
 Derived attribute – A derived attribute has its value computed from another attribute or attributes.
A derived attribute is not a part of a table from a database, but is shown for clarity or included for design
purposes even though it adds no semantic information; it also provides clues for application programmers.
An example of this can be seen in Figure below. Age can be derived from the attribute Birthdate In this
situation, Birthdate is called a stored attribute, which is physically saved to the database.

Figure. Derived attribute


 Unstable attributes - This type of attribute have values that always change.
For example, the salary of employee.
 Mandatory attributes - Mandatory attributes must have a value. For example, in most businesses that track
personal information, Name is required.
 Optional attributes - Optional attributes may have a value or be left null; For example, address of
employee
 Unique identifier - This type of attribute distinguishes one entity from another.
For example, in a company, you can distinguish between one employee and another using a EmployeeID.
5.4.6. Keys
key is an attribute or a group of attributes whose values can be used to uniquely identify an individual entity
in an entity set.
A key is a field or a set of fields that has/have a unique value for each record in the relation. You need a key
to ensure that you do not meet redundancies within a relation.
There are several types of keys each having slightly different characteristics:
 Super key-is defined as a set of attributes within a table that can uniquely identify each record within a
table. Super Key is a superset of Candidate key.
 Candidate key – A candidate key is an attribute or set of attributes that uniquely identifies a record in a
relation.
A candidate key is unique and minimal.
It is unique because no two rows in a table may have the same value at any time. It is minimal because every
- 77 -
column is necessary in order to attain uniqueness.
From our Company database example, if the entity is Employee(SerialNo,EmpId, First Name, Surname,
Address, Contact, Birthdate, Salary, Depid), possible candidate keys are:
• EmpId,
•SerialNo
• FirstName and Surname – assuming there is no one else in the company with the same full name
• Surname and Depid – assuming two people with the same Surname don’t work in the same Department
 Composite keys – these keys have multiple attributes.
Using the example from the candidate key section, possible composite keys are:
• First Name and Surname
• Surname and Depid
 Primary key – A primary key is one of the candidate keys from a relation. Every relation must have a
primary key.
A primary key shall be at least:
 Stable: The value of a primary key must not change or become null throughout the life of the entity.
The primary key is indicated in the ER model by underlining the attribute.
For example, consider an employee record; using the Age field as the primary key would not be appropriate
because the value of the primary key must not change over time.
 Minimal:The primary key should be composed of the minimum number of fields to ensure the
occurrences are unique.
In this case Employee (EmpId, First Name, Surname, Address, Contact, Birthdate, Salary, Depid),
EmpId is primary key
 Secondary key
A secondary key is an attribute used strictly for retrieval purposes (can be composite), for example: Phone and
Surname.
 Alternate key – An alternate key is any candidate key that is not chosen to be the primary key. It may
become the primary key if the selected primary key is not appropriate.
 Simple keys – these keys have a single attribute.
Foreign keys – these keys exist usually when there are two or more relations. An attribute from one relation
has to exist in the other(s) relation. A foreign key is a field (or fields) that points to the primary key of another
table. The purpose of the foreign key is to ensure referential integrity of the data. In other words, only values
that are supposed to appear in the database are permitted In the Company database example below, Depid is
the foreign key (EmpId, First Name, Surname, Address, Contact, Birthdate, Salary, Depid)
Notes:Attributes and Keys
 Key attributes must be unique for each entity
 Keys are used to identify particular entities
 Partial keys are only partially unique used for weak entity types

Age SSN Date


Attribute Key Attribute Partial Key Attribute
NOTICE: Nulls
A null is a special symbol,independent of data type,which means either unknown or [Link] does not
mean zero or blank.
The features of null include:
No data entry
Not permitted in the primary key.
Should be avoided in other attributes
It can represent:
 An unknown attribute value
 A known but missing attribute value
 A not applicable condition.

- 78 -
5.4.7. Degree of a relationship
The degree of a relationship refers to the number of associated entities. The degree of a relationship can broadly
be classified into unary, binary, and ternary relationship.
 Unary Relationship
The unary relationship is known as recursive relationship.
In the unary relationship the number of associated entities is one. An entity is related to itself is known as
recursive relation.
An example is shown by the following figure:

Figure. Recursive relation


Roles and Recursive Relations
When an entity set appears in more than one relationship, it is useful to add labels to the connecting lines. These
labels are called roles.
In this example, labels “Husband” and “wife” are referred to as roles.

Husband Wife

Figure. Wife-Husband relationships


[Link] Binary Relationship
In a binary relationship, two entities are involved. Consider the example where each staff will be assigned to a
particular department. Here the two entities are STAFF and DEPARTMENT.

[Link]. Ternary Relationship


In a ternary relationship, three entities are simultaneously involved. Ternary relationships are required when
binary relationships are not sufficient to accurately describe the semantics of an association among three
entities.

- 79 -
Example
Consider the example of employee assigned a project.
Here we are considering three entities EMPLOYEE, PROJECT, and LOCATION. The relationship is
“assigned-to.” Many employees will be assigned to one project hence it is an example of one-to-many
relationship.
[Link]. Quaternary Relationships
Quaternary relationships involve four entities. The example of quaternary relationship is “A professor teaches
a course to students using slides.” Here the four entities are PROFESSOR, SLIDES, COURSE, and
STUDENT.
The relationships between the entities are “Teaches.”

Figure. slides-professor-student-course relationship


The degree of relationship, which determines how many instances of an entity relate to a single instance of
another entity is called Cardinality.
5.4.8. Classifications or types of Relationships
Based on cardinality, the different types of relationships that can exist between entities are:
[Link]. One-to one (1:1)
A single instance of an entity can relate to only one instance of the other [Link] is the relationship of one entity
to only one other entity, and vice versa. It should be rare in any relational database design. In fact, it could
indicate that two entities actually belong in the same table.
An example from our Company database is one employee is associated with one spouse, and one spouse is
associated with one employee.
Other Examples:
1. A person can have only one passport.
2. The relationship between the President and the country is an example of one-to-one relationship. For a
particular country at a given time, there will be only one President. In general, a country will not have more
than one President at a given time hence the relationship between the country and the President is an example
of one-to-one relationship.
3. Another example of one-to-one relationship is House to Location. A house is obviously in only one
location.
[Link]. One-to-many (1: M)
An instance of one entity can relate to multiple instance of another instance.
The relationship that associates one record of entity A to more than one record of entity B is called one-to-many
relationship.
Example of one-to-many relationship is a country having states.
For one country there can be more than one state hence it is an example of one-to-many relationship. Another
example of one-to-many relationship is parent–child relationship. For one parent there can be more than one
child. Hence it is an example of one-to-many relationship.
For Example,
 A class has many students.
 The relationship between EMPLOYEE and DEPARTMENT is an example of many-to- one relationship.
- 80 -
There may be many EMPLOYEES working in one DEPARTMENT. Hence relationship between EMPLOYEE
and DEPARTMENT is many-to-one relationship.
[Link]. Many-to-One Relationship Type (M: 1)
The relationship between EMPLOYEE and DEPARTMENT is an example of many-to-one relationship.
There may be many EMPLOYEES working in one DEPARTMENT.
Hence relationship between EMPLOYEE and DEPARTMENT is many-to-one relationship

[Link]. Many-to-many (M: M):


Multiple instances of an entity can relate to multiple instances of another entity. For our company database.
The relationship between employee and department is many-to-many relationship.
Other examples are:
 A customer can purchase more than one book.
 The relationship between TEACHER entity and STUDENT entity is an example of many- to-many
relationship. Many one teacher teaches many students and one student is taught by many teachers.
 Employee and project, many employees can work on many projects

5.4.9. Participation and Cardinality


Participation defines the least number of relationship instances in which an entity must compulsory
participate.
Participation can be:
 Total participation : double or thick line indicates required participation
 Partial participation: thin line indicates optional participation

EMPLOYEE WorksFor DEPARTMENT

Total Participation

EMPLOYEE WorksOn PROJECT

Partial- Participation
81 -
Cardinality defines the maximum number of relationship instances in which an entity can participate.
Note:
 Cardinality Ratios: a cardinality ratios specify the maximum number of relationship instances that an
entity may participate in.
1
EMPLOYEE Manages DEPARTMENT

1:1 ratio

n 1
EMPLOYEE WorksFor DEPARTMENT
n:1 ratio
n m
WorksOn PROJECT
EMPLOYE
n:m ratio
Figure : Cardinality Ratios Structural Constraints
 Structural constraints specify the minimum and maximum number of relationship instances that an entity
may participate in.

EMPLOYEE (1,1) WorksFor (4,n) DEPARTMENT

An employee must work for exactly 1 department. A department must have at least 4 employees.
Database optimization through normalization
5.5.1. Introduction
Another method for designing a relational database is to use a process commonly known as normalisation.
The goal is to generate a set of relation schemas that allows us to store information without unnecessary
redundancy, yet also allows us to retrieve information easily.
Normalisation is a series of steps designed to remove repeating groups and unwanted functional
dependencies. Normalisation is a design technique for constructing a set of table designs from a list of data
items. It is also used to avoid insertion, deletion and updating anomalies.
5.5.2. Normal Forms
Normalization theory defines six normal forms (NF). Each normal form involves a set of dependency
properties that a schema must satisfy and each normal form gives guarantees about the presence and/or
absence of update anomalies. To correct update anomalies in a database, you must convert tables to various
types of normal forms.
The most common normal forms are First Normal Form (1NF), Second Normal Form (2NF), Third Normal
Form(3NF) and Fourth Normal Form(4NF).
 First Normal Form

A relation (table) that contains a repeating group (multiple entries for a single record) is called unnormalised
relation. Removing repeating groups is the starting point in the quest to create tables that are as free of problems
as possible.
Rules for First Normal Form
The first normal form expects you to follow a few simple rules while designing your database, and they are:
Rule 1: Single Valued Attributes
Each column of your table should be single valued which means they should not contain multiple values. We will
- 82 -
explain this with help of an example later, let's see the other rules for now.
Rule 2: Attribute Domain should not change
This is more of a "Common Sense" rule. In each column the values stored must be of the same kind or type.
For example: If you have a column DoB to save date of births of a set of people, then you cannot or you must not
save 'names' of some of them in that column along with 'date of birth' of others in that column. It should hold only
'date of birth' for all the records/rows.
Rule 3: Unique name for Attributes/Columns
This rule expects that each column in a table should have a unique name. This is to avoid confusion at the time of
retrieving data or performing any other operation on the stored data.
If one or more columns have same name, then the DBMS system will be left confused.
Rule 4: Order doesn't matters
This rule says that the order in which you store the data in your table doesn't matter.

The conversion to first normal form (lNF) requires splitting the data into two groups. Tables without
repeating group are said to be in 1NF.
A relation is in first normal form if and only if the domain of each attribute contains only atomic (indivisible)
values, and the value of each attribute contains only a single value from that domain
Example1:
A database has been designed to store data about sellers and the products they have sold. The following facts
help to define the structure of the database:
 each seller works in a particular shop
 each seller has a unique Surname
 each shop has one or more sellers
 each product which is sold is manufactured by one company only
 each seller can sell any of the products
 the number of products that each seller has sold is recorded
Table: SHOPSALES
SurName ShopName ProductName NumberofProducts Manufacturer
KAGABO CompuTech Ltd Digital Camera 3 Nikon
Printer 2 Canon
Laptop 6 HP
KALISA DigiTech Hair dryer 1 Panasonic
Electric shaver 8 Phillips
KAMALI CompuTech Ltd Digital Camera 2 Nikon
Printer 8 Canon

Modem 4 Huawei
Mobile Phone 3 Samsung 3
The table above is not in 1NF because:
1. SHOPSALES table has repeated group of attributes (ProductName, Manufacturer)
(ProductName, NumberofProducts), (NumberofProducts, Manufacturer)
2. each seller has a number of products
3. SurName and ShopName would need to be repeated for each record The following table is in 1NF because
it does not contain repeating groups Table: SHOPSALES
SurName ShopName ProductName NumberofProducts Manufacturer

- 83 -
KAGABO CompuTech Ltd Digital Camera 3 Nikon
KAGABO CompuTech Ltd Printer 2 Canon
KAGABO CompuTech Ltd Laptop 6 HP
KALISA DigiTech Hair dryer 1 Panasonic
KALISA DigiTech Electric shaver 8 Phillips
KAMALI CompuTech Ltd Digital Camera 2 Nikon
KAMALI CompuTech Ltd Printer 8 Canon
KAMALI CompuTech Ltd Modem 4 Huawei
KAMALI CompuTech Ltd Mobile Phone 3 Samsung
Example2:
Here is our table, with some sample data added to it.

roll_no name subject


101 Akon OS, CN
103 Ckon Java
102 Bkon C, C++

Our table already satisfies 3 rules out of the 4 rules, as all our column names are unique, we have stored data
in the order we wanted to and we have not inter-mixed different type of data in columns.
How to solve this Problem?
It's very simple, because all we have to do is break the values into atomic values.

roll_no name subject


101 Akon OS
101 Akon CN
103 Ckon Java
102 Bkon C
102 Bkon C++

By doing so, although a few values are getting repeated but values for the subject column are now atomic for
each record/row.
Using the First Normal Form, data redundancy increases, as there will be many columns with same data in
multiple rows but each row as a whole will be unique.

- 84 -
 Second Normal Form (2NF)
For the second normal form, the relation must first be in 1NF. The relation is automatically in 2NF if, and only
if, the Primary Key comprises a single attribute.
To move to 2NF, a table must first be in 1NF. The database is changed to the following design: SELLER
(SurName, ShopName)
PRODUCTSSOLD (SurName, ProductName, NumberofProducts, Manufacturer)

Table: SELLERS
SurName ShopName
KAGABO CompuTech Ltd
KALISA DigiTech
KAMALI CompuTech Ltd
Table: PRODUCTS SOLD
SurName ProductName NumberofProducts Manufacturer
KAGABO Digital Camera 3 Nikon
KAGABO Printer 2 Canon
KAGABO Laptop 6 HP
KALISA Hair dryer 1 Panasonic
KALISA Electric shaver 8 Phillips
KAMALI Digital Camera 2 Nikon
KAMALI Printer 8 Canon
KAMALI Modem 4 Huawei

KAMALI Mobile Phone 3 Samsung

Table SELLER is in Second Normal Form because attribute ShopName depends on primary key SurName;
the same on PRODUCTSSOLD where NumberofProducts and Manufacture attributes depends on composite
primary key SurName, ProductName
The link between these two tables is: primary key of SELLER table is FirstName, links to FirstName in
PRODUCTSSOLD table, FirstName in SalesProducts table is foreign key
 Third Normal Form (3NF)
To be in third normal form, the relation must be in second normal form. Also all transitive dependencies must
be removed; a non-key attribute may not be functionally dependent on another non-key attribute.
In our case on table PRODUCTSSOLD, Manufacturer attribute is dependent on ProductName, which is not
the primary key of the PRODUCTSSOLD table therefore there is no key dependency.
Process for 3NF:
1. Eliminate all dependent attributes in transitive relationship(s) from each of the tables that have transitive
relationship.
2. Create new table(s) with removed dependency.
3. Check new table(s) and modified table(s) to make sure that each table does not contain inappropriate
dependencies.
- 85 -
See the three new tables below. SELLERS (SurName, Shop)
PRODUCTSSOLD (SurName, ProductName, NumberofProducts)
PRODUCTS (ProductName, Manufacturer)
Table: Sellers

SurName ShopName
KAGABO ComputeTech Ltd
KALISA DigiTech
KAMALI CompuTech

Table: ProductsSoldM1
SurName ProductName Manufacturer
KAGABO Digital Camera Nikon

KAGABO Printer Canon


KAGABO Laptop HP
KALISA Hair dryer Panasonic
KALISA Electric shaver Phillips
KAMALI Digital Camera Nikon
KAMALI Printer Canon
KAMALI Modem Huawei
KAMALI Mobile Phone Samsung

Table: PRODUCTS
ProductName Manufacturer
Digital Camera Nikon
Printer Canon
Laptop HP
Hair Dryer Panasonic
Electric shaver Phillips
Modem Huawei
Mobile Phone Samsung

Note:Boyce-Codd Normal Form (BCNF)


When a table has more than one candidate key, anomalies may result even though the relation is in 3NF.
Boyce-Codd normal form is a special case of 3NF.
A relation is in BCNF if, and only if, every determinant is a candidate key.
Example
Consider the following table STUDENT
Table: STUDENT
StudentId Combination ClassTeacher
100 MCE KABALISA Jean Claude
101 PCB MUGABO Boniface
- 86 -
102 MCB MUKAMANA Scovia
103 HEG KAGABO Pascal
The following facts help to define the structure of the database:
1. Each Student may major in several Combinations.
2. For each Combination, a given Student has only one ClassTeacher.
3. Each Combination has several Advisors.
4. Each ClassTeacher advises only one Combination.
5. Each ClassTeacher advises several Students in one Combination.
The functional dependencies for this table are:
1. StudentId, Combination → ClassTeacher
2. ClassTeacher → Combination
Anomalies for this table include:
 Delete→ Student deletes ClassTeacher information
 Insert → a new ClassTeacher needs a Student
 Update →inconsistencies or contradiction
Because no single attribute which is a candidate key, primary key can be StudentId, Combination,
Student_id,ClassTeacher.
To reduce STUDENT table to BCNF, there is creation of two tables:
 STUDENTTEACHER (Studentid, ClassTeacher)
 TEACHERCOMBINATION(ClassTeacher, Combinationr)
STUDENTTEACHER
StudentId ClassTeacher
100 KABALISA Jean Claude
101 MUGABO Boniface
102 MUKAMANA Scovia
103 KAGABO Pascal
TEACHERCOMBINATION
ClassTeacher Combination
KABALISA Jean Claude MCE
MUGABO Boniface PCB
MUKAMANA Scovia MCB
KAGABO Pascal HEG
 Fourth Normal Form (4NF)
Fourth normal form eliminates independent many to one relationships between columns. A relation is in
Fourth Normal Form:
 A relation must first be in Boyce-Codd Normal Form.
 Given relation may not contain more than one multivalued attribute.
The multi valued dependency X→Y holds in a relation R if whenever there is two tuples of R that same in all
the attributes of X, then we can swap their Y components and get two new tuples that are also in R.
Table: STUDENTS
StudentId Subject Clubs
110 Mathematics Anti SIDA
110 Computer Science Anti SIDA
110 Mathematics Anti drugs
110 Computer Science Anti drugs
151 Music Environmental

Primary key→{StudentId , Subject , Clubs}


 Many StudentId have same Subject.
- 87 -
 Many StudentId have same Clubs. Thus violates 4NF.
To convert to 4NF, the table STUDENTCLUB is changed to the following design:
STUDENTSUBJECT {StudentId, Subject}
StudentId Subject
110 Mathematics
110 Computer Science
151 Music
STUDENTCLUBS {StudentId , Clubs}
StudentId Clubs
110 Anti SIDA
110 Anti Drugs
151 Environmental

- 88 -
UNIT 6: POINTERS AND STRUCTURE IN C++
6.1 Pointers in C++
6.1.1 Definition of Pointers
A pointer is a variable which contains the address in memory of another variable. There can be a pointer to any
variable type.
The unary or monadic operator & gives the ``address of a variable''.
The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''.
C++ gives the power to manipulate the data in the computer's memory directly. The space in the memory can be
assigned and de-assigned. This is done using pointer variables. Pointer variables are variables that points to a
specific address in the memory pointed to by another variable.
6.1.2 Dereference operators
The asterisk sign (*) in the cout statements is called the dereference operator. If the dereference operator is used, the
“value pointed by” a pointer is got.
The statement:
cout << *ptr; means to print the content of the memory space pointed by ptr.
Example: Use a pointer in calculating area of circle of Radius 5.
#include<iostream>
using namespace std;
int main ()
{
float PI = 3.14;
float *PIptr;
float r=5, A;
float x;
PIptr=&PI; //PIptr contains the address of PI
x=*PIptr; // value stored in PI(3.14)is assigned to x.
A=r*r*x;
cout<<"The area of circle is"<<A;
getchar ();
return 0;
}
6.1.3 Reference operator
The ampersand sign (&) is called the reference operator. If the reference operator is used, it will get the “address of”
a variable. The ptr = &x; means that it stores the address of the variable x in the pointer ptr.
Example:
#include<iostream>
using namespace std;
int main()
{
int x;
int *ptr;
x = 5;
ptr = &x;
cout << *ptr;
return 0;
}

- 87 -
Note: If you forget to place * (in front of the pointer) in the cout statement, you will print the address of integer x.
Example of pointer demonstrating the use of & and *:
#include <iostream>
using namespace std;
int main()
{
/* Pointer of integer type, this can hold the address of an integer type variable. */
int *p;
int var = 10;
/* Assigning the address of variable var to the pointer * p. The p can hold the address of var because var is * an
integer type variable. */
p = &var;
cout<< "Value of variable var is:"<< var <<endl;
cout<<"\n Value of variable var is: "<< *p <<endl;
cout<<"\n Address of variable var is: "<< &var <<endl;
cout<<"\n Address of variable var is: "<< p <<endl;
cout<<"\n Address of pointer p is: "<< &p <<endl;
getchar();
return 0;
}
Output:

Interpretation of this output:

- 88 -
6.1.4 Declaring pointer variables
A pointer is declared by using the * (asterisk) operator before an identifier. It is necessary to initialize the pointer
before you can use a pointer in for instance a cout statement.
Pointer declaration Syntax:
data_type *pt_name;
Where data_type is the data type of the value that the pointer is intended to point to.

The following are three declarations of pointers and all of them are pointers and will occupy the same amount of
space in memory:
int * number;
char * character;
float * greatnumber;
Some Pointer declaration examples
int *iptr; // iptr is pointer to int
char *cptr; // cptr is a pointer to char float
*fptr; // fptr is a pointer to float
List*lptr; // lptr is a pointer to List object
6.1.5 Initialization of Pointer Variable
Pointers can be initialized to point to specific locations at the very moment they are defined,You need to initialize a
pointer by assigning it a valid address.
pointer_variable = &variable;

Example of initialization:
int *ptr; // pointer to int declared, value undefined
int x = 5; // int declared and initialized to 5
cout << x; //prints 5
cout << *ptr; //Error! Prints undefined value, since ptr not initialized
ptr =&x; //ptr now contain value of x
cout<<*ptr; // Prints 5
Example program of Declaring and Initializing pointer:
#include<iostream>
using namespace std;
int main ()
{
// Declaring Variables and Pointer
int Num=10;
int *Ptr;
Ptr=&Num;
// Printing Values of Pointer
cout <<"\n Value Of Num :" << Num << endl ;
cout <<"\n Address Of Num :" << &Num << endl;
cout <<"\n Value Of Ptr :" << Ptr << endl;
cout <<"\n Address Of Ptr :" << &Ptr << endl;
cout <<"\n Ptr's Pointer Value:" << *Ptr << endl;
cout <<"\n Ptr Equal to &Num :" << *(&Num) << endl;
// Change Values of Using Pointer
cout <<"\n\n We Can Change Value Of Num,Without Using Num" << endl;
*Ptr=100;
cout <<"\n Address Of Num :"<<&Num << endl;

- 89 -
cout <<"\n Ptr's Pointer Value:"<<*Ptr << endl;
getchar();
}
6.1.6 Graphical representation of pointers for referencing memory allocation.
Consider the following:
int jim,tom,*blaise; jim = 10;
tom= jim;
blaise = &jim;
The following is graphical representation of the value contained in each variable after the execution of this, are shown
in the following diagram:

Figure : Graphical representation of the value contained variable


First, we have assigned the value 10 to jim (a variable whose address in memory we have assumed to be 501).
The second statement copied to tom the content of variable jim which is 10. the third statement copies to blaise not
the value contained in jim but a reference to it (its address, which we have assumed to be 501).
The reason is that in this third assignment operation we have preceded the identifier jim with the reference operator
(&), so we were no longer referring to the value of jim but to its reference (its address in memory).
6.1.7 Incrementing a Pointer
Incrementing a pointer is generally used in array because we have contiguous memory in array and we know the
contents of next memory location. Incrementing pointer variable depends upon data type of the Pointer variable
Three Rules should be used to increment pointer:
i. Address + 1 = Address
ii. Address++ = Address
iii. ++Address = Address
The following program increments the variable pointer to access each succeeding element of the array :
#include <iostream>
using namespace std;
const int MAX = 3;
int main ( )
{
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have array address in pointer.
ptr = var;
for (int i =0 ; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the next location
ptr++;

- 90 -
}
return 0;
}

6.1.8 Decrementing a Pointer


As shown in example below, the program decrementing a pointer, which decreases its value by the number of bytes
of its data type
#include <iostream>
using namespace std;
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the last element in pointer.
ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--) {
cout << "Address of var[" << i << "] = "; cout << ptr << endl;
cout << "Value of var[" << i << "] = "; cout << *ptr << endl;
// point to the previous location ptr--;
}
getchar();
return 0;
}

- 91 -
6.1.9 Arrays and pointers
The name of an array is a pointer to the first element in the array.
int a[10];
int *aptr = a;
a // is equivalent to &a[0]
aptr = a // is equivalent to aptr = &a[0];
aptr+5 // is equivalent to &a[5]
*(aptr+5) // is equivalent to a[5]
Example :
#include <iostream>
using namespace std;
int main()
{
float arr[10];
float *ptr;
cout << "Displaying address using arrays: " << endl;
for (int i = 0; i < 10; ++i)
{
cout << "&arr[" << i << "] = " << &arr[i] << endl;
}
// ptr = &arr[0]
ptr = arr;
cout<<"\n Displaying address using pointers: "<< endl;
for (int i = 0; i < 10; ++i)
{
cout << "ptr + " << i << " = "<< ptr + i << endl;
}
getchar();
return 0;
}

- 92 -
Different pointer ptr is used for displaying the address of array elements arr. Pointers are the variables that hold
address. Not only can pointers store address of a single variable, it can also store address of cells of an array.

6.1.10 Comparison of pointers


Pointers may be compared by using relational operators, such as ==, <, and >.
The following program incrementing the variable pointer so long as the address to which it points is either less than
or equal to the address of the last element of the array, which is &var[MAX - 1].
#include <iostream>
using namespace std;
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;// let us have address of the first element in pointer.
ptr = var;
int i = 0;
while ( ptr <= &var[MAX - 1] )
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl; // point to the previous location
ptr++;
i++;
}
getchar();
return 0;
}
6.1.11 Subtracting pointers
Differencing means subtracting two Pointers. Subtraction gives the Total number of objects between them.
Subtraction indicates “How apart the two Pointers are?”
Example:
#include<iostream>
using namespace std;
int main()
{
int num , *ptr1 ,*ptr2 ;
ptr1 = &num ;
ptr2 = ptr1 + 2 ;
cout << " the difference of two pointers is: " << ptr2 - ptr1 << endl;
getchar ();
return 0;
}

- 93 -
6.2. Memory allocation
6.2.1 Definition
Memory allocation means reserving memory for specific purposes. It is a process by which computer programs and
services are assigned with physical or virtual memory space, the process of reserving a partial or complete portion
of computer memory for the execution of programs and processes.
6.2.2 Dynamic memory allocation in C++
This refers to performing memory allocation manually by programmer.
When a memory is dynamically allocated, the operating system is asked to reserve some of that memory for that
program’s use. If it can fulfill this request, it will return the address of that memory to the current application. From
that point forward, the application can use this memory as it wishes. When the application is done with the memory,
it can return the memory back to the operating system to be given to another program. This allows to obtain more
memory when required and release it when not necessary.
C++ integrates the operators new and delete for allocating dynamic memory. With the functions malloc, calloc,
realloc and free are available in C++ and can also be used to allocate and deallocate dynamic memory.
A. Operators:
i. Operator new and new[]

Dynamic memory is allocated using operator new. New is followed by a data type specifier and, if a sequence of
more than one element is required, the number of these are within brackets []. It returns a pointer to the beginning of
the new block of memory allocated.

Its syntax is:


pointer = new type
pointer = new type [number_of_elements]
The first expression is used to allocate memory to contain one single element of type type. The second one is used

- 94 -
to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing
the amount of these.
For example:
int * mem;
mem= new int[6];

There is a substantial difference between declaring a normal array and allocating dynamic memory for a block of
memory using new. The most important difference is that the size of a regular array needs to be a constant
expression, and thus its size has to be determined at the moment of designing the program, before it is run, whereas
the dynamic memory allocation performed by new allows to assign memory during runtime using any variable
value as size.

The dynamic memory requested by a program is allocated by the system from the memory heap (unused memory of
the program). However, computer memory is a limited resource, and it can be exhausted. Therefore, there are no
guarantees that all requests to allocate memory using operator new are going to be granted by the system.

ii. Operators delete and delete[]

In most cases, memory allocated dynamically is only needed during specific periods of time within a program; once it
is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic
memory. This is the purpose of operator delete, whose syntax is:

delete pointer;
delete[] pointer;

The first statement releases the memory of a single element allocated using new, and the second one releases the
memory allocated for arrays of elements using new and a size in brackets ([]).
The value passed as argument to delete shall be either a pointer to a memory block previously allocated with new,
or a null pointer (in the case of a null pointer, delete produces no effect).
b. Functions

i. malloc (): void* malloc (size_t size);


Allocate memory block.
Allocates requested size of bytes of memory and returns a pointer to the beginning of the block (first byte of
allocated space). Simply pass in how big you want your memory to be (in bytes), and you get a pointer to that
memory back. The content of the newly allocated block of memory is not initialized, remaining with indeterminate
values. If it fails it returns NULL. It is routine used to allocate a single block of memory.

ii. calloc (): void* calloc (size_t num, size_t size);


Allocate and zero-initialize array
Allocates space for an array element, initializes to zero and then returns a pointer to memory. The calloc() takes two
integer arguments and multiplied together to specify how much memory to allocate. This is routine used to allocate
arrays of memory.
iii. Free (): void free (void* ptr);
Deallocate memory block (the previously allocated space).
A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again
for further allocations.

- 95 -
iv. Realloc (): void* realloc (void* ptr, size_t size);
Reallocate memory block, Change the size of previously allocated space pointed to by ptr.
The function may move the memory block to a new location (whose address is returned by the function).
Example:
#include <iostream> #include <stdlib.h> #include <string.h> using namespace std; int main () {
char *str;
/* Initial memory allocation */ str = (char *) malloc(10); strcpy(str, "HelloWorld");
cout<<"String is:"<<str<<" "<<"Address is:"<<&str<<endl;
/* Reallocating memory */
str = (char *) realloc(str, 15); strcat(str, ".com");
cout<<"String is:"<<str<<" "<<"Address is:"<<&str<<endl;

free(str); str = NULL; getchar();


return(0);.
}

Figure : Output of Dynamic memory allocation example program


Notice: In the above program:
 Malloc () function dynamically allocates initial value of the size maximum 10 characters (e.g the size of
HelloWord has 9 characters) otherwise it returns null and is copied to str variable which has address in memory.
 Realloc() function :reallocate the content of str concatenating with .com and change the size from 10 to 15 but it
keeps the existing address which is 0x22ff44.
 Free(): the memory size of (10) characters that has been reallocated with realloc () is released after using free()
because it is no longer needed.
6.2.3 Static memory (or Compile Time) allocation
The memory for your variables is allocated when the program starts, the size is fixed when the program is created.
Statically allocated variables have their storage allocated and initialized before main starts running and are not

- 96 -
deallocated until main has terminated. Statically allocated local variables are not re- initialized on every call to the
function in which they are declared. A statically allocated variable thus has the occasionally useful property of
maintaining its value even when none of the functions that access the variable are active.
6.2.4 Advantages of dynamic memory allocation over static memory allocation
An advantage is that the program determines how much memory it needs at run time and allocate exactly the right
amount of storage and released when it's no longer needed.
 Dynamic Memory Allocation
o Memory allocated "on the fly" during run time
o dynamically allocated space usually placed in a program segment known as the heap or the free store
o Exact amount of space or number of items does not have to be known by the compiler in advance.
o For dynamic memory allocation, pointers are crucial

 Static (or Compile Time) Allocation


o Memory for named variables is allocated by the compiler
o Exact size and type of storage must be known at compile time
o For standard array declarations, this is why the size has to be constant

6.3 . C++ Structures


6.3.1 Introduction to C++ structure
Structure is a collection of variables of different data types under a single name. These data elements, known as
members, can have different types. To store some information about a student: Name, Age and student ID. Creation
of different variables name, Age, ID needed to store this information separately.
6.3.2 How to declare a structure in C++ programming?
The struct keyword defines a structure type followed by an identifier (name of the structure).
Data structures can be declared in C++ using the following syntax:

struct type_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
} object_names;
Where:
type_name is a name for the structure type, object_name can be a set of valid identifiers for objects that have the type
of this structure. Within braces {}, there is a list with the data members, each one is specified with a type and a valid
identifier as its name.

6.3.3 Initializing structure in C++ programming


Just like any variable, we can specify the initial value of a structure at the time of its definition.
Example of Initialization of structure:
#include<iostream>
using namespace std;
struct Book
{
char name [100];
float price;
int pages;
};
int main ()
{

- 97 -
struct Book b1= {"Computer Programing with C++",30000,250};
struct Book b2= {"Computer Networking ",15000,200};
cout<<"Book 1 Details\n"<<endl;
cout<<"Title:\t"<<[Link]<<endl;
cout<<"Price:\t"<<[Link]<<endl;
cout<<"Pages:\t"<<[Link]<<endl<<"\n";
cout<<"Book 2 Details\n"<<endl;
cout<<"Title:\t"<<[Link]<<endl;
cout<<"Price:\t"<<[Link]<<endl;
cout<<"Pages:\t"<<[Link]<<endl;
getchar ();
return 0;
}
Members of object b1 and b2 are initialized. Values which will be passed to members of the structure are listed in
the braces.

6.3.4 Calculate Memory consumption by structure


To generate the program below, padding must be added to the structs to satisfy this alignment criteria. It creates two
structs; both contain 3 values of the same types and of the same name. It then prints out the sizes of these structs (in
bytes).
#include <iostream>
using namespace std;
struct A
{
char a; long b; char c;
};
struct B
{
char a; char c; long b;
};
int main()
{
A a;
B b;
cout << "sizeof(a): " << sizeof(a) << endl;
cout << "sizeof(b): " << sizeof(b) << endl;
getchar ();
return 0;
}
Output:
sizeof(a): 12
sizeof(b): 8
Note: Output may vary depending on the systems

The C++ standard defines that struct members must be arranged in memory in the same order that they are defined
within their access level. Different types must have certain memory alignment requirements; long (on a 64-bit
platform) uses 8 bytes of memory and must start at a memory location divisible by 8 char, on the other hand, only

- 98 -
uses 1 byte of memory and can start at any memory address.

6.3.5 Accessing members of a structure


We need to specify both the structure name (name of the variable) and the member name when accessing
information stored in a structure.
There are two types of operators used for accessing members of a structure:

 Member operator (.) or Dot Operator

structure_variable_name.member_name

For Example:
We can access the member age of employee structure variable employee_one as:
struct employee
{
char name[50]; int age;
float salary;
char department[30];
}
employee_one = {"paul", 25, 150000.5, "ICT"};
int age = employee_one.age;
 Structure pointer operator (->) or Arrow Operator (->)
Structure pointer operator or Arrow operator is used to access members of structure using pointer variable. When
we have pointer to a structure variable, then we can access member variable by using pointer variable followed by
an arrow operator and then the name of the member variable.
structure_pointer->member_name;

For example:
struct employee
{
char name [50]; int age;
float salary;
char department [30];
}
employee_one = {"Paul", 25, 150000.5, "ICT"};
struct employee *ptr = &employee_one;
int age = ptr->age;
//C++ Program to print the members of a structure using dot and arrow operators:
#include <iostream>
#include <conio.h>
using namespace std;
struct employee
{
char name[100];
int age;
float salary;
char department[50];
};

- 99 -
int main()
{
struct employee employee_one, *ptr;
cout<<"Enter Name, Age, Salary and Department of Employee\n";
cin>>employee_one.name>>employee_one.age>>employee_one.salary>>employee_one.depar tment;
/* Printing structure members using dot operator */
cout<<"Employee Details\n"<<employee_one.name<<"\t"
<<employee_one.age<<"\t"
<<employee_one.salary <<"\t" <<employee_one.department ;
/* Printing structure members using arrow operator */
ptr=&employee_one;
cout<<"\n\nEmployee Details\n"<<ptr->name<<"\t"<<ptr->age<<"\t"<<ptr->salary<<"\t"<<ptr->department;
getch();
return 0;
}}

6.3.6 Nesting structure


Structures can be nested within other structures in C++ programming. Structures can also be nested so that a valid
element of a structure can also be another structure.
When a structure contains another structure, it is called nested structure. For example, we have two structures
named Address and Student. To make Address nested to Student, we have to define Address structure before and
outside Student structure and create an object of Address structure inside Student structure.
Syntax for structure within structure or nested structure
struct structure1
{
----------
----------
};
struct structure2
{
----------
----------

- 100 -
struct structure1 obj;
};
Example:
#include <iostream>
#include<conio.h>
using namespace std;
struct Address
{
char SchoolName[25];
char Prov[25];
char District[25];
char City[25];
char Code[25];
};
struct Student
{
int Id;
char FName[25];
char SName[25];
char StudentClass[25];
char StudentCourse[25];
float Marks;
struct Address Add;
};
int main()
{
int i;
Student S;
cout << "\n\t Enter StudentFirst Name : ";
cin >> [Link];
cout << "\n\t Enter Student Second Name : ";
cin >> [Link];
cout << "\n\tEnter Student Id : ";
cin >> [Link];
cout << "\n\tEnter Student Shool Name : ";
cin >> [Link];
cout << "\n\tEnter Student Shool province : ";
cin >> [Link];
cout << "\n\tEnter Student Shool District : ";
cin >> [Link];
cout << "\n\tEnter Student Shool City : ";
cin >> [Link];
cout << "\n\tEnter Student Shool code : ";
cin >> [Link];
cout << "\n\tEnter Student marks : ";
cin >> [Link];
cout << "\nDetails of Students";
cout << "\nDetails of Students";
cout << "\n\tStudent First Name: " << [Link];
cout << "\n\tStudent Second Name : " << [Link];
cout << "\n\tStudent ID : " << [Link];

- 101 -
cout << "\n\tSchool Name : " << [Link];
cout << "\n\t School Province : " << [Link];
cout << "\n\t School District : " << [Link];
cout << "\n\t School City : " << [Link];
cout << "\n\t school code : " <<[Link];
cout << "\n\t Marks No : " << [Link];
getch();
return 0;
}
6.3.7 Array of structure
Arrays of structure are good for storing information of a single entity. By declaring an array of structures, you
specify the number of reserved structures inside array brackets when you declare the structure variable.
Example:
#include <iostream>
#include <conio.h>
#include<stdio.h>
#include<string.h>
using namespace std;
struct Employee
{
int empcode;
char empname[20];
char empdesig[20];
float empsalary;
};
int main ( ){
int i;
clrscr();
for (i=1; i<= 3; i++){
cout<<"\nEnter info about Employee No "<<i <<":\n\n" ;
cout<<"\tEnter employee code:";
cin >>emp[i].empcode;
cout<<"\tEnter employee name:";
cin>>emp[i].empname;
cout<<"\tEnter employee designation:";
cin>>emp[i].empdesig;
cout<<"\tEnter employee salary:";
cin>>emp[i].empsalary;
}
//print the structure emp1 information to the screen
cout<<"\n\nHere is the employee information:\n\n";
for(i=1;i<=3;i++){
cout<<"\nInformation about Employee No "<<i <<" is \n" ;
cout<<"\n\t Employee code:"<<emp[i].empcode;
cout<<"\n\t Employee name:"<<emp[i].empname;
cout<<"\n\t Employee designation:"<<emp[i].empdesig;
cout<<"\n\t Employee salary:"<<emp[i].empsalary<<"\n";
}
getch();
return 0;

- 102 -
}
Output:

- 103 -
UNIT 7: OBJECT ORIENTED PROGRAMMING IN C++
7.1. Introduction to Object Oriented Programming (OOP)
7.1.1 Definition of Object Oriented Programming
Object-oriented programming (OOP) refers to a type of computer programming (software design) in which
programmers define not only the data type of a data structure, but also the types of operations (functions) that can be
applied to the data structure.
In this way, the data structure becomes an object that includes both data and functions. In addition, programmers can
create relationships between one object and another.
Some key features of the object oriented programming are:
 Emphasis on data rather than procedure
 Programs are divided into entities known as objects
 Data structures are designed such that they characterize objects.
 Functions that operate on data of an object are tied together in data structures.
 Data is hidden and cannot be accessed by external functions.
 Objects communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 Follows bottom up design in program design.
7.1.2 Basic Concepts of Object Oriented Programming
The main concepts and principles used within Object Oriented Programming are:
Definitions of OOP concepts
a) Object
An objects is the basic unit of OOP. It is an instance of class, which has data members and use various member
functions to perform tasks.
b) Class
A class is basically a blueprint of an object. It can also be defined as user defined data type but it also contains
functions in it. It declares and defines what data variables the object will have and what operations can be performed
on the class's object.
c) Encapsulation
Encapsulation means that the internal representation of an object is generally hidden from view outside of the
object’s definition. Typically, only the object’s own methods can directly inspect or manipulate its fields. It can also
be said data binding. Encapsulation is all about binding the data variables and functions together in class.
d) Abstraction
Data abstraction and encapsulation are closely tied together, because a simple definition of data abstraction is the
development of classes, objects, types in terms of their interfaces and functionality, instead of their implementation
details. Abstraction denotes a model, a view, or some other focused representation for an actual item.
In C++, classes can provide methods to the outside world to access & use the data variables, keeping the variables
hidden from direct access, or classes can even declare everything accessible to everyone, or maybe just to the classes
inheriting it. This can be done using access specifiers.
e) Inheritance
Inheritance as the key feature of Object-Oriented Programming is a way to reuse code of existing objects, or to
establish a subtype from an existing object, or both, depending upon programming language support. In classical
inheritance where objects are defined by classes, classes can inherit attributes and behavior from pre-existing classes
called base classes, super classes, parent classes or ancestor classes. The resulting classes are known as derived
- 104 -
classes, subclasses or child classes. The relationships of classes through inheritance gives rise to a hierarchy.
The derived class inherits all the features from the base class and can have additional features of its own.
f) Polymorphism
It is a feature, which lets programmers create functions with same name but different arguments, which will
perform different actions. That means, functions with same name, but functioning in different ways. Or, it also allows
users to redefine a function and provide it with a completely new definition.
g) Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at runtime (during the
running of the program).
Graphically the principles of Object Oriented Paradigm can be represented like this.

Advantages of Object Oriented Programming


One of the principal advantages of Object-Oriented Programming techniques over procedural programming
techniques is that they enable programmers to create modules that do not need to be changed when a new type of
object is added.
So, Object Oriented Programming has great advantages over other programming styles.
1. Code Reuse and Recycling: Objects created for Object Oriented Programming can easily be reused in other
programs.
2. Data Redundancy: Inheritance is the good feature for data redundancy. If you need a same functionality in
multiple classes, you can write a common class for the same functionality and inherit that class to sub class.
3. Data hiding: Implementation details are hidden from other modules and other modules has a clearly defined
interface.
4. Design Benefits: Large programs are very difficult to write. Object Oriented Programming force designers to go
through an extensive planning phase, which makes for better designs with less flaws.
In addition, once a program reaches a certain size, Object Oriented Programs are actually easier to program than
non-Object Oriented ones.

5. Software Maintenance: An Object Oriented Program is much easier to modify and maintain than a non-Object
Oriented Program. So although a lot of work is spent before the program is written, less work is needed to maintain it
over time.
Disadvantages of Object oriented Programming
1. Size: object oriented programs are much larger than other programs.
2. Effort: object oriented programs require a lot of work to create it.
3. Speed:object oriented programs are slower than other programs,partially because of their [Link] aspects
- 105 -
of object oriented programs also demand more system resources,thus slowing the program down.

7.2 Class definition in C++


7.2.1 Definition of a class
A class is defined in C++ using keyword class followed by the name of class.
The body of class is defined inside the curly brackets and terminated by a semicolon at the end.

7.2.2 Syntax
class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
};
Example1:
classTest
{
private:
int data_1;
double data_2;
public:
void function_1()
{
data_1 =2;
}
double function_2()
{
data_2 =3.5;
return data_2;
}
};
Here, the class is named Test.
This class has two data members: data_1 and data_2 and two member functions: function_1() and function_2().
A Class is an expanded concept of data structures, like data structures, it can contain data members, but it can also
contain functions as members.
Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this
class.
The body of the declaration can contain members, which can either be data or function declarations, and optionally
access specifiers.
Classes have the same format as plain data structures, except that they can also include functions and have these new
things called access specifiers (data hiding).
An access specifier is one of the following three keywords: private, public or protected.
Access specifiers are used to identify access rights for the data and member functions of the class.
There are three main types of access specifiers in C++ programming language:
 A private member within a class denotes that only members of the same class have accessibility.
The private member is inaccessible from outside the class.
 Public members are accessible from outside the class.
 A protected access specifier is a stage between private and public access. If member functions defined in a
class are protected, they cannot be accessed from outside the class but can be accessed from the derived class.
- 106 -
When defining access specifiers, the programmer must use the keywords: private, public or protected when
needed, followed by a colon and then define the data and member functions under it.
class AddNumbers
{
private:
int x,y;
public:
void sum()
{
………
………
}
};
In the code above, the member x and y are defined as private access specifiers. The member function sum is defined as
a public access specifier.
General structure for defining a class is:
class class_name
{
access_specifier:
data member;
member_functions;
access_specifier:
data_member;
member_functions;
};
֍ Generally, in class, all members (data) would be declared as private and the member functions would be declared
as public.
If no access specifiers are identified for members of a class, the members are defaulted to private access (Private is
the default access level for specifiers).
class AddNumbers
{
int a,b;
public:
void sum()
{
………
………
}
};
In this example, for members a and b of the class AddNumbers there are no access specifiers identified. This means
that by default a and b are private members of class AddNumbers.
You can have functions inside class. These functions can be either under public or private, and their syntaxes are
the same.
For example, if you have a function to display information of an account called display, and other classes should be
able to access that function, the following line would be added under the public area:

void display (accountno);

- 107 -
And use the following syntax to implement the function:
void BankAccount::display (int accountno)
{
……………;
………….;
}
The computer accesses an object through the use of one of the object’s methods. The method performs some action
to the data in the object and returns this value to the computer. Classes of objects can also be further grouped into
hierarchies, in which objects of one class can inherit methods from another class.
The structure provided in object-oriented languages makes them very useful for complicated programming tasks.
7.2.3 Defining member functions inside or outside the class definition
Member functions of a class can be defined either inside or outside the class definition.
In both cases, the function body remains the same, however, the function header is different.
[Link] Inside the Class
When a member function is defined inside the class, the class name and the scope resolution operator are not specified
in the function header. Moreover, the member functions defined inside a class definition are by default inline
functions.
To understand the concept of defining a member function inside a class, consider this example.
Example 1: Definition of a member function inside a class
Class student
{
string fname;
float marks;
public:
void getdata(); //declaration
void putdata()//definition inside the class
{
cout<<"\n student name is: "<<fname;
cout<<"\n his marks are: "<<marks;
};
In this example, the member function putdata() is defined inside the class Student. Hence, putdata()is
by default an inline function.
Example 2:
#include <iostream>
using namespace std;
class car
{
private:
int number;
char model[10];
public:
void getdata()
{
cout<<"Enter car number:";
cin>>number;
cout<<"Enter car model:";
cin>>model;
}
void showdata()
{
cout<<"Car number is "<<number<<endl;
- 108 -
cout<<"Car model is "<<model<<endl;
}
};
//main function starts
int main()
{
car c1;
[Link]();
[Link]();
return 0;
}
[Link] Outside the Class
Defining a member function outside a class requires the function declaration (function prototype) to be provided
inside the class definition. The member function is declared inside the class like a normal function. This declaration
informs the compiler that the function is a member of the class and that it has been defined outside the class. After a
member function is declared inside the class, it must be defined (outside the class) in the program.
֍ The definition of member function outside the class differs from normal function definition, as the function name
in the function header is preceded by the class name and the scope resolution operator (: :).
The scope resolution operator informs the compiler what class the member belongs to.
Here is the syntax for defining a member function outside the class:
class class_name
{
…………………
…………………
public:
return_type function_name(parameter_list)
};
//function definition outside class
return_type class_name :: function_name (parameter_list)
{
………………..// This is the body of the function(function definition)
}
To understand the concept of defining a member function outside a class, consider this example.
Example 1:
#include <iostream>
using namespace std;
class car
{
private:
int number;
char model[10];
public:
// functions declaration
void getdata();
void showdata();
};
// function definition
void car::getdata()
{
cout<<"Enter car number:";
cin>>number;

- 109 -
cout<<"Enter car model:";
cin>>model;
}
void car::showdata()
{
cout<<"Car number is "<<number<<endl;
cout<<"Car model is "<<model<<endl;
}
//main function starts
int main()
{
car c1;
[Link]();
[Link]();
return 0;
}
In the above program,the functions showdata( ) and getdata( ) are declared inside a class and defined outside the class.
Example2:
Let us re-write the program which converts the degree from Fahrenheit to Celsius and displays the corresponding
degrees on the screen. By creating the method outside the class, we have:
#include<iostream>
#include<conio.h>
using namespace std;
class temperature
{
private:
float degreeCelcius;
float tempFahr;
public:
void conversion (float); // declaration of a method or function

}; // end of the class


void temperature::conversion(float a) //definition of a method
{
tempFahr=a;
degreeCelcius=((tempFahr-32)*(0.55));
cout<<"After conversion the degree in Celcius is:"<<degreeCelcius<<endl;
} // end of the function
int main()
{
temperature celsius; // creation of an object statically
float b;
cout<<"Enter degree in Fahrenheit:"<<endl;
cin>>b;
[Link] (b); // calling a method
getch();
}
Note that the member functions of the class can access all the data members and other member functions of the same
class (private, public or protected) directly by using their names.
In addition, different classes can use the same function name.

- 110 -
7.3 Object in C++
7.3.1 Definition:
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the
variable.
So, an object is a group of variables of various types. It thus usually gathers tens of very different information
from/to each other within the same structure, thus making this information easier to handle.
By analogy with equation of Wirth, we could say that the equation of the Object Oriented Programming (OOP) is:
Methods+Data= Objects

With the difference of what occurs with a table, the various variables of the same object are not indicated by an
index, but by a name which is proper for them.
In fact, these names which characterize the various variables within an object are called properties of the object. As
consequence, any property of object obeys strictly the rules which apply to the variables in any language (type, size,
rules of assignment…).
It will be also said that several objects which have the same properties are of the same type, or for better
explanation, of the same class.
Example
For example, let us say that you want to make a program which will record or process the data on the books in a
library or bookshop, take an object of everyday usage: “A book”.

The properties of a book are: its size (number of the pages), the name of the author, date of publication, printing
company, its price, its name (title), if a person can borrow it or not, etc.
You can easily find the type of each one of these properties:
 The title and the name of author are the properties of the character type.
 The size (a number of pages) and the price are the properties of the numerical type. The situation “if one can
borrow it from the library or not” is a Boolean property.

7.3.2 Creating single object


When a class is defined, only the specifications for the object is defined, the memory or storage is not allocated.
To use the data and access functions defined in the class, you need to create objects.

[Link] Syntax to define Object in C++


className objectVariableName;
You can create objects of Test class (defined in above example) as follows:
Class Test
{
private:
int data1;
float data2;
public:
void function1()
{
data1 =2;
}
float function2()
{
data2 =3.5;
return data2;
}
- 111 -
};
int main()
{
Test o1, o2;
}
Here, two objects o1 and o2 of Test class are created.
In the above class Test, data1 and data2 are data members and function1() and function2() are member functions.
Example: Class and Object
// Program to illustrate the working of objects and class in C++ Programming
#include<iostream>
usingnamespace std;
classTest
{
private:
int data1; float data2;
public:
void insertIntegerData(int d)
{
data1 = d;
cout <<"Number: "<< data1;
}
float insertFloatData()
{
cout <<"\nEnter data: ";
cin >> data2;
return data2;
}};
int main()
{
Test o1, o2;
float secondDataOfObject2;
[Link](12);
secondDataOfObject2 = [Link]();
cout <<"You entered "<< secondDataOfObject2;
return0;
}
Output
Number: 12
Enter data: 23.3
You entered 23.3
In this program, two data members data1 and data2 and two memberfunctions insertIntegerData() and
insertFloatData() are defined under Test class.
Two objects o1 and o2 of the same class are declared.
The insertIntegerData() function is called for the o1 object using:

[Link](12);
This sets the value of data1 for object o1 to 12.
Then, the insertFloatData() function for object o2 is called and the return value from the function is stored in variable
secondDataOfObject2 using:

secondDataOfObject2 = [Link]();
- 112 -
In this program, data2 of o1 and data1 of o2 are not used and contains garbage value.
[Link]. Creating array of objects
All of whose elements are of the same class,can be declared just as an array of any built-in type.
Syntax:
class_name array_name[size];
Example:
#include <iostream>
using namespace std;
class books
{
private:
char title[10];
float price;
public:
// functions declaration
void getdata();
void putdata();
};
// function definition
void books::getdata()
{
cout<<"Enter book title:";
cin>>title;
cout<<"Enter book price:";
cin>>price;
}
void books::putdata()
{
cout<<"the title is "<<title<<endl;
cout<<"the price is "<<price<<endl;
}
//main function starts
int main()
{
const int size=3;
books book[size];
for(int i=0;i<size;i++)
{
cout<<" DETAILS OF BOOK "<<(i+1)<<endl;
book[i].getdata();
}
for(int i=0;i<size;i++)
{
cout<<" DETAILS OF BOOK "<<(i+1)<<" are:"<<endl;
book[i].putdata();
}
return 0;
}
7.3.3. Passing object to function
As it is known, we can pass (give) any type of arguments within the member function which can have any numbers

- 113 -
of arguments. In C++ programming language, it is also possible to pass an object as an argument within the member
function of class.
This is useful, when we want to initialize all data members of an object with another object, we can pass objects and
assign the values of supplied object to the current object. For complex or large projects, we need to use objects as an
argument or parameter.
Syntax:

Example: C++ program to add two complex numbers by passing objects to a function.
#include <iostream>
using namespace std;
class Demo
{
private:
int a;
public:
void set(int x)
{
a = x;
}
void sum(Demo ob1, Demo ob2)
{
a = ob1.a + ob2.a;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
//object declarations Demo d1;
Demo d2; Demo d3;
//assigning values to the data member of objects
[Link](10);
[Link](20);
//passing object d1 and d2
[Link](d1,d2);
//printing the values
[Link]();
[Link]();
[Link]();
return 0;
}

Output:
Value of A: 10
- 114 -
Value of A: 20
Value of A: 30
Above example demonstrate the use of object as a parameter. We are passing d1 and d2 objects as arguments to the
sum member function and adding the value of data members a of both objects and assigning to the current object’s
(that will call the function, which is d3) data member a.
7.4 Data Encapsulation and Data Abstraction in C++
All C++ programs are composed of the following two fundamental elements
 Program statements (code): This is the part of a program that performs actions and they are called functions.
 Program data: The data is the information of the program which gets affected by the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate
the data, and that keeps both safe from outside interference and exploitation. Data encapsulation led to the important
OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is
a mechanism of exposing only the interfaces and hiding the implementation details from the user.
Consider an example of Bluetooth in a mobile phone. When we switch on the Bluetooth we are able to connect
another mobile but not able to access the other mobile features like dialing a number, accessing inbox etc. This is
because, Bluetooth feature is given some level of abstraction.
Another point is when mobile A is connected with mobile B via Bluetooth whereas mobile B is already connected
to mobile C then A is not allowed to connect C via B. This is because of accessibility restriction.

C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called
classes. We already have studied that a class can contain private, protected and public members. By default, all
items defined in a class are private. For example
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth;// Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be accessed only by other members
of the Box class, and not by any other part of your program. This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the
public keyword. All variables or functions defined after the public specifier are accessible by all other functions in
your program.
Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal is to
keep as many of the details of each class hidden from all other classes as possible.
Data Encapsulation Example
Any C++ program where you implement a class with public and private members is an example of data
encapsulation and data abstraction. Consider the following example
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0)
- 115 -
{
total = i;
}
// interface to outside world
void addNum(int number) {
total += number;
}
// interface to outside world
int getTotal() {
return total;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
[Link](10);
[Link](20);
[Link](30);
cout << "Total " << [Link]() <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result
Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces
Total 60

to the outside world and a user needs to know them to use the class. The private member total is something that is
hidden from the outside world, but is needed for the class to operate [Link]
7.5 Friend function in C++
One of the important concepts of OOP is data hiding, i.e., a non-member function cannot access an object's private or
protected data but there is mechanism built in C++ programming to access private or protected data from non-member
[Link] is done using a friend function or/and a friend class.
If a function is defined as a friend function then, the private and protected data of a class can be accessed using the
function.
The compiler knows a given function is a friend function by the use of the keyword friend.
For accessing the data, the declaration of a friend function should be made inside the body of the class (can be
anywhere inside class either in private or public section) starting with keyword friend.
Note: Characteristics of friend function
 The friend function is not in class scope
 It should be declared inside the class with friend keyword
 It can be defined anywhere in the program and outside of the class like a normal function but the friend
key word must not be used in the function definition.
 It is not in class [Link] it cannot be called by objects of the class
 It can be called like a normal function.
 Usually it has class objects as arguments
 It cannot access member variables or functions directly,but can only be accessed by the help of the objects
of the class

- 116 -
 It can be declared with any access specifier and the access specifier does not have any impact on the friend
function.
Declaration of friend function in C++
class class_name
{
... .. ...
friend return_type function_name(argument/s);
... .. ...
}
Example 1: Working of friend Function
/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance()
{
meter=0;
}
//friend function
friend int addFive(Distance);
};
// friend function definition
int addFive(Distance d)
{
//accessing private data from non-member function
[Link] += 5;
return [Link];
}
int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}
Output
Distance: 5
Here, friend function addFive() is declared inside Distance class. So, the private data meter can be accessed from this
function.
Example 2:
/*finding tax from salary entered by a user using friend function*/
#include <iostream>
using namespace std;
class person
{
// member variables declaration
string name;
int salary;

- 117 -
public:
void getSalary()
{
cout<<"Enter the name:" <<endl;
cin>>name;
cout<<"Enter the salary:"<<endl;
cin>>salary;
}
void printDetails()
{
//show output
cout<<" YOU HAVE ENTERED THE DETAILS:"<<endl;
cout<<" Name:"<<name<<",Salary:"<<salary<<endl;
}
//friend function declaration
friend int calculateTax(person p);
};
// friend function definition
int calculateTax(person p)
{
//calculate tax 5% and returns tax amount
int tax =([Link]/100)*5;
return tax;
}
int main()
{
//object creation for class
person obj;
int tax=0;
[Link]();
[Link]();
//call friend function like normal function
tax=calculateTax(obj);
cout<<"Calculated Tax(5%) :" <<tax;
return 0;
}
7.6 Polymorphism in C++
Polymorphism is derived from two Greek words: poly and morphs. The word "poly" means many and morphs
means forms. So polymorphism means having many forms.
The process of representing one Form in multiple forms is known as Polymorphism.
So Polymorphism is a feature of OOPs that allows the object to behave differently in different conditions.
In c++ we have two types of polymorphism:
 Compile time polymorphism(Static or early binding).
 Runtime polymorphism (or dynamic or late binding).
a) Compile time polymorphism
Process by which the binding of functional call and choosing the correct function declaration done by compiler at
the compile time.
Function overloading and operator overloading are perfect example of compile time polymorphism.

- 118 -
Example:
#include <iostream>
using namespace std;
class Add{
public:
int sum(int num1,int num2)
{
return num1+num2;
}
int sum(int num1,int num2,int num3)
{
return num1+num2+num3;
}
};
int main( ) {
Add obj;
//This will call the first function
cout<<"The 1st sum is :"<<[Link](10,20)<<endl;
//This will call the second function
cout<<"The 2nd sum is: "<<[Link](11,22,33);
return 0;
}
Output:
The 1st sum is :30
The 2nd sum is :66
In the above program ,we have two functions(called sum) with the same name but different number of arguments.
Based on how many parameters we pass during function call determines which function is to be called,this is why it is
considered as an example of polymorphism because in different conditions the output is different.
b) Runtime polymorphism
Here the binding happens at run [Link] overriding is an example of runtime polymorphism
Function overriding: when a child class declares a method,which is already present in the parent class then this is
called function overriding,here child class overrides the parent class.
Example:
#include <iostream>
using namespace std;
class A{
public:
void disp(){
cout<<"Super class function"<<endl;
}
};
class B:public A {
public:
void disp( ){
cout<<"Sub class function";
}
};
int main( ) {
//parent class object
A obj;
[Link]();
// Child class object
- 119 -
B obj2;
[Link]();
return 0;
}
Output:
Super class function
Sub class function
7.7 Overloading
Overloading is the reuse of the same symbol(operator) or function name for two or more distinct operations or
functions.
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use,
by comparing the argument types you have used to call the function or operator with the parameter types specified in
the definitions. The process of selecting the most appropriate overloaded function or operator is called overload
resolution.
In C++ ,we can overload:
 Methods(functions)
 Constructors
 Indexed properties
And C++ has two types of overloading:
Function overloading
Operator overloading
a. Operator overloading
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide special
meaning to the user-defined data type.
It is a feature in C++ that enables the redefinition of operators.
Example:Overloading + to add two time class objects.
Following is the example to show the concept of operator over loading using a member function.
Here an object is passed as an argument whose properties will be accessed using this object, the object which will
call this operator can be accessed using this operator as explained below
#include <iostream>
using namespace std;
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
- 120 -
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
[Link] = this->length + [Link];
[Link] = this->breadth + [Link];
[Link] = this->height + [Link];
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification [Link](6.0); [Link](7.0); [Link](5.0);
// box 2 specification
[Link](12.0); [Link](13.0);
[Link](10.0);
// volume of box 1
volume = [Link]();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = [Link]();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = [Link]();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result.
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Overloadable/Non-overloadableOperators
Following is the list of operators which can be overloaded

+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
- 121 -
b. Function overloading
Function overloading is defined as the process of having two or more functions with the same name,but different
parameters.
In function overloading,the function is redefined by using either different types of arguments or a different number of
arguments. It is only through these differences compiler can differentiate between the functions.
The advantage of function overloading is that it increases the readability of the program because you don’t need to
use different names for the same action.
Example 1:
//Program of function overloading when number of arguments vary
#include <iostream>
using namespace std;
class addition{
public:
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
};
int main( ) {
addition c; // class object declaration
cout<<[Link](10,20)<<endl;
cout<<[Link](12,20,23);
return 0;
}
Output:
30
55
Example2:
//Program of function overloading with different type s of arguments
#include <iostream>
using namespace std;
class addition{
public:

int sum(int x,int y)


{
return x+y;
}
double sum(double x,double y)
{
return x+y;
}};
int main(void)
{
addition S;
cout<< “The sum integers is:”<<[Link] (20,10)<<endl;

- 122 -
cout<<”The sum of doubles is:”<< [Link] (10.5,20.1);
return 0;
}
Output:
The sum of integers is:30
The sum of doubles is:30.6
7.8 Constructors and Destructors
Introduction:
Constructors and destructors determine how the objects of a class are created, initialized, copied, and destroyed.
They are member functions whose names are distinguished from all other member functions because they have the
same name as the class they belong to. Constructors and destructors have many of the characteristics of normal
member functions.
7.8.1. Constructor
A constructor is a member function that is automatically called when an object of that class is declared. Inside a
constructor function you will do all the initialization you want on the data members. For example you can assign the
account number, put in the amount of money, etc.
A constructor has the same name as the class in which it is created. It does not return any type and can have an
unspecified number of arguments.
Notice that you are allowed to have more than one constructor. This is called overloading of functions. Therefore,
if you have more than one constructor in your class you can have more than one method to declare an object of that
kind.
A constructor is member function, defined as other functions and is called automatically at each creation of an
object.
a. Types of constructors
i. Default constructor
Default constructor is the constructor which does not take any argument. It has no parameter.
Syntax:
Class_name()
{
Constructor Definition
}
Example:
class cube
{
int side;
public:
cube() //default constructor definition
{
side=10;
}};
int main (){
cube c; // creating object by using default constructor
………….
return 0;
}
In this case, as soon as the object is created the default constructor is called which initialize its data members.
A default constructor is so important for initialization of object member, that even if we do not define a constructor
explicitly, the compiler will provide a default constructor implicitly.

- 123 -
ii. Parametarised constructor
These are the constructors with parameters. Using constructor you can provide different values to data members of
different objects, by passing the appropriate values as argument.
Syntax:
Class_name( parameters)
{
Constructor Definition
}
Example:
#include<iostream>
using namespace std;
class cube
{
int side;
public:
cube(int i)
{
side=i;
}
};
int main ()
{
cube c(10);//creating object c using parameterised constructor
cube m(45);//creating object m using parameterised constructor
return 0;
}
iii. Copy constructor
These are special type of constructor which takes an object as argument, and is used to copy values of data
members of one object into other object.
b. Characteristics of constructor
 Name of the constructor function is same as that of the class they are part of.
 No return type is required for the constructor function.
 Constructor functions are automatically called at the time of object creation/declaration.
 Constructor functions are always defined in the public type access specifier.
 Constructor functions can be overloaded.
Example of a program implementing the constructor
#include<iostream>
#include<conio.h>
using namespace std;
class example
{
double h,w,area;
public:
example(double height, double width)
{
h=height;
w=width;
}
void rectanglearea(void)
{
area=h*w;
- 124 -
}
void display(void)
{
cout<<"The area of the rectangle is:"<<area<<endl;
}
}; //end of the example class
int main( )
{
double a,b;
cout<<"Enter a: and b:"<<endl;
cin>>a>>b;
example object(a,b);
[Link]( );
[Link]( );
}
7.8.2. Overloading of a constructor
Constructors are just likew other functions,they can also be overloaded,that is same named constructors can be
used to give different set of outputs depending upon the kind of input given to tem.
Example:
#include<iostream>
#include<conio.h>
using namespace std;
class work
{
int X,Y;
public:
work( )//constructor1
{
X=10;
Y=30;
}
work(int c)//constructor2
{
X=c;
Y=2*c;
}
work(int x,int y)//constructor3
{
X=x;
Y=y;
}
}; //end of the work class
int main( )
{
work w; //10:call for constructor1
work r(30,60);//20:call for constructor3
work rr(30);//30:call for constructor2
}

7.8.3. Destructors
The destructor is the counterpart of a constructor. It is a member function that is called automatically when a class
object goes out of scope. It has same name as that of the class , proceeded by a tilde (~). A destructor destroys an
- 125 -
object. Destructors are declared in the header files of their class, or are inherited from the base class of that class.
a. Characteristics of Destructors:
A destructor has the same features as that of the constructor that are
 Name of the destructor function is same as that of the class they belong to, preceded by tilde (~)
 No return type is required for the destructor function
 Destructor functions are automatically called when the object goes out of scope
 Destructor functions are always defined in the public type access specifier
b. Use of destructors
When an object is created, sufficient amount of memory is allocated to it. When the scope of an object comes to an
end, resource allocated to it must be freed so that it can be used elsewhere. This process can be achieved by the use of
a destructor. This function is automatically invoked when the scope of an object comes to an end.
Note: In case the programmer does not provide for a destructor manually, the compiler provides a default destructor
just as the default constructor.
The definition of the destructor is similar to that of the constructor, but its name is preceded by a tilde (“~”), and it
does not have the arguments.
Briefly:
 It has the same name as the name of the class in which it is defined,
 It is preceded by a tilde
 It does not have a return type (not even void)
Example:
point:: ~point ( )
{
//statements
}
Example: use of destructor
#include<iostream>
#include<conio.h>
using namespace std;
class trial {
private:
int t1,t2;
public:
trial (int a,int b) // constructor function
{
t1=a;
t2=b;
cout<<" This is a trial program";
}
void output( ){
cout<<endl<<" The sum of the variables entered is "<<t1+t2;
}
~trial() // destructor function
{
cout<<" \n The trial program is over";
}};
int main()
{
trial t(1000,2000);
[Link]();
getch();
}
- 126 -
Destructors are less used compared to constructors. It will be used only if the objects are linked to other objects by
pointers. Thus, we can use the destructor to delete the pointers towards these objects.
7.9. Inheritance in C++
7.9.1 Definition of Inheritance
 Inheritance is the process by which new classes called derived classes are created from existing classes called
base classes. The derived classes have all the features of the base class and the programmer can choose to add new
features specific to the newly created derived class.
 In Object Oriented Programming, Inheritance is the process by which objects of one class acquire the properties
and functionality of objects of another class.
Creating or deriving a new class using another class as a base is called inheritance in C++. The new class created is
called a Derived class and the old class used as a base, is called a Base class in C++ inheritance terminology.
For example, a programmer can create a base class named fruit and define derived classes as mango, orange,
banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit)
with additional attributes or features specific to these newly created derived classes. Mango would have its own
defined features, orange would have its own defined features, banana would have its own defined features, etc.
The General Form of Inheritance:
Class derived-class: access-specifier base-class
{
...
... //instructions
...
};
The two points indicate that derived-class is derived from base-class. The access-specifier is optional and if it is
present can be private or public.
The mode of visibility by default is private. It indicates if the aspects of the base class are inherited in a private way
or [Link] inheritance is also called derivation.
7.9.3. Advantages of Inheritance
1. Reusability:
Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need
not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base
class as needed while adding specific features to each derived class as needed.

2. Saves Time and Effort:


The above concept of reusability achieved by inheritance saves the programmer time and effort; since the main
code written can be reused in various situations as needed.

3. Increases Program Structure which results in greater reliability.


Attention!
Some of the exceptions to be noted in C++ inheritance are as follows.
 The constructor and destructor of a base class are not inherited,
 The assignment operator is not inherited,
 The friend functions and friend classes of the base class are also not inherited.
7.9.4. Inheritance rules
a. class derived_classname: inheritance_ specifier baseclassname
For example, if the base class is student and the derived class is peter it is specified as: class student: public peter
The above makes peter have access to both public and protected variables of base class student.
Reminder about public, private and protected access specifiers:

- 127 -
 If a member or variables defined in a class is private, then they are accessible by members of the same class
only and cannot be accessed from outside the class.
 Public members and variables are accessible from outside the class.
 If a member functions or variables defined in a class are protected, then they cannot be accessed from outside
the class but can be accessed from the derived class.
b. Base class
A base class is a class that is created with the intention of deriving other classes from it. It is also called
super/parent/old class.

c. Child Class
A child class is a class that was derived from another, that will now be the parent class to it. It is also called
sub/derived/inherited class.
The protected and public variables or members of the base class are all accessible in the derived class, but a
private member variable is not accessible by a derived class.
The derived class inherits some or all the features from the parent class. A class can also inherit the properties of
more than one class or more than one level.
A derived class with only one parent class is called simple inheritance. And that with several base classes is called
multiple inheritance. In addition, the features of a class can be inherited by more than one class. This process is
known as a hierarchical inheritance.
Declaration
The Commentary
mechanism to derive a class from another derived class is known as multilevel inheritance.

class Circle : public GraphicObject Simple inheritance: circle derives


from GraphicObject in public mode
classGraphicText:publicGraphicObject, Multiple inheritance: GraphicText derives at the
public Chain same time from GraphicObject and from Chain
and it is, each time in public.

class john : private person john inherits uniquely from the person class in
private.

Table . Some examples of inheritance


d. The role of the inheritance modifier and the access modifier: protected
A protected attribute is not accessible outside the class but is accessible from the derived classes. This modifier is
thus intermediate between private and public. The following table recapitulates the accesses provided by these three
modifiers:

Access Modifier Visibility in the children classes Visibility from outside


Private No No
Protected Yes No
Public Yes Yes
Table. accesses to the members and modifiers
The inheritance modifier can be public or private. It conditions the visibility of the members of the parent class in
the derived class. The following table indicates to which access is associated a member with the parent class in the
child class according to the inheritance modifier:

- 128 -
Access in the Access in the child class
parent class Public inheritance Private inheritance
Private Not accessible Not accessible
protected protected Private
Public Public Private

7.9.5 Types/ Forms of Inheritance

[Link] Single Inheritance


In this type of inheritance one derived class inherits from only one base class. It is the simplest form of Inheritance.
Example:
//A program to add two numbers using inheritance
#include<iostream>
using namespace std
class AddData //Base Class
{
protected:
int num1, num2;
public:
void accept()
{
cout<<"\n Enter First Number : ";
cin>>num1;
cout<<"\n Enter Second Number : ";
cin>>num2;
}
};
class Addition: public AddData //Class Addition – Derived Class
{
int sum;
public:
void add()
{
- 129 -
sum = num1 + num2;
}
void display()
{
cout<<"\n Addition of Two Numbers : "<<sum;
}
};
int main()
{
Addition a;
[Link]();
[Link]();
[Link]();
return 0;
}
Output:
Enter First Number : 20
Enter Second Number : 30
Addition of Two Numbers: 50
[Link] Multiple inheritance
Multiple inheritance is the construction in which objects inherit from more than one object type or class.
This contrasts with single inheritance, where objects can only inherit from one type or class.
#include<iostream.h>
#include<conio.h>
class A
{
public:
void addition(int a,int b)
{
cout<<"Addition:"<<a+b<<endl;
}
};
class B
{
public:
void subtraction(int a,int b)
{
cout<<"Subtraction:"<<a-b<<endl;
}
};
class C
{
public:
void multiplication(int a,int b)
{
cout<<"Multiplication:"<<a*b<<endl;
}
};
class D:public A,public B,public C
{
public:
void division(int a,int b)
- 130 -
{
cout<<"Division:"<<a/b<<endl;
}
};
int main( )
{
int a,b;
cout<<"a and b?"<<endl;
cin>>a>>b;
D ob;
[Link](a,b);
[Link](a,b);
[Link](a,b);
[Link](a,b);
getch( );
}
[Link]. Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherits from a single base class.
// A program to find the sum and product of two numbers using hierarchical inheritance
#include <iostream>
using namespace std;
class A //single base class
{
public:
int x, y;
void getdata()
{
cout << "\nEnter value of x and y:\n";
cin >> x >> y;
}
};
class B : public A //B is derived from class base A
{
public:
void product()
{
cout << "\nProduct= " << x * y;
}
};
class C : public A //C is also derived from class base A
{
public:
void sum()
{
cout << "\nSum= " << x + y
}
};
int main()
{
B obj1; //object of derived class B
C obj2; //object of derived class C
[Link]();
- 131 -
[Link]();
[Link]();
[Link]();
return 0;
} //end of program
Output:
Enter value of x and y
2
3
Product= 6
Enter value of x and y:
2
3
Sum= 5
[Link]. Multi-level inheritance
Let us consider an example: let us assume that the result of an exam of the student is stored in the 3 different
classes. Class number stores the registration number, class test stores marks obtained in the two subjects and finally
the class result contains the total of the points obtained in the exam. The class result can inherit the details, such as the
points obtained in the exam and the registration number of the student through the multilevel heritage.
Example:
#include<iostream>
using namespace std;
class number
{
protected:
int reg_number;
public:
void get_number(int);
void display_number(void);
};
void number::get_number(int a)
{
reg_number =a;
}
void number::display_number(void)
{
cout<<"Registration number="<<reg_number<<"\n";
}
class test:public number
{
protected:
float cpp,vb;
public:
void get_marks(float,float);
void display_marks(void);
};
void test::get_marks(float b,float c)
{
cpp=b; vb=c;
}
void test::display_marks( )
- 132 -
{
cout<<"The marks in cpp="<<cpp <<"\n";
cout<<" The marks in vb="<<vb<<"\n";
}
class result:public test
{
float total ;
public:
void display(void);
};
void result::display( )
{
total=cpp + vb;
display_number( );
display_marks( );
cout<<"Total marks="<<total<<"\n";
}
int main( )
{
result object ;
int d ;
float e,f ;
cout<< "Enter the registration number"<< "\n";
cin>>d ;
cout<< "Enter the marks in cpp"<< "\n";
cin>>e ;
cout<< " Enter the marks in vb"<< "\n";
cin>>f ;
object. get_number(d);
object.get_marks(e,f);
object. display( );
}
[Link]. Hybrid Inheritance
There could be situations where we must apply two types or more of inheritance to develop a program.
The following example shows how the hybrid inheritance looks like.
#include <iostream>
#include<conio.h>
using namespace std;
class identification
{
private:
char name[25];
int nbr;
public:
void getident(void)
{
cout<<"What is your name?"<<endl;
cin>>name;
cout<<"and your number?"<<endl;
cin>>nbr;
}
void displayident(void)
- 133 -
{
cout<<nbr<<"\t"<<name;
}
};
class theory:public identification
{
protected:
int math,fr;
public:
void gettheory(void)
{
cout<<"Enter marks in mathematics and french"<<endl;
cin>>math>>fr;
}
void displaytheory(void)
{
cout<<"\t"<<math<<"\t"<<fr;
}
};
class practice
{
protected:
int maint,prog;
public:
void getpractice(void)
{
cout<<"Enter marks in maintenance and in programming"<<endl;
cin>>maint>>prog;
}
void displaypractice(void)
{
cout<<"\t"<<maint<<"\t"<<prog;
}
};
class result:public theory,public practice
{
private:
int total;
public:
void displayresult(void)
{
total=math+fr+maint+prog;
cout<<"\t"<<total<<endl;
}
};
int main( )
{
result ob[29];
for(int a=0;a<5;a++)
{
ob[a].getident( );
ob[a].gettheory( );
- 134 -
ob[a].getpractice( );
}
cout<<" "<<endl;
cout<<endl<<"Nbr\tName\tMath\tFr\tMaint\tProg\tTotal"<<endl;
cout<<" ----------------------------------------------------------- "<<endl;
for(int a=0;a<5;a++)
{
ob[a].displayident( );
ob[a].displaytheory( );
ob[a].displaypractice( );
ob[a].displayresult( );
}
cout<<endl<<" ----------------------------------------------------- ";
getch( );
}

- 135 -
UNIT-9: VARIABLES, OPERATORS, EXPRESSIONS AND CONTROL STRUCTURES.
1.1. Types of Visual Basic Data
There exist many types of variables, but the most used in Visual Basic are:
 An elementary data type, such as Boolean, Long, or Decimal.
 A composite data type, such as an array or structure.
 An object type, or class, defined either in current application or in another application
All the above types are grouped in two major data types: numeric data type and non-numeric data type.
9.1.1Numeric data types
Numeric data types are types of data that consist of numbers, which can be computed mathematically with
various standard operators such as add, minus, multiply, divide among others. Table : Numeric data types
Type Storage Range of values Prefix
Byte 1 byte 0 to 255 or 0 to 28-1 byte
Integer 2 bytes -32,768 to 32,767 or -1/2(216) to ½(216)-1 (signed) int
Long 4 bytes -2,147,483,648 to 2,147,483,648 or -1/2(232)to ½(232)-1(signed) lng

Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values sng


1.401298E-45 to 3.402823E+38 for positive values.
Double 8 bytes -1.79769313486232E+308 to -4.94065645841247E-324 for Dbl
negative values
4.94065645841247E-324 to 1.79769313486232E+308 for
positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807 cur
or -1/2(264)to ½(264)-1 (signed)
Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 or +/-296 if no dec
decimal is use
+/- 7.9228162514264337593543950335 (28 decimal places).
Variant 16 bytes Any value as large as Double Var
(numeric)

9.1.2Non-numeric data types


Non- numeric data types are types of data that cannot be manipulated mathematically using standard
arithmetic operators. The non- numeric data types comprise of text or string data types, the Date data types,
the Boolean data types, Object data type and Variant data type.

Table : Non-numeric data types

- 168 -
Data type Storage Range Prefix
String(fixed length) Length of string 1 to 65,400 characters str
String(variable length) Length +10 bytes 0 to 2 billion characters
Date 8 bytes January 1,100 to December 31,9999 dte
Boolean 2 bytes True or False bln
Object 4 bytes Any embedded object Obj
Variant(text) Length + 22 bytes Same as variable-length string
Suffixes for literal
Literals are values that you assign to data. In some cases, we need to add a suffix behind a literal so that VB
can handle the calculation more accurately. For example, we can use num=1.3089# for a Double.
If a suffix is not added behind a literal, it generates a syntax error. For example, num
= 2.3807# is used for Double data type.
The Table below shows Visual Basic Data Types and their suffixes or Appended type character

Data type Suffix or Appended


type character

Boolean None
Integer %
Long (Integer) &
Single (Floating) !
Double(Floating) #
Currency @
Date None
Object None
String $
Variant None

Note: String literals are normally enclosed within double quotations while date and time literals are
enclosed within two # sign. Strings can contain any characters, including numbers. The following table
summarizes the data types with their enclosing characters and appended type characters

Table : data types with their enclosing characters and appended type characters

Appended type
Data type Enclosing character
character
Boolean (none) (none)

- 169 -
Byte (none) (none)
Char " C
Date # (none)
Decimal (none) D or @
Double (none) R or #
Integer (none) I or %
Long (none) L or &
Short (none) S
Single (none) F or !
String " (none)
Examples:
•Strname = " Hakizimana Petero"
•Telnumber = " 250783297650"
•Firstday = #01-Jan-06 #
•ArrivalTime = # 12:00 am#
9.2Variables
A variable is a name assigned to a data storage location. It can also be defined as area allocated by the computer memory
to hold data. Variables are used in Visual Basic to store various kinds of data during program execution.
9.2.1Variable name
In Visual Basic Program, each variable must be given a name. To name a variable in Visual Basic, there is a set
of rules to be followed.
The rules used in naming variables in Visual Basic are:
No more than 40 characters
Variables must include letters, numbers and underscores ( ). No punctuation, spaces or other
characters are permitted.
A variable name must begin with a letter
The name cannot be a reserved word (words needed by Visual Basic).
For example, End is a reserved word in Visual Basic and therefore should not be used as a variable name.
Examples of valid and invalid variable names are displayed in the table below:
Table : examples of valid and invalid variable names
Valid name Invalid name Reason
My_house [Link] The dot character is used to separate name of a file and its
extension. So it is a reserved character
Today 2Years The first character must be a letter not a number
First_Name_Last_name Her&hermother & is not acceptable

9.2.2Variable declaration
They are three ways for declaration of a variable.
1. Default Declaration
If the variables are not implicitly or explicitly declared, they are assigned the variant (a variable that can
hold data of any size or format) type by default. The variant data type is a special type used by visual basic
that contains numeric, string or date data.

- 170 -
For example: the following VB program finds the sum of two given numbers:
Private Sub Command1_Click()
Dim n1, n2, sum As Variant
n1 = Val([Link])
n2 = Val([Link])
n3 = n1 + n2
[Link] = n3
End Sub
2. Implicit Declaration
To implicitly declare a variable, use the corresponding suffix.
For example:
 TextValue$= my school creates a string variable
 Amount%=1000 creates an integer variable.
3. Explicit Declaration
In a good programming practice, variables have to be explicitly declared. In this variable declaration way,
Visual Basic will take care of ensuring consistency in upper and lower case letters used in variable names.
To explicitly declare a variable, its scope has to be firstly determined. There are four levels of scope are
procedural level, static, form and module level, and last global level
These levels of scope progress from the narrowest (block) to the widest (namespace), where
narrowest scope means the smallest set of code that can refer to the element without qualification.
a)Procedure level
With procedure level, variable are declared using the Dim statement
Example: Dim MyName As String
Dim MyInt As Integer
This is given to variables declared using the Dim reserved word within a block of statemet such as an if …
Then … else statement, or a loop statement.

For example:
Private Sub Command1_Click()
Dim fname As String 'procedure level variable
fname = [Link]
If fname = "Paul" Then
Dim Newname As String ' block level variable this can't be accessed out of if...then else
Newname = "Jean Paul"
[Link] = Newname
Else
Newname = name
[Link] = Newname
End If
End Sub
Here, the variable can only exist and be used within the If … Then … Else statement. It is a local variable
visible only inside the block where it has been declared.
b)Procedure level scope, static
In procedure level ,static, variables declared in this manner do not retain their value once a procedure
terminate, within a procedure level, static variables are declared using the Dim statement
For example: Private
Sub End_click() Static
age As Integer Static

- 171 -
MyName As string End
Sub
Note that
 Dim can only exist and be used within the procedure or function. It is a local variable in that
procedure or function.
 Procedure level variables declared in this manner do not retain their value once a procedure
terminates.
 To make a procedure level variable retain its value upon existing the procedure, replace the Dim
keyword with Static
c)Form(module) level scope
The variable is declared in the General Declarations section at the start of the module. Form (module)
level variables retain their values and are available to all procedures within that form. Module level
variables are declared in the declarations part of the general object in the form’s (module’s) code
window. The Dim keyword is used.
Example1: Dim MyDate as Date
Example2: a program which requires three numbers entered from keyboard then calculates their sum and
average.

Requirements to perform the asked question;


Design interface containing five Text box with their corresponding labels and four commands representing
sum, agerage clear and exit respectively least but not last assign properties to each control and last attach
code
VB Source code can look as follows :
Dim sum As Integer 'module level variable
Private Sub add_Click()
Dim num1, num2, num3 As Integer 'procedure level variable
num1 = Val([Link])
num2 = Val([Link])
num3 = Val([Link])
sum = num1 + num2 + num3
[Link] = sum
End Sub
Private Sub average_Click()
Dim average As Integer 'procedure level variable
average = sum / 3

- 172 -
[Link] = average
End Sub
PrivateSub Command3_Click()
[Link] = ""
[Link] = ""
[Link] = ""
[Link] = ""
[Link] = "" End Sub
Private Sub Command4_Click()
Unload Me
End Sub

Output for the asked question:

d)Global level scope


This is given to variables declared using the public reserved word within a code module. The variable is
declared in the General Declarations section at the start of the module.
It is advisable to keep all global variables in one module. Use the Global or public keyword.
Examples:
Global MyInt as Integer or Public MyInt as
Integer
Notice that several variables can be declared in one statement without having to repeat the data type.
In the following statements, the variables i, j, and k are declared as type Integer, l and m as Long, and x and y as Single:
Dim i, j, k As Integer
'All three variables in the preceding statement are declared as Integer.
Dim l, m As Long, x, y As Single
'In the preceding statement, l and m are Long, x and y are Single.
Variable initialization
Once a variable is declared, it does not have a defined value, hence it cannot be used until it is initialized
by assigning it a value.
Thus, variable initialization is the process of providing or assigning value to the variable

- 173 -
Syntax: Variablename = value
Where Variablename is the descriptive name of the variable, = is the assignment operator and value is the value that a
variable will contain.
For examples:
Private Sub Command1_Click()
Dim Number1As Integer
Dim FirstName As string
DimNumber1As Single
Number1 = 5
FirstName = “Steve”
LoanAmount = 67.38
Print Number1
Print FirstName
Print LoanAmount
End Sub
9.2.4 Declaring Constants
Constant is value in memory that does not change during program execution.
For example, in mathematics, pi is a constant whose numeric value is 22/7.
The declaration of a constant goes immediately with its initialization. Syntax:
Const constant name As data type = value
Examples:
Private Sub Form_Load()
[Link]
Dim circumference As Single
Const r As Integer = 8
Const Pi As Single = 3.14159265358979
circumference = 2 * r * Pi
Print "The circumference of a circle is:"; circumference
End Sub

9.3Scope of a variable
The scope of a declared element is the set of all code that can refer to it without qualifying its name. It is an area of
influence and lifetime for a variable. This means a period of existence dependent on where and how the variable is
declared.
An element can have scope at one of the following levels:
Table : Scope of variables
Level Description
Block/private scope Available only within the code block in which it is declared

- 174 -
Procedure scope Available to all code within the procedure in which it is declared

Module /global Available to all code within the module, class, or structure in which it is declared
scope

In Microsoft Visual Basic for Applications, the three scopes available for variables are private, module, and public.
9.3.1Private (Local) Scope
A local variable with private scope is recognized only within the procedure in which it is declared. A local variable can
be declared with a Dim or Static statement.
When a local variable is declared with the Dim statement, the variable remains in existence only as long as the
procedure in which it is declared is running. Usually, when the procedure is finished running, the values of
the procedure's local variables are not preserved, and the memory allocated to those variables is released.
A local variable declared with the Static statement remains in existant the entire time Visual Basic is
running. Local variable retains its value after the module has finished executing.
9.3.2Module (Global) Scope
A variable that is recognized among all of the procedures on a module sheet is called a "module- level" variable. A
module-level variable is available to all of the procedures in that module, but it is not available to procedures in other
modules. A module-level variable remains in existence while Visual Basic is running until the module in which it is
declared is edited. Module-level variables can be declared with a Dim or Private statement at the top of the module
above the first procedure definition.

Example:
Dim A As Integer ' Module-level variable.
Private B As Integer ' Module-level variable.
Sub Example1()
A = 100
B=A+1
End Sub
Sub Example2()
MsgBox "The value of A is " & A
MsgBox "The value of B is " & B
End Sub
Sub Example3()
Dim C As Integer ' Local variable.
C=A+B
MsgBox "The value of C is " & C
End Sub
Sub Example4()
MsgBox A ' The message box displays the value of A.
MsgBox B ' The message box displays the value of B.
MsgBox C ' The message box displays nothing because C was a local variable.
End Sub
9.3.3Public scope
Public variables have the broadest scope of all variables. A public variable, like a module-level variable, is declared at
the top of the module, above the first procedure definition.
A public variable cannot be declared within a procedure. A public variable is always declared with a "Public"

- 175 -
statement. A public variable may be declared in any module sheet.
Example:
Public SalesPrice As Integer
Public UnitsSold As Integer
Public CostPerUnit As Integer
Sub CDSales()
Dim X as String
SalesPrice = 12
UnitsSold = 1000
CostPerUnit = 5
X = "yes"
MsgBox "The Gross Profit for CD Sales is $" & (SalesPrice*UnitsSold) -(UnitsSold * CostPerUnit)
' Displays the value of 7000 as the gross profit.
End Sub
9.4Operators and expressions in Visual Basic
In programming context, an operator is a symbol or a keyword that instructs a compiler to evaluate
mathematical or logical expressions.A Visual Basic expression is a combination of operators and
operands.
For example, in the expression: energy = mass * light_speed ^2
Energy, mass ,light_speed and 2 are the operands while = is the assignment operator, * is multiplication operator
and ^ the exponentiation arithmetic operator.
9.4.1Arithmetic operators
The most common operators in Visual Basic are the arithmetic operators.
Table . below gives a summary of arithmetic operators supported in Visual Basic.
Operator Description Example
^ Exponentiation 6^ 2=36
* Multiplication 8*10=80
/ Division 18/3=6
\ Integer division(truncates) 10\3=3(Only the integer portion of the result is considered)
Mod Modulus 15Mod4=3
+ Addition 9 + 4 = 13
- Subtraction 5-3=2
Note that:
Parentheses () can change the precedence
To concatenate two strings, use the & symbol or the + symbol: [Link]="My country“+“is”+ “Rwanda”
myname=”John” & “Mugabo”
[Link] (Comparison) operators
Normally, they are used to compare data values and then the result helps to decide what action to take. The result of
comparison operation is a Boolean value (True or False).
Table 9.8: Relational (Comparison) operators

Operator Meaning Example

== Equal to txtItem = “ Video”

- 176 -
> Greater than txtValue > 20.45

< Less than txtValue < 50

>= Greater than or equal to txtValue >= 60.5

<= Less than or equal to txtValue <= 20

<> Not equal to txtPrice <> 10

9.4.3. Logical operators

Operator Operation
Not Negation
And / AndAlso Logical and
Or/ OrElse Logical or
Xor Exclusive Or
AND: An expression has a true value if both operands are true, and false value elsewhere
OR: An expression has a true value if at least one of the operand is true and false elsewhere.
Xor: An expression has a true value if both operand are different and has a false value if both operands are the same.
NOT: Negates Boolean operand
Table: Implementation of Logical Not operators
Operand Logical Not expression
X Logical Not operator Output of expression
True Not X False
False Not X True
Table : Implementation of logical And,Or and Xor operators

Operands Logical expressions


X Y Logical And Logical Or Logical Xor
True True X And Y True X Or Y True X Xor Y False
True False X And Y False X Or Y True X Xor Y True
False True X And Y False X Or Y True X Xor Y True
False False X And Y False X Or Y False X Xor Y False

The following example of VB program illustrates the Not ,And,Or,and Xor operators
The output of the above source code is:
Private Sub Form_Load()
[Link]
Dim a, b, c, d, e, f, g, x, y As Boolean
x = Not 23 > 14
y = Not 23 > 67 ' The preceding statements set x to False and y to True a = 23 > 14 And 11 > 8
b = 14 > 23 And 11 > 8 ' The preceding statements set a to True and b to False. c = 23 > 14 Or 8 > 11
d = 23 > 67 Or 8 > 11 ' The preceding statements set c to True and d to False. e = 23 > 67 Xor 11 > 8
f = 23 > 14 Xor 11 > 8
g = 14 > 23 Xor 8 > 11 ' The preceding statements set e to True, f to False, and g to False.
Print x

- 177 -
Print y
Print a
Print b
Print c
Print d
Print e
Print f
Print g
End Sub

Note that The AndAlso Operator is very similar to the And operator, in that it also performs logical conjunction on
two Boolean expressions. The key difference between the two is that AndAlso exhibits short-circuiting behavior. If
the first expression in an AndAlso expression evaluates to False, then the second expression is not evaluated because
it cannot alter the final result, thus AndAlso returns False.
Similarly, the OrElse Operator performs short-circuiting logical disjunction on two Boolean expressions. If the first
expression in an OrElse expression evaluates to, then the second expression is not evaluated because it cannot alter
the final result, and OrElse returns True.

9.4.4. Bitwise operators


Bitwise operations evaluate two integral values in binary (base 2) form. They compare the bits at corresponding
positions and then assign values based on the comparison. Bitwise operators are similar to logical operators only that
they are specifically used to manipulate binary digits.
Table 9.12: Bitwise operators

Operator Description
Not Bitwise Not
And Bitwise And
Or Bitwise Or
Xor Bitwise exclusive Or (Xor)
Example:
Consider the expression below:
x = 5 Or 6
5 in binary form =101
6 in binary form =110
101 And 110=110

- 178 -
 The bitwise And operator compares the binary representations, one binary position (bit) at a time. If both bits at a
given position are 1, then a 1 is placed in that position in the result. If either bit is 0, then a 0 is placed in that position
in the result. The result is treated as decimal. The value 100 is the binary representation of 4, so x = 4.
The bitwise Or operator takes a 1 and assigns to the result bit if either or both of the compared bits is 1.

Example:
Consider the expression below:
x = 5 Or 6
101 (5 in binary form)
110(6 in binary form)
111(The result, in binary form)
The result is treated as decimal. The value 111 is the binary representation of 7, so x =7.
 Bitwise Not takes a single operand and inverts all the bits, including the sign bit, and assigns that value to the result.
This means that for signed positive numbers, Not always returns a negative value, and for negative numbers, Not
always returns a positive or zero value.
Example:
Dim x As Integer
x = Not 5
101 (5 in binary form) , its negation is 010
The result is treated as decimal. The value 010 is the binary representation of 2, so x =2.
Bitwise Xor assigns a 1 to the result bit if exactly one of the compared bits (not both) is 1.
Example:
Dim x As Integer
x = 5 Xor 6
101 (5 in binary form)
110 (6 in binary form)
011 (The result, in binary form)

The result is treated as decimal. The value 011 is the binary representation of 3, so x =3.
 The AndAlso and OrElse operators do not support bitwise operations. The following example of VB program
illustrates the use of bitwise operators
Private Sub Form_Load() [Link]
Dim x, y, z, w, v, s As Integer
x=5
y=7
s = Not x
z = x And y
w = x Or y
v = x Xor y
Print " The value of s is:"; s
Print " The value of z is:"; z
Print " The value of w is:"; w
Print " The value of v is:"; v
End Sub
Output is as follow:

- 179 -
[Link] of operators
When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called
operator precedence.
Precedence Rules:
When expressions contain operators from more than one category, they are evaluated according to the following rules:
 The arithmetic and concatenation operators have greater precedence than the comparison, logical, and bitwise
operators.
 All comparison operators have equal precedence, and all have greater precedence than the logical and bitwise
operators, but lower precedence than the arithmetic and concatenation operators.
 The logical and bitwise operators have lower precedence than the arithmetic, concatenation, and comparison
operators.
 Operators with equal precedence are evaluated left to right in the order in which they appear in the expression
Just like in BODMAS, the order of precedence can be changed by use of parenthesis.
Table : Operator precedence

Operator Description Precedence Highes


^ Exponentiation Left to right t
* Multiplication Left to right
/ Division Left to right
Mod Modulus Left to right
+ Addition Left to right
- Substraction Left to right
& String concatenation Left to right
= Equal to Left to right
<> Not equal to Left to right
< Less than Left to right
> Greater than Left to right
<= Less than or equal to Left to right
>= Greater than Left to right
Not Logical not Left to right
And,And Also Logical and Left to right
Or,OrElse Logical and Left to right
Not Bitwise Not Left to right
And Bitwise And Left to right
Or Bitwise Or Left to right
Xor Bitwise Xor Left to right
= Assignment Right to left

Lowest
Note that:
 The string concatenation operator (&) is not an arithmetic operator, but in precedence it is grouped with the
arithmetic operators.
 When operators of equal precedence appear together in an expression, for example multiplication and
division, the compiler evaluates each operation as it encounters it from left to right.
The following example illustrates this.
Private Sub Form_Load()
[Link]

- 180 -
Dim x, y, z As Integer
x = 96 / 8 / 4 - 8 * 4 / 2
y = (96 / 8) / (4 - 8) * 4 / 2
z = 96 / (8 / 4) - 8 * 4 / 2
Print " The value of x is:"; x
Print " The value of y is:"; y
Print " The value of z is:"; z
End Sub
Output:

9.5. Decision structures in Visual Basic


The control structures are used to control the flow of execution of a program they are used in a program to repeat a set
of operations (looping control structures), and for making decisions according to the conditions when a program is
executing (decision control structures).
A decision structure will test a condition and then perform operations depending on whether yes or not the condition is
met (True or false).
9.5.1Types of decision control structures
Decision control structures also known as selection control statements are conditional logic used when there is one or
more options or alternatives to choose from.
There are four types of decision control structures namely if…then, if…then else, nested if ….then else, and select
case.
a)If ….. Then statement
If …. Then statement is used for making a decision in program.
The If...Then selection structure performs an indicated action only when the condition is True; otherwise the action is
skipped
The syntax of If ….Then structure is :
If condition Then VB statement(s) End If
Example: To set the Maths mark to grade “A” we can use the following statement:
If txtMaths >= 80 Then textGrade = “ A”
End if
b)If …..Then ….Else statement
The If...Then...Else selection structure allows the programmer to specify that different actions are to be performed
when the condition is True than when the condition is False. If the condition is true, the first part of the if …then is
executed.
However if the condition is false the block of the else statements is executed
The syntax of the If …Then …Else conditional statement is as follows:

- 181 -
If (Boolean expression/condition) Then
VB statement(s)
Else
VB statement(s)
End If
Example: a program to check whether the entered number is odd or even Dim n As Integer
a = Val([Link]) If n Mod 2 = 0 Then
[Link] = "The number you entered is even" Else
[Link] = "The number you entered is odd " End If
End Sub
We can also use the same example by using MsgBox function
x = val([Link])
If x Mod (2) = 0 Then
MsgBox "This is an even number you entered"
Else
MsgBox”you entered the odd number”
End If
c)Nested If ….Else statement
Nested If...Then...Else statement test for multiple cases by placing If...Then...Else selection structures inside
If...Then...Else structures
The syntax of the Nested If …Else:
If (Boolean expression/condition) Then
VB statement(s)
Else if (Boolean expression/condition) VB statement(s)
Else
VB statement(s)
End If
In using branching statements, be aware that each IF and Else If in a block is tested sequentially. The first time an If
test is met, the code associated with that condition is executed and the If block is exited. If a later condition is also
True, it will never be considered.

Example:
Write a program to read marks (per cent) of university students and put these students into classes according to their
marks.
Classes with their corresponding marks:
a. From 80 to 100: First class honours
b. From 70 to 79: Upper second class honours
c. From 50 to 69: Lower second class honours
d. From 40 to 49: Pass

- 182 -
e. Below 40: Fail
Solution: User interface

Source code
Private Sub check_Click()
Dim txtmarks As Integer
txtmarks = Val([Link])
If txtmarks >= 80 And txtmarks <= 100 Then
textClass = "The student got First Class Honours"
ElseIf (txtmarks >= 70 And txtmarks < 80) Then
textClass = "The student got Upper second class Honours"
ElseIf (txtmarks >= 50 And txtmarks < 70) Then
textClass = "The student got Lower second class Honours"
ElseIf (txtmarks >= 40 And txtmarks < 50) Then textClass = "The student got Pass"
ElseIf (txtmarks >= 40 And txtmarks < 50) Then textClass = "The student got Pass"
ElseIf (txtmarks >= 0 And txtmarks < 40) Then textClass = "The student got Fail"
Else
textClass = "Invalid input"
End If
End Sub
Private Sub clear_Click() txtmark = ""
textClass = ""
End Sub
Private Sub exit_Click() Unload Me
End Sub
Output:

Figure : Running program

- 183 -
d)Select case statement
Select...Case structure is an alternative to nested If...Then...Else for selectively executing a single block of statements
from among multiple block of statements. If the “case” matches the condition is selected and all instructions within the
matching case are executed. Select...case is more convenient to use than the If...Else...End If.
The general format is:
Select case expression
Case value 1
Block of visual basic statements
Case value2
Block of visual basic statements
Case value3
Block of visual basic statements
Case value4
Case Else
Block of visual basic statements
End Select
Each possible value of the item is checked using a Case statement followed by one or more Visual Basic statements
that will be carried out if there is a match for that value. The final part of the structure is usually a Case Else
statement to be executed if none of the above values match. This is useful for informing the user that he /she is out of
cases.
Example 1: A Visual Basic program that displays the Grade according to the marks entered by students:

0 - 10 U
11 - 20 S
21 - 30 F
31 - 40 E
41 - 50 D
51 - 60 C
61 - 74 B
75 - 100 A

Interface:

- 184 -
Source codes:
Private Sub Command1_Click()
Dim x As Integer
x = Val([Link]) Select Case x
Case 0 To 10
[Link] = "Grade U"
Case 11 To 20
[Link] = "Grade S"
Case 21 To 30
[Link] = "Grade F"
Case 31 To 40
[Link] = "Grade E"
Case 41 To 50
[Link] = "Grade D"
Case 51 To 60
[Link] = "Grade C"
Case 61 To 70
[Link] = "Grade B"
Case 71 To 100
[Link] = "Grade A"
Case Else
[Link] = "No Grade because you Entered Invalid marks"
End Select
End Sub
Private Sub Command2_Click ()
[Link] = ""
[Link] = "" End Sub
Private Sub Command3_Click ()
Unload Me
End Sub
Output:

Figure : Running Program


Example 2: Application to assign grade (comment) to students depending upon the marks they’ve got.
Dim x As Single
Private Sub Compute_Click()

- 185 -
x = [Link]
Select Case x
Case 0 To 49
[Link] = "Need to work hard"
Case 50 To 59
[Link] = "Average"
Case 60 To 69
[Link] = "Above average"
Case 70 To 79
[Link] = "Good"
Case Else
[Link] = "Excellence"
End Select
End Sub
User interface

VB source code
Dim x As Single
Private Sub check_Click() x = [Link]
Select Case x Case Is >= 100
[Link] = "Wrong input!"
Case Is >= 80
[Link] = "Excellence [Link] it Up!"
Case Is >= 70
[Link] = " Very Good!"
Case Is >= 60
[Link] = "Above average!"
Case Is >= 50
[Link] = "Average student!"
Case Is >= 0
[Link] = "You need to work harder!"
Case Else
[Link] = "Wrong input!" End Select
End Sub
Private Sub clear_Click() mark = ""
textGrade = ""
End Sub
Private Sub exit_Click() Unload Me
End Sub

- 186 -
Output:

9.6Repetition structures
Repetitions also known as iterations or loops are structures that allow a statement or group of
statements to be carried out repeatedly while some conditions remain true (or for a specified number of times)
They are two basic iteration structures:
[Link]-test iterations: in these loops, the condition to be met occurs at the beginning of the loop and the code
will not run at all if the condition is never met. This can be implemented using: For … Next, Do While ….
Loop, Do Until … Loop and While … Wend loop
[Link] –test iterations: in these loops, the condition to be met is at the end of the loop so that the code
always runs at least once. This can be implemented using the: Do … Loop While, Do … Loop Until
Visual Basic supports two types of loops which are indeterminate loops and determinate loop
9.6.1 Indeterminate loops
These are loops which repeat until a predetermined goal is achieved. Repeating until some initial conditions change.
The Indeterminate loops supported in VB are the following:
(i) Do While … Loop
The general format is:
Do while (condition) VB statement(s) Loop
When Visual Basic executes this Do While … Loop, it first tests condition. If condition is False, it skips past all the
statements. If it’s True, Visual Basic executes the statements and then goes back to the Do while statement and tests
the condition again. Consequently, the loop can execute any number of times, as long as condition is True. The
statements never execute if initially is False. Example: a visual basic program to find the sum of number from 0 to
100
Private Sub Form_Load()
[Link]
Dim num As Integer, Total As Integer num = 0
Total = 0
Do While num <= 100
Total = Total + num num = num + 1
Loop
[Link] = Total End Sub

- 187 -
Output:

(ii)Do Until … Loop


Unlike the Do While...Loop and While...end loop structures, the Do Until... Loop structure tests a condition for
falsity. Statements in the body of a Do Until...Loop are executed repeatedly as long as the loop-continuation test
evaluates to False.
The general format is:
Do until condition
Block of one or more statements
Loop
Example: a simple program to find even numbers from 10 to 20
Private Sub Form_Load() [Link]
Dim number As Long number = 10
Do Until number >= 20 number = number + 2
Print number
Loop End Sub
The outpout is as follow:

(iii)While …. Wend
A While...Wend statement behaves like Do While...Loop statement. It executes a set of VB statements till the
condition evaluates to true.

The general format is:


While condition
One or more VB statements
Wend
For example: Generate the sum of first 10 integers

- 188 -
Private Sub Form_Load ()
[Link]
Dim I As Integer, Sum As Integer I = 0
Sum = 0 While I <= 10
Sum = Sum + I I = I + 1
Wend
Print “The sum of first 10 integers is”; Sum End Sub

The outpu of above code

(iv)Do … Loop While


The Do...Loop While statement first executes the statements and then test the condition after each execution.
Syntax :
Do
Block of one or more VB statements
Loop While condition
For Example: Loop counts from 1 to 20 using do .......... loop while
Private Sub Command1_Click()
Dim number As Long
number = 0
Do
number = number + 1
Print number
Loop While number < 20
End Sub

- 189 -
The output of above source code is as follow: The programs executes the statements between Do and Loop
While structure in any case.
Then it determines whether the number is less than 20.
If so, the program again executes the statements between Do and Loop While, else exits the Loop.
(v)Do … Loop Until
The general format is:
Do
Block of one or more VB statements Loop Until condition
Example: program to count multiples of three up to 15
Private Sub Form_Load()
[Link]
Dim Counter =0 As Integer
Do
Counter = Counter + 3
Print Counter
Loop Until Counter = 15
End Sub
The output of above source code is as follow:

9.6.2 Determinate loop


This loop repeats a set of operations a fixed number of times. The common used terminate loop is
For ….next loop.
The general format is:
For variable = start To end
VB statements to be repeated
Next variable
In this syntax statement, For, To, and Next are required keywords, and the assignment operator is required. First, you
replace variable with the name of a numeric variable that keeps track of the current loop count. Next, you replace
start and end with numeric values that represent the starting and stopping points for the loop. The line or lines
between the For and Next statements are the instructions that repeat each time the loop executes.
Example 1: Suppose you want to print the numbers from 1 to 10.
The following lines of codes can be used in procedure.
Private Sub Form_Load()
Dim i As Integer
[Link]
For i = 1 To 10 ‘step1 is by default
Print i
Next i
End Sub
Output:

- 190 -
Example 2: VB application to display the multiplication tables of 5
User interface:

Source code:
Private Sub Command1_Click()
Dim a As Integer
a = Val([Link])
For i = 1 To 10
Print a; "*"; i; "="; a * i
Next i
End Sub
Private Sub Command2_Click()
[Link] = ""
[Link]
End Sub
Private Sub Command3_Click()
Unload Me
End Sub

- 191 -
Output:
Note:

Creating Loops with a Custom Counter


You can create a loop with a counter pattern other than 1, 2, 3, 4, and so on. First, you specify a different start value in
the loop. Then, you use the Step keyword to increment the counter at different intervals.
In this case the syntax for a For...Next loop looks like the following:
For counter = initial To End
Step [Increment]
One or more VB statements
Next [counter]
The arguments counter, start, end, and increment are all numeric. The increment argument can be either positive or
negative.
If increment is positive, start must be less than or equal to end or the statements in the loop will not execute. If
increment is negative, start must be greater than or equal to end for the body of the loop to execute.
If step isn’t set, then increment defaults to 1.
Example: Print the numbers from 1 to 50 by the increment of 3
Private Sub Form_Load()
[Link]
Dim intnum As Integer
For intnum = 1 To 50 Step 3
Print intnum
Next intnum
End Sub
The VB source code above prints this sequence of numbers: 1 4 7 10 13 16 19 22 25 28 31 34 37
40 43 46 49
Specifying Decimal Values
You can also specify decimal values in a loop.
For example:
For i = 1 To 2.5
Step 0.1
Print i
Next i

- 192 -
The program above prints this sequence of numbers as follow:

Note that:
The exit statement allows you to exit directly from For Loop and Do Loop. Exit For can appear as many times as
needed inside a For loop, and Exit Do can appear as many times as needed inside a Do loop (the Exit Do statement
works with all versions of the Do Loop syntax).
Sometimes the user might want to get out from the loop before the whole repetitive process is executed; the command
to use is Exit For to exit a For Next Loop or Exit Do to exit a Do…
Loop, and you can place the Exit For or Exit Do statement within the loop.
The exit keyword in loop control statement is used as break Jump control statement in other programming languages
to terminate prematurely the loop.
a) Exit For The format is:
for counter= start To end step (increment) Statements
Exit for Statement Next counter
Example:
Private sub Form Load_( )
[Link]
Dim n as Integer
For n=1 to 10
If n > 6
Then Exit For
Print n
Next n
End Sub
Output: 1 2 3 4 5 6
b) Exit Do The format is:
Do While condition Statements
Exit Do Statements Loop
Example:
Private sub Form _Load( )
[Link]
Dim x As Integer
X=0
Do While x < 10
Print x
x=x+1
If x = 5 Then
Print "The program is exited at x=5"
Exit Do
End If Loop
End Sub
The output: 0 1 2 3 4 the program is exited at x=5
c)Nested Loops

- 193 -
The nested loops are the loops that are placed inside each other.
The most inner loop will be executed first, then the outer ones.
Nested loops are very useful when there is a requirement to generate different kinds of patterns as output.
Example: Program to generate the output given below:
1
22
333
4444
55555
Solution:
Private Sub Form_Load()
[Link] = 24
For i = 1 To 5
For j = 1 To i
[Link] = [Link] + Str(i) + " "
Next j
[Link] = [Link] + vbCr
Next i
End Sub
d)For Each loop
The For Each loop is a scope that defines a list of statements that are to be repeated for all items specified within a
certain collection/array of items. The For Each loop, as compared to the For loop, can’t be used to iterate from a range
of values specified with a starting and ending value. Syntax of a For Each Loop:
For each variable in Items Vb codes
Next variable
Where:
Variable is the iterating variable which is used to iterate through the elements of the collection or array
Items: a collection or array of items
Next: closing statement for the loop. Optionally you can specify the Iterator variable
Example: a program to display elements of the list Private
Sub Form_Load()
[Link]
Dim x(7) As Long, a As Variant
x(0) = 30
x(1) = 40 The output is:
x(2) = 50
x(3) = 60
x(4) = 70
x(5) = 80
x(6) = 90
x(7) = 100
For Each a In x
Print a
End Sub

- 194 -
[Link] TO VISUAL BASIC
8.1. Understanding Visual Basic.
8.1.0. General introduction
VISUAL BASIC is a high level and Event-driven Programming Language which evolved from the
earlier Disk Operating System (DOS) version called BASIC. (BASIC means: Beginners' All- purpose
Symbolic Instruction Code)
Visual basic for DOS and Visual Basic for Windows were introduced in 1991 and evolved through the
Visual basic 6.0 version released in 1998.
Visual basic 6.0. has the following advantages:
 It is easier for the user to minimize code writing.
 The user will become more familiar with visual approach for other visual languages.
 It provides Input box and Output box as interactive windows with user.
 It is very easy program language compare with others.
 The VB –IDE has been highly optimized support rapid application development (“RAD”). It is
particularly easy to develop graphical user interfaces.
 VB provides a comprehensive interactive and context-sensitive online help system.
 Visual basic is built around the .NET environment used by all Microsoft Visual language, so the
is a very little that can’t done in Visual Basic that can be done in other languages (such as C#).
Visual basic 6.0. has the following disadvantages:
 Visual Basic is a proprietary programming language written my Microsoft, so program written in
Visual Basic cannot be easily transferred to other operating system
8.1.1. Definition of terms
a) Graphical User Interface.
A graphical user interface (GUI) is an interface through which a user interacts with electronic devices
such as computers, hand-held devices and other appliances. GUI representations are manipulated by a
pointing device such as a mouse, trackball, stylus, or a finger on a touch screen.
Graphical user interface (GUI) is different from command line interface (CLI) or command language
interpreter as command line interface (CLI) enables users to type commands in a terminal or console
window to interact with an operating system.

Figure . Graphical User Interface (GUI) created using VB

- 136 -
b) Desktop application
A desktop application is a computer program that runs locally on a computer device, such as desktop or
laptop computer, in contrast to a web application, which is delivered to a local device over the Internet
through browser from a remote server.
Difference between desktop and web applications.
i) Desktop applications
 They must be developed for and installed on a particular operating system.
 Have strict hardware requirements that must be met to ensure that they function correctly.
 Updates to the applications must be applied by the user directly to their installation and may require
hardware upgrades or other changes in order to work.
ii) Web applications
 A web application is any computer program that performs a specific function by using a web
browser.
 The user accesses the application using the web browser and works with resources available over
the internet, including storage and CPU processing power.
 This approach allows for “thin clients” (machines with limited hardware capabilities) to provide
access to complex applications delivered from a centralized infrastructure.
c) Event oriented programming.
In computer programming, event-driven programming is a programming paradigm in which the flow of
the program is determined by events such as user actions (mouse clicks, key presses, SetFocus,
KeyDown,etc…),
Event oriented programming using Visual Basic
Visual Basic is Event oriented programming because of the following:
 The programmer needs to write code that performs some tasks in response to certain events.
 Has events that occur by mouse clicking and moving or keyboard stokes (Some of the events are
load, click, double click, drag and drop, pressing the keys and more.)
 Focus on the use of Graphical User Interface.
 The events usually comply but not limited to the user’s inputs.
8.1.2. The Features of Visual Basic
Visual Basic has the following features:
1. Data Access Features: this allows programmers to develop database front end applications and
server side components for most popular database formats including MS SQL and other Databases.
2. Active X Technologies: that allows programmers to use the functionality provided by other
applications, such as MS Office and other windows applications.
3. Internet capabilities make it easy to provide access to documents and applications across internet
server applications.
4. Your finished application is a true executable (.exe) file that uses a visual Basic Virtual Machine
that you can freely distribute.
8.1.3 Standard EXE Visual Basic Application
Using Visual Basic one can develop one of these main projects as indicated in the screen below:

- 136 -
Figure . The highlighted is standard EXE project which we are emphasising in this unit.

Standard Exe project is a typical application in which can use the database manipulation.
It is the most widely used Project type using VB6. Standard EXE application is normally the most
widely used among the available Project types in Visual Basic. Stand-alone programs have an .EXE file
extension. A standard EXE application is normally used when you want to develop a stand-alone
application. Examples include calculators, text editors, and other similar applications.
8.1.4. Starting VB 6.0
Opening application of visual basic 6.0
On start up, Visual basic 6.0 will display a dialog box, and one can choose to start a new project, open a
new existing project, or select a list of recently opened programs.

Figure . Dialog Box of VB 6.0 for project creation.

- 137 -
8.2 .Visual Basic Integrated Development Environment (VB-IDE)
IDE(Integrated Development Environment)is a term commonly used in the programming world to
describe the interface and environment that we use to create our applications. It is called integrated
because we can access virtually all of the development tools that we need from one screen called an
interface.
The IDE is also commonly referred to as the design environment.
The visual basic IDE is made up of the following components
 Menu Bar
 Project Explorer
 Form Layout Window
 Form Designer
 Tool Bar
 Properties Window
 Tool Box
 Object browser

Figure. components of VB 6.0 Standard EXE IDE.


This is the main IDE window of Visual Basic. The following are components of the standard
[Link].
8.2.1. Form window
The form designer is the main window in the middle of the screen, in which we can design and edit user
interface. The same window displays a text editor in which we can enter and edit
applications code.

- 138 -
8.2.2. Tool Box
The Toolbox contains a set of controls that are used to place on a Form at design time thereby creating
the user interface area. A Toolbox is represented in figure shown below.

Figure . VB 6.0 toolbox


8.2.3. Code window or VB Editor

Each standard form has a code window in which the user can write to direct the behavior of a control.
You open the code window by double clicking on a form or a control. If you double click a form, you
will be taken to a procedure for the form, but once the code window is open, you can go to any
procedure for any object on the selected form.
The codes are of two Categories:
 Declaration is written before any procedure in the code window.
 Statements. The user selects the required event then code statements are written inside these event
procedures.

- 139 -
8.2.4 Project explorer

On the right side of the form design, just under the tool bar, is the Project Explorer window. The Project
Explorer as shown in below figure serves as a quick reference to the various elements of a project
namely form, classes and modules.
8.2.5 Properties Window
Properties are the attribute of controls. Every object has properties, for example a Pen, has its Color,
Metal Type, Ink Color, Type etc. Some properties are read only, which means the values of such
properties can’t change using code, while others are Read and Write. You can move Property window
any side of VB IDE Window, can appeal using tool bar or by Pressing F4.
The Properties window displays the properties of various controls and objects that are created in your
applications. Each and every form in an application is considered an object.

8.2.6 Form Layout Window


The Form Layout window is a visual design tool which is used to control the placement of the forms in
the windows environment when they are executed especially when you have more than one form in your
program,
To position a form in the Form Layout window, simply drag the miniature form to the desired location
in the window.

- 140 -
8.2.7. Menu Bar
This is where you can select actions to perform on all your project files and to access help. When a
project is open extra menus of project, build and data, are shown in addition to the default menu
selection of File, edit, View, Debug, tools, window and Help.

8.2.8. Toolbar
It gives easy access to the menu-bar you use frequently
8.2.9. Object Browser

Object browser allows us to browse through the Various Properties events and methods that are made
available or exposed.
8.3. Visual basic controls
 A control: is a tool you use to create objects on a Visual Basic form. You select controls from the
toolbox and use the mouse to draw objects on a form. You use most controls to create user interface
elements, such as command buttons, image boxes, and list boxes.
 Properties of a control.
Before writing an event procedure for the control to respond to an event, you have to set certain properties
for the control to determine its appearance and how it will work with the event procedure. You can set the
properties of the controls in the properties window or at design time.

Other things you can do are to change its foreground and background color, change the font type and font
size, enable or disable minimize and maximize buttons etc.
Here are the important points about setting up control properties:
 Caption Property of a control should be clearly defined so that a user knows what to do with control
 Use a meaningful name for property as it is easier to write and read the event procedure and easier
to debug or modify the program later.
 One more important property is whether to make the control enabled or not.
 You should also consider making the control visible or invisible at design time, or when should it
become visible or invisible.
The following are common controls used in Visual Basic:
8.3.1 Form

Form is used when you start Visual Basic, a default form (Form1) with a standard grid (a window
consisting of regularly spaced dots) appears in a pane called the Form window. You can use the Form
window grid to create the user interface and to line up interface elements.

- 141 -
Steps to create Form
Step 1: Click Project on menu and choose Add form from the list of options

Step 2: Click Form and click Open

Step 3: Set the Properties for a form


 Name: Enter the name of the form. It returns the name used to identify form.
 Enabled: form controls can be enabled or disabled on initial execution with the enabled
property.
 Appearance: It sets whether or not object is painted at run time with 3D effects.
 Caption: Enter the caption associated with the form. It sets the text displayed as the title of the
form.
 Backcolor: Choose background color of textbox .It sets the background color used to display
textbox.
 Borderstyle: Choose border style of the form
 Fillcolor: It sets the colour used to fill in shapes,circles and boxes.
 Fillstyle: It returns the fill style of a shape
 Backstyle: Choose background style; Opaque or transparent
 Font: It returns the font of a form.

- 142 -
 Scaleheight: It sets the number of units for the vertical measurement of form.
 Scaleleft: It returns the horizontal coordinates for the left edge of form.
 Visible shows or hide a control on a form. It sets value that determines whether an object is
visible or hidden.
8.3.2. Label
Label displays a text on the form. Labels are commonly used to identify the controls. The text in
the label control can be changed by changing the caption property. The table below summarizes how a
label can be used.
The following are the steps to add a label on the form. Step 1: Click on the label icon on the toolbox
Step 2: Drag and drop a label control in the form
Step 3: Set Properties for label
 Name: Enter the name of the label control. It returns the name used to identify object.
 Alignment: It returns/sets the alignment of a label
 Appearance: It sets whether or not object is painted at run time with 3D effects.
 Caption: Enter the caption associated with the label. It sets the text displayed on the form.
 Font: It returns the font of object (font face, font style, size and effects)
 Forecolor: It returns foreground color of a label
 Height: Enter the height of the label.
 Backcolor: Choose background color. It sets the background color used to display label.
 Borderstyle: Choose border style of the label(None-no border or Fixed Single-With border)
 Backstyle: Choose background style; Opaque or transparent

Figure . Labels drawn on form


8.3.3. Text Box

Text box is a box for entering and displaying text (characters or values) in user project. This tool is
used frequently in most of the application.

Steps to add Textbox


Step 1: Click on the Textbox icon on the toolbox
Step 2: Drag and drop a Textbox control in the form
Step 3: Set Properties for Textbox such as Name, alignment, appearance, backcolor etc.
- 143 -
8.3.4. Frame
If you want to create a group of controls that work together, you must first create a frame for the
controls. (To do this, use Frame, a Visual Basic toolbox control.) Next, place your controls inside the
frame so that they can be processed as a group in your program code and moved as a group along with
the frame
Steps to add Frame
Step 1: Click on the Frame icon on the toolbox Step 2: Drag and drop a Frame control in the form
Step 3: Set Properties for Frame: on this step, you set preferred properties

8.3.5. Radio Buttons/ Option Buttons


Option Button control is a part of an option group allows the user to select only one option even it
displays multiple choices.
Unlike check boxes, selecting one option button immediately clears all the other buttons in the group.
Steps to add Option Button
Step1:Click on the optionButton icon on the toolbox
Step 2: Drag and drop an OptionButton control in the form
Step 3: Set Properties for Option Button

- 144 -
[Link] buttons grouped in a frame
8.3.6. Check box control
Is similar to the OptionButton control, except that Checkbox displays a list of choices and gives the
user the option to pick multiple items (or none at all) from a list of choices.
You create a check box on a form much as you would make an option button. Start by clicking the
Checkbox control in the toolbox, and then draw on the form. If you want to create a group of check
boxes that work together, create a frame for the buttons with Frame, a toolbox control.
Then, you can place your check boxes inside the frame so that they can be processed as a group in your
program code or moved as a group along with the frame.
Steps to add CheckBox
Step 1: Click on the CheckBox icon on the toolbox
Step 2: Drag and drop a CheckBox control in the form
Step 3: Set Properties for CheckBox

8.3.6. Command button


Command button Is a very important control as it is used to execute commands. It displays an illusion
that the button is pressed when the user clicks on it. The most common event associated with the
command button is the Click event.

- 145 -
8.3.7 List Box
List Box contains a list of options from which user can choose. In windows the Font List box is
an example of the use of a list box. The Selected item in a ListBox is given by the Text property.
The sorted property determines whether the items in the list box will be sorted or not.

Adding items to list


a) Change property list from properties window: Open the list properties window and choose list
property. Write a list of items to appear in the list box

- 146 -
[Link] items to list.
8.3.8 Combo Box
The function of a Combo Box is to present a list of items where the user can click and select the items
from the list. However, the user needs to click on the small arrowhead on the right of the combo box to
see the items which are presented in a dropdown list.
Figure 8.25 Combo box
8.3.9. Picture Box

Picture Box is a control used to display images on a VB page. The Picture Box control also supports
few functionality of generating advanced drawing.
8.3.10. Imagebox
The Image Box is another control that handles images and pictures. It functions almost identically
to the picture box. However, there is one major difference, the image in an Image Box is
stretchable, which means it can be resized. This feature is not available in the Picture Box. The syntax
is as follows:
8.3.11. Timer
When we need to perform tasks at regular interval we can use Timer . Open a new project and place a
timer object on your form. Then locate a label at the center of the form and adjust the size
as shown in the figure below. For such a program a better look will be established by sizing your form
- 147 -
as a pop up window.

8.3.12. File System Controls


File System Controls are set of controls which help us to add file handling capabilities to our program.
They are used together to provide an interface for accessing and exploring drives, folders and files. File
system controls can be drive list box, directory list box and file list box.
a) Drive List Box: The Drive ListBox is for displaying a list of drives available in your computer.
When you place this control on the form and run the program, you will be able to select different
drives from your computer.

Figure . Use of DriveList control


b) Directory List Box: is for displaying the list of directories or folders in a selected drive. When
you place this control into the form and run the program, you will be able to select different
directories from a selected drive in your computer.
c) File List Box: This control displays a list of files in the current folder. These are important
controls even though there are plenty of controls used in VB.

- 148 -
8.3.13. ADO
ADO (ActiveX Data Objects) is the preferred method for accessing non-Jet [Link] is native to Jet,
and on several operations, it might perform a bit faster on Jet than ADO. DAO will contain some
methods and properties that are only relevant to Jet, not other databases.
8.3.14. DAO
DAO (Data Access Objects) was the first object-oriented interface that exposed the Microsoft Jet
database engine (used by Microsoft Access) and allowed Visual Basic developers to directly connect to
Access tables as well as other databases - through Open Database Connectivity (ODBC).
8.4. Planning and Developing a Visual Basic program.
8.4.1 The process of Planning and Developing a Visual Basic program
There are three steps involved in building a visual basic application:
 Draw the user interface
 Assign properties to controls
 Attach codes to control
a. Draw the interface
This step consists of designing the application’s user interface using controls,the controls are taken from
the toolbox by dragging them from there to the form designer.
b. Assign properties to control
At this stage, user need to set set up properties for the created form and controls. Those properties are
set from the properties window.
c. Write the event code.
Coding is to be done in the code window and you get there by double clicking a form or control in the
form.
Now we double click on the form1, the source code Window for the form1 appears as shown below:
Private Sub Form_Load()
VB statement(s)
End Sub
You just have to write your code between the two statements. To display the output, you have to
add Form_name.show in order to display the statements or message written on the form.

- 149 -
Example 1: VB application to display the message: “welcome to the world of programming:”

Private sub Form_load()


[Link]
Print"welcome to the world of programming"
End sub.

Example 2: application to display date, time and message


Codes: Output:

Private Sub Form_Load()


[Link]
Print " my message"
Print " today’s date is:" & Date
Print " and the time is: " & Time
Print " thanks and bye."
End Sub

Example 3: Build an application program to calculate the volume of the cylinder


1) First build the interface as it is shown on the right side

2) Procedure:
 Put the pointer on the form 1, right button, properties, go to name and replace form1 by
frmvolumecylinder.
 Go to caption; and replace form1 by Volume of cylinder
 Go now to toolbox, then choose label (3 times) and if toolbox is not there, go to view then
choose toolbox
 Click once on the label one, right button; properties and replace label1 name by lblradius
- 150 -
and the caption by the "Radius”
 Click on the label2, properties and replace the label2 name by lblheight and the caption
by “Height”
 Click on label3, properties and replace the name by lblarea and caption by “Volume”.
 Then go to toolbox, choose now the textbox (3 times) starting by the first, go to properties and
remove.
 Go to text name and replace the text1, text2 and text3 by txtradius, txtheight and txtvolume
respectively.
 Go back to toolbox and choose command buttons (3 times)
 Go to properties and replace names command1, command2 and command3 by cmdcalculate,
cmdnew and cmdexit respectively captions by Calculate, Newcalculation and Exit.
3) Command “Calculate”
 Double click on command button "Calculate" to write the code to calculate the area when you
click on it at running time.
Codes:
Private Sub cmdcalculate_Click()
[Link] = 3.14 * Val([Link] ^ 2) * Val([Link])
End Sub
4) Command “New Calculation”
Double click on the command New calculation to write the code to let you make other calculation when
click on it.
Codes:
Private Sub cmdnew_Click() [Link] = ""
[Link] = ""
[Link] = ""
End Sub

5) Command “Exit”
 And finally Exit command to write the code to end the program when you click on it.
Codes:
Private Sub cmdexit_Click() Unload Me
End Sub
Output:

[Link] form (Volume of Cylinder)

- 151 -
8.4.2. Debugging Your Code and Handling Errors
A. Debugging
 Debugging is a process by which you find and resolve errors in your code. To debug code in
Visual Basic, consider the ideas suggested below. These techniques can also be applied in different
sequences.
 Print the code, if you find it easier to read code on paper instead of softcopy.
 Run the application to find trouble spots:
From the Run menu, choose ‘Start’ to begin running the application. Run until an error stops execution,
or halt execution manually when you suspect an error by choosing ‘Break’ from the Run menu. Resolve
all compile errors and run-time errors. From the Run menu, choose ‘Continue’ to continue running the
application.
Once bugs are found Try out bug fixes and then make edits by testing individual lines of new or
debugged code in the Debug window. Search and replace code for all occurrences of an error, checking
other procedures, forms, or modules with related code. From the Run menu, choose ‘Restart’ to reset
application variables and properties and restart the application from the beginning.
 Debugging tools.
These are tools designed to help in stopping the execution of a program at specific points, detecting run-
time and logic errors and understanding the behavior of error-free code.
B. Handling errors
Error handling should be used to process only exceptional situations, despite the fact that there is
nothing to prevent that programmer from using errors as an alternate form of program control.
These errors can be grouped into three categories:
- Syntax errors
- Run-time errors
- Logic errors
 Syntax errors are grammatical errors in the formulation of statements and are picked up by the
interpreter while you are typing in the code
 Run-time errors these are errors that cannot be detected until the program is running. The syntax of
the statements is correct, but once executed they cause a error situation to arise. Examples of run-
time errors are attempted division by zero or trying to access a non-existent object.
 Logic errors these are errors or bugs that cause the program to behave incorrectly. A logic error
produces unintended or undesired output or other behavior, although it may not immediately be
recognized. This is why careful testing is so important.
8.4.3. Building an executable file
You can make an executable file (.exe) from Visual Basic using the following procedure.
To make an executable file in Visual Basic
1. From the File menu, choose Make projectname .exe where projectname is the application name
for the project.
2. Type a file name, or browse through the directories and select an existing file name to overwrite
an existing executable with a newer version.
3. By clicking the Options button, you can also specify a number of version-specific details about
the executable file in the Project Properties dialog box.
4. If you want to modify the version number of the project, set the appropriate Major, Minor, and
Revision numbers.
Selecting Auto Increment will automatically step the Revision number each time you run the
Make projectname .exe command for this project.
5. To specify a new name for the application, under Application, type a new name in the Title
box. If you want to specify a new icon, choose one from the list.
6. You can also enter version-specific commentary on a variety of issues under the Version
- 152 -
Information box (comments, company name, trademark and copyright information, and so on)
by selecting a topic from the list box and entering information in the text box.
7. Choose OK to close the Project Properties dialog box, and then choose OK in the Make
appname .exe dialog box to compile and link the executable file.
You can run the executable file like any other Windows-based application: double-click the icon for the
executable file.
8.4.4. Deploying a VB Project
The Visual Basic Package and Deployment Wizard makes it easy for you to create the necessary cab
files and setup programs for your application.
There are three ways of starting the Package and Deployment Wizard:
 Run it from within Visual Basic as an add-in. If run the wizard as an add-in, first set the
necessary references in the Add-In Manager to load the wizard.
 It as a stand-alone component from outside the development environment. Run the wizards as a
stand-alone component, prompted choose the project on which working with.
 Start it in silent mode by launching it from a command prompt. "Running the Wizard in Silent
Mode" in this topic for more information.
After you start the wizard, a series of screens prompt you for information about your project and let you
choose options for the package. Each screen explains how it is to be used, including which information is
optional, and what information must be entered before move to the next screen. If it display information
on screen, press F1 or click the Help button.
Note Save and compile project before running the Package and Deployment Wizard..
To start the Package and Deployment Wizard from within Visual Basic
1. Open the project you want to package or deploy using the wizard.
Note If you are working in a project group or have multiple projects loaded, make sure that the
project you want to package or deploy is the current project before starting the wizard.
2. Use the Add-In Manager to load the Package and Deployment Wizard, if necessary: Select Add-
In Manager from the Add-Ins menu, select Package and Deployment Wizard from the list,
then click OK.
3. Select Package and Deployment Wizard from the Add-Ins menu to launch the wizard.
4. On the main screen, select one of the following options:
 If you want to create a standard package, Internet package, or dependency file for the
project, click Package.
 If you want to deploy the project, click Deploy.
 If you want to view, edit, or delete scripts, click Manage Scripts.
For an introduction to these options, see "The Package and Deployment Wizard."
5. Proceed through the wizard screens.
To start the Package and Deployment Wizard as a stand-alone component
1. If the project you want to package is open, save it and close Visual Basic.
2. Click the Start button, and then click Package and Deployment Wizard from the Visual Basic
submenu.
3. In the Project list on the initial screen, choose the project you want to package.
Note You can click Browse if your project is not in the list.
4. On the main screen, select one of the following options:
 If you want to create a standard package, Internet package, or dependency file for the
project, click Package.
 If you want to deploy the project, click Deploy.
 If you want to view, edit, or delete scripts, click Manage Scripts.
5. Proceed through the wizard screens.

- 153 -
- 135 -
136
UNIT 10: INTRODUCTION TO JAVA
[Link] of Java Programming
[Link]
Java is a computer programming language. It enables programmers to write computer instructions
using English-based commands instead of having to write in numeric codes. It is known as a high-level
language because it can be read and written easily by humans
[Link] of Java

Advantages Explanations
Simple Java is designed to be easy to learn. With the understanding of the
basic concept of OOP Java, it would be easy to master.
Secure With Java's secure feature, it enables to develop virus-free, tamper- free
systems. Authentication techniques are based on public-key encryption.
Architecture-neutral Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with
the presence of Java runtime system.
Portable Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is
written in ANSI C with a clean portability boundary, which is a POSIX
subset.
Robust Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime
checking.
Multithreaded With Java's multithreaded feature, it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the
developers to construct interactive applications that can run smoothly.
Interpreted Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and
analytical since the linking is an incremental and light-weight process.
High Performance With the use of Just-In-Time compilers, Java enables high
performance.
Distributed Java is designed for the distributed environment of the internet.
Dynamic Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment.

[Link] of JAVA Program


10.2.1 JRE & JDK & JVM
The Java platform is the name given to the computing platform from Oracle that helps users to run and
develop Java applications. The platform does not just enable a user to run and develop a Java application, but
also features a wide variety of tools that can help developers work efficiently with the Java programming
language.
The platform consists of two essential pieces of software:
 Java Runtime Environment (JRE): This is the environment within which the java virtual machine runs.
JRE contains Java virtual Machine (JVM), class libraries, and other files excluding development tools such as

- 199 -
compiler and debugger.
 Java Development Kit (JDK), which is needed to develop those Java applications and applets( a small
dynamic Java program that can be transferred via the Internet and run by a Java-compatible Web browser).
JDK contains everything that JRE has along with development tools such as compiler,debugger etc.
The Java platform consists of the Java Application Programming Interfaces (APIs) and the Java Virtual
Machine (JVM). Java APIs are libraries of compiled code that you can use in your programs.
Any computer system with the Java VM installed can run Java programs regardless of the computer system
on which the applications were originally developed.
For example, a Java program developed on a Personal Computer (PC) with the Windows NT operating
system should run equally well without modification on Macntosh computer running Mac OSx operating
system, and vice versa.
10.3 Write, Compile and run a java Program
10.3.1 Create a java program
The first application, HelloWorldApp, will simply display the greeting "Hello World!" To create this
program, the following steps must be respected
1) Create an IDE (Integrated Development Environment) project:
Creating an IDE project means creating an environment in which to build and run the applications. Using IDE
projects eliminates configuration issues normally associated with developing on the command line. Build or
running an application can be done by choosing a single menu item within the IDE.
a) Launch the NetBeans IDE.
o On Microsoft Windows systems, use the NetBeans IDE item in the Start menu.
o On Solaris OS and Linux systems, execute the IDE launcher script by navigating to the IDE's bindirectory
and typing. /netbeans.
o On Mac OS X systems, click the NetBeans IDE application icon.
b) Choose File | New Project....

Figure . NetBeans IDE with the File | New Project menu item selected.
In the New Project wizard, expand the Java category and select Java Application as shown in the
following figure:

- 200 -
[Link] IDE, New Project wizard, Choose Project page.
In the Name and Location page of the wizard, do the following (as shown in the figure below):
 In the Project Name field, type HelloWorldApp.
 In the Create Main Class field, type [Link].

 Then click the button Finish in the figure below.

[Link] java application window


The project is created and opened in the IDE. In the next figure, there are the main components of the

- 201 -
environment
 The Projects window, which contains a tree view of the components of the project, including source
files, libraries that the code depends on, and so on.
 The Source Editor window with a file called [Link] open.

 The Navigator window, used to quickly navigate between elements within the selected class.

Figure. NetBeans IDE with the HelloWorldApp project open


Add Code to the Generated Source File: A source file contains code, written in the Java programming
language, that programmers can understand. As part of creating an IDE project, a skeleton source file is
automatically generated and the source file is then modified to add the "Hello World!" message.
When this project was created, the Create Main Class checkbox was left selected in the New Project wizard.
The IDE has therefore created a skeleton class for the programmer. The "Hello World!" message is added to
the skeleton code by replacing the line:
// TODO code application logic here With the
line:
[Link]("Hello World!"); // Display the string. Optionally, you
can replace these four lines of generated code:
/**
*
* @author
*/With these lines:
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
These four lines are a code comment and are not affecting how the program runs. Later sections
of this unit explain the use and format of code comments.
Notice that Java programming is case sensitive. It means that “a” is different from “A”,

- 202 -
helloWorldApp is also different fromHelloWorldApp.
1. After adding the code, the remaining action is to Save the changes by choosing File | Save.
The file should look something like the following:
/* * To change this template, choose Tools | Templates* and open the template in the editor. */
packagehelloworldapp;
/**
* The HelloWorldApp class implements an application that
* Simply prints "Hello World!" to standard output.
*/
public class HelloWorldApp {
/**
* @paramargs the command line arguments
*/
public static void main(String[] args)
{
[Link]("Hello World!"); // Display the string.
}
}
10.4. Compile the Source File into a .class File
The IDE invokes the Java programming language compiler (javac), which takes the source file and translates
its text into instructions that the Java virtual machine can understand. The instructions contained within this
file are known as byte [Link] compile the source file, choose Run | Build Project (Hello World App)
from the IDE's main menu.
10.4.1 Running the Program
The IDE invokes the Java application launcher tool (java), which uses the Java virtual machine to run your
application.
From the IDE's menu bar, choose Run | Run Main Project. The result is displayed in the next figure.

Figure . Output for the “Hello World” java program


After successful compilation and run, the program prints "Hello World!" to the Output window (along with
other output from the build Scripts.

- 203 -
Figure . Hello world program
10.5 Elements of Java source file
10.5.1 .Syntax of a java program
class class_name
{
public static void main(String[] args)
{
// java code goes here
}
}
Explanation of the syntax
i. class : class keyword is used to declare classes in Java
ii. public : It is an access specifier. Public means this function is visible to all.
iii. static : static is again a keyword used to make a function static. To execute a static function you do not
have to create an Object of the class. The main() method here is called by JVM, without creating any object
for class.
iv. void : It is the return type, meaning this function will not return anything.
v. main : main() method is the most important method in a Java program. This is the method which is
executed, hence all the logic must be inside the main() method. If a java class is not having a main() method,
it causes compilation error.
vi. String[] args : This represents an array whose type is String and name is args. We will discuss more about
array in Java Array section.
10.5.2. Variables and Data types in Java
The declaration of variables necessitates always specifying their types. Variables cannot exist without types
and vice versa.
For example, String message;
This statement is a declaration, because it declares that the variable named message is of type String.

- 204 -
Each variable has a type that determines what kind of values it can store
A) Data type
Data type is a classification of data which tells the compiler or interpreter how the programmer intends to
use the data. Most programming languages support various types of data, for example: real, integer
or Boolean.
Classification of Java Data type
i. Primitive Java Data Types
There are eight primitive data types supported by Java and are predefined by the language and named by a
keyword. They are presented in the following table.
Type Description
Byte  Byte data type is an 8-bit signed two's complement integer
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an integer.
 Example: byte a = 100, byte b = -50

Short  Short data type is a 16-bit signed two's complement integer


 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

Int  Int data type is a 32-bit signed two's complement integer.


 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is
a concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000

Long  Long data type is a 64-bit signed two's complement integer


 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L
Float  Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f

- 205 -
Double  double data type is a double-precision 64-bit IEEE 754 floating point
 This data type is generally used as the default data type for decimal values,
generally the default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d
 Example: double d1 = 123.4

Boolean  Boolean data type represents one bit of information


 There are only two possible values: true and false
 This data type is used for simple flags that track true/false conditions
 Default value is false
 Example: boolean one = true
Char  char data type is a single 16-bit Unicode character
 Minimum value is (0)
 Maximum value is (or 65,535 inclusive)
 Char data type is used to store any character
 Example: char letterA = 'A'

[Link] Data types or Objects


Reference variables are created using defined constructors of the classes. They are used to access objects. These
variables are declared to be of a specific type that cannot be changed.
For example, employee, puppy, etc.
 Class objects and various types of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or any compatible type.

B) Variable in Java
A variable is a storage location (like a house, a pigeon hole, a letter box) that stores a piece of data for
processing. It is called variable because you can change the value stored inside. More precisely, a variable is
a named storage location, that stores a value of a particular data type.
The syntax for declaration of variable is as follow:
data_type variable_name;
Examples
To declare an integer variable named x, simply type:int x;
It is also possible to declare and initialize on the same line.
String message = "Hello!”;
int hour = 11;
int minute = 59;
NOTE:Printing variables
The value of a variable can be displayed by using the functions print or println.
The following statements declare a variable named firstLine, assign it the value "Hello, again!", and display
that value.
String firstLine = "Hello, again!";
[Link](firstLine);
Displaying a variable means displaying the value of that variable. To display the name of a variable, you have

- 206 -
to put it into quotes.
[Link]("The value of firstLine is ");
[Link](firstLine);
For this example, the output is:
The value of firstLine is Hello, again!
Conveniently, the syntax for displaying a variable is the same regardless of its type.
For example:
int hour = 11;
int minute = 59;
[Link]("The current time is ");
[Link](hour);
[Link](":");
[Link](minute);
[Link](".");
The output of this program is:
The current time is 11:59.
10.5.2. Types of Variables in Java
In terms of visibility of variables in a program, there are three types of in Java namely local
variable, instance variable and class variable.
1. Local Variables
This type of variable has the following characteristics:
o Local variables are declared in methods, constructors, or blocks.
o Local variables are created when the method, constructor or block is entered and the variable will be
destroyed once it exits the method, constructor, or block.
o Access modifiers cannot be used for local variables.

o Local variables are visible only within the declared method, constructor, or block.
o Local variables are implemented at stack level internally.
o There is no default value for local variables, so local variables should be declared and an initial value
should be assigned before the first use.
Example: Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to
only this method.
Public class Test{
public void pup Age(){
int age =0;
age= age +7;
[Link]("Puppy age is : "+ age);
}
Public static void main(String args []){
Test test=new Test();
[Link]();}}
2. Instance Variables
The variables defined within a class or method is called instance variables because each instance of the class

- 207 -
(that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is
separate and unique from the data for another. An instance variable can be declared public or private or
default (no modifier).To avoid that the variable’s value is changed out-side its class, it should be declared as
private. Public variables can be accessed and changed from outside of the class.
The syntax is shown below.

Figure. syntax of instance variable


[Link] or static variables
These are also known as static member variables and there's only one copy of that variable that is shared with
all instances of that class. If changes are made to that variable, all other instances will see the effect of the
changes.
Example:
public class Demo {
static int a;
static int b;
static {
a = 10;
b = 20;
}
public static void main(String args[]) {
[Link]("Value of a = " + a);
[Link]("Value of b = " + b);
}}
Output
Value of a=10
Value of b=20
10.5.4 Java keywords
Keywords are words that have already been defined for Java compiler. They have special meaning for the
compiler. Java Keywords must be in your information because you cannot use them as a variable, class or a
method name. Java keywords are categorized as datatypes and access modifiers
A. Data types
All predefined datatypes in java are keywords eg. int, char, bool, double, float, and String
B. Java access modifiers
Modifiers are keywords that are added to change meaning of a definition. In Java, modifiers are
categorized into two types,
 Access control modifier
 Non Access Modifier

- 208 -
1) Access control modifier
Java language has four access modifiers to control access levels for classes, variable methods and
constructors.
 Default : Default has scope only inside the same package
 Public : Public has scope that is visible everywhere
 Protected : Protected has scope within the package and all sub classes
 Private : Private has scope only within the classes
2) Non-access Modifier
Non-access modifiers do not change the accessibility of variables and methods, but they do provide them
special properties. Non-access modifiers are of 5 types,
 Final
 Static
 Transient
 Synchronized
 Volatile
i. Final
Final modifier is used to declare a field as final i.e. it prevents its content from being modified. Final field
must be initialized when it is declared. Final keyword can be used with a variable, a method or a class.
ii. Static Modifier
Static Modifiers are used to create class variable and class methods which can be accessed without instance of
a class.
iii. Synchronized modifier
When a method is synchronized it can be accessed by only one thread at a time.
iv. Volatile modifier
Volatile modifier tells the compiler that the volatile variable can be changed unexpectedly by other parts of
the program.

v. Transient modifier
When an instance variable is declared as transient, then its value doesn't persist when an object is serialized.
10.5.6 Java Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new value,
although sometimes an expression simply assigns a value to a variable. Expressions are built using values,
variables, operators and method calls.
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types of expressions in
Java:
 Those that produce a value, i.e. the result of (1 + 1), Expressions that produce a value use a wide range
of Java arithmetic, comparison or conditional operators.
For example, arithmetic operators include +, *, /, <, >, ++ and %.
 Those that assign a variable, for example (v = 10)
 Those that have no result but might have a "side effect" because an expression can include a wide range
of elements such as method invocations or increment operators that modify the state (i.e. memory) of a
program.

- 209 -
Example: This program here contains plenty of expressions
public class MyClass {
public static void main(String args[])
{
int x=10;// assign a variable Expressions int
y=25;// assign a variableExpressions int
z=x+y;// produce a value Expressions
[Link]("Sum of x+y = " + z);
}
}
10.6. Elements of Java source file
1. Class:
A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties
or methods that are common to all objects of one type.
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life
entities
Example:
/* Display a message */
Class Hello
{
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
Explanation of the above program
Java program consists of a named class(Hello). The body of the class is surrounded by braces
Almost every Java program must have one and only one main ( ) function
The body of the function is surrounded by brackets. Statements can be combined within braces to form a
block statement which can be used wherever a statement is required by the Java syntax
2. Object:
It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java program
creates many objects, which interact by invoking methods.
An object consists of:
 State: It is represented by attributes of an object. It also reflects the properties of an object.
 Behavior: It is represented by methods of an object. It also reflects the response of an object with
other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other objects.
3. Method:
It is a unit of program code, within a class designed to perform specific task or function.
A method is a program module that contains a series of statements that carry out a task.
A method is executed by invoking or calling it from another method. Any class can contain an unlimited
number of methods, and each method can be called an unlimited number of times.

- 210 -
The syntax to declare method is hereafter..

Within a class, a method can be used as follow.

Example:
/* Display a message */
class Hello {
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
The identifier [Link] is an object
The identifier println is one of the methods for that object
4. Statements:
A programming statement is the smallest independent unit in a program, just like a sentence in the English
language. It performs a piece of programming action.
Statements are:
 Variable declarations: primitive data types and classes
 Operations: arithmetic, logical, bit-level, class access

- 211 -
 Control structures: selection, looping, etc.
 Object messages: i.e., calls to methods A statement ends with a semi-column (;).
Example
class Weather {
public static void main(String[] arguments) {
float fah = 86;
[Link](fah + " degrees Fahrenheit is ...");
// To convert Fahrenheit into Celsius
// Begin by subtracting 32
fah = fah - 32;
// Divide the answer by 9
fah = fah / 9;
// Multiply that answer by 5
fah = fah * 5;
[Link](fah + " degrees Celsius\n");
Float cel = 33;
[Link](cel + " degrees Celsius is ...");
// To convert Celsius into Fahrenheit
// Begin by multiplying it by 9
cel = cel * 9;// Divide the answer by 5
cel = cel / 5;
// Add 32 to the answer
cel = cel + 32;
[Link](cel + " degrees Fahrenheit");
}}
10.7. Flow control
A control statement tells the computer to divert onto a different path. If a program has no control statements,
the JVM executes it, statement by statement, in sequential order. Often programmers refer to an execution
path as a flow of control.
The statements that control the flow of execution through a method fall into two categories:
Conditionals and loops.
10.7.1. Conditional statements
a. The IF Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean expression
is false.
The Java if statement has the following syntax:
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
If the Boolean condition is true, the statement is executed; if it is false, the statement is skipped.
Example
Public class Test{
Public static void main(String args[]){
int x =30;
if( x <20){

- 212 -
[Link]("This is if statement");
}
else{
[Link]("This is else statement");
}}}
[Link] IF-ELSE Statement
An else clause can be added to an if statement to make it an –elseif statement. The following is the syntax of
an if...else statement.
If (Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}
else {
// Executes when the none of the above condition is true.
}
Example
Public class Test{
Public static void main (String args[]){
int x =30;
if( x = =10){
[Link]("Value of X is 10");
}
elseif( x = =20){
[Link]("Value of X is 20");
}
elseif( x = =30){
[Link]("Value of X is 30");
}
else{
[Link]("This is else statement");
}}}
[Link] SWITCH Statement in Java
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each case.
The syntax of switch statement is;
switch(expression)
case value :
// Statements
break; // optional
case value :

- 213 -
// Statements
break; // optional
// You can have any number of case statements.
.
.
.
default : // Optional
// Statements
}
Example
Public class Test{
Public static void main(String args[]){
char grade ='C';
switch(grade){
case 'A':
[Link]("Excellent!");
break;
case 'B':
case 'C':
[Link]("Well done");
break;
case'D':
[Link]("You passed");
case'F':
[Link]("Better try again");
break;
default:
[Link]("Invalid grade");
}
[Link]("Your grade is "+ grade);
}}
10.5.2 Loops in java
Looping in programming languages is a feature which facilitates the execution of a set of
instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for
executing the loops:
1 . While loop: Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2 . For loop: Execute a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
3 . do...while loop: Like a while statement, except that it tests the condition at the end of the loop body.
[Link] while loop
The syntax of the while loop is as shown below;
initial_value while(Boolean_expression) {
// Statements
}

- 214 -
Example

b. The do...while loop


This loop is similar to the while loop, except that a do...while loop is guaranteed to execute at least one time.
The syntax of a do...while loop is:
do {
// Statements
}
while (Boolean_expression);

- 215 -
Example:

[Link] for loop.


This is a repetition control structure that allows you to efficiently write a loop that needs to be executed a
specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
// Statements
}

- 216 -
Example:

- 217 -
UNIT 11: OOP AND JAVA
11.1. Classes vs Objects in Java
11.1.1 Class in Java
a. Definition
A class is an entity that determines how an object will behave and what the object will contain. In other words, it
is a blueprint or a set of instruction to build a specific type of object or a class is a group of objects which have
common properties.
b. Syntax to declare a class:
class <class_name>
{
field; method;
}
c. General form of a class
A class is declared by the use of the class keyword. A simplified general form of a class definition is shown here:
class classname {
access specifier type instance-variable1;
access specifier type instance-variable2;
...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
11.1.2. Object in Java
An object is nothing but a self-contained component which consists of methods and properties to make a
particular type of data useful. Object determines the behavior of the class.
a. Syntax of an object
ClassName ReferenceVariable = new ClassName( );
b. Reference variable
An object can be accessed only through a reference variable.
Reference variables can be declared as static variables, instance variables, method parameters, or local variables.
The data within the object can be modified, but the reference variable cannot be changed.
 Object initialization through reference Variable:
Initializing simply means storing data into object

Example 1: Below is the example where class student is created, new keyword and the reference variable are
used.
class Student{
int id;
String name;
}
class TestStudent1{

- 218 -
public static void main(String args[])
{
Student s1=new Student(); //creating an object of Student
[Link]=101;
[Link]="Uwineza";
[Link]([Link]);
//accessing member through reference variable
[Link]([Link]);
//accessing member through reference variable
} }

Output:
101
Uwineza
Example: We can also create multiple objects and store information in it through reference variable.
class Student
{
int id;
String name;
}
class TestStudent3{
public static void main(String args[])
{
//Creating objects
Student s1=new Student();
Student s2=new Student();
Student s3=new Student();
//Initializing objects
[Link]=101;
[Link]="Uwineza";
[Link]=102;
[Link]="Munezero";
[Link]=103;
[Link]="Rugwiro";
//Printing data
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link] );
}
}
Output:
101 Uwineza
102 Munezero
103 Rugwiro

11. 2 Constructor in Java


11.2.1. Understanding constructor in Java
a. Definition
A constructor is a special method of a class that initializes an object of that type.
A Constructor is a special type of method which is used to initialize the object. It is called constructor because it
constructs the values at the time of object creation.

- 219 -
Every time an object is created using new () keyword, at least one constructor is called. It is called a default
constructor.
There are two (2) ways of creating a constructor: explicit and implicit:
 Explicit means that the constructor is created by the programmer.
 Implicit means that the creation of a constructor was done by the Java Virtual Machine or the tool, not the
Programmer.
Java will provide default constructor implicitly even if the programmer doesn't write the code for constructor. It is
called default constructor. The explicit is opposite to this implicit which means that the programmer has to write a
constructor.
Example: The program below maintains records of employees.
class Employee
{
int id; // instance variable
string name;
float salary;
Employee(int i, string n, float s) // constructor
{
id= i ;
name=n;
salary=s;
}
void insert(int i, String n, float s)
{
id= i ;
name=n;
salary=s;
}
void display()
{
[Link](id+" "+name+" "+salary);
} }
public class TestEmployee {
public static void main(String[] args)
{
Employee e1=new Employee(101,"Uwera",45000);
Employee e2=new Employee(102,"Kabera",25000);
Employee e3=new Employee(103,"Mugisha",55000);
[Link]();
[Link]();
[Link]();
[Link](201,"Umutesi",65000);
[Link](202,"Kabayija",75000);
[Link](203,"Mutara",85000);
[Link]();
[Link]();
[Link]();
}}
Output
101 Uwera 45000.0
102 Kabera 25000.0
103 Mukiza 55000.0
201 Umutesi 65000.0

- 220 -
202 Kabayija 75000.0
203 Mutara 85000.0

There are two types of constructors in java namely default constructor (no-argument constructor) and
parameterized constructor
11.2.2 Default Constructor
A default constructor is a constructor which doesn’t have any parameter and which can be called with no
arguments.
Syntax of default constructor:
Class <class_name>( )
{
………….
}
Example of default constructor
We are going to create the no-argument constructor in the Bike class. It will be invoked at the time of object
creation.
class Bike1{
Bike1() // Default constructor
{
[Link]("Bike is created");
}
public static voidmain(String args[]){
Bike1 b=new Bike1( );
} }
Rule: If there is no constructor in a class, compiler automatically creates a default constructor
Example: Default constructor that displays the default values
class Student3
{
int id;
string name;
Void display( )
{
[Link](id+” “+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
[Link]();
[Link]();
}}
Output
0 null
0 null
Explanation: In the above class, there is no constructor created, so the compiler provides a default constructor.
Here 0 and null values are provided by default constructor respectively as values for id and name.
11.2.3 Parameterized constructor in Java
A constructor which has a specific number of parameters is called parameterized constructor. A parameterized
constructor is used to provide different values to the distinct objects.
Example : In this example, the constructor of Student class has two parameters of the number of parameters in
the constructor can vary.
Class Student4{

- 221 -
int id;
String name;
Student4(int i,string n)//parameterized constructor
{
Id=i;
name=n;
}
void display()
{
[Link](id+” “+name);
}}
Public static void main(String args[])
{
Student4 s1=new Student4(111,”Umubyeyi”);
Student4 s1=new Student4(222,”Shyaka”);
[Link]();
[Link]();
}
}
Output
111 Umubyeyi
222 Shyaka

11.2.4. Constructor Overloading in Java


In Java, a constructor is just like a method but without return type and it can also be overloaded like Java
methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists.
They are arranged in a way that each constructor performs a different task.

Example: Constructor Overloading


class Student5
{
int id;
string name;
int age;
Student5(int i, String n)// constructor 1 has two parameters
{
id = i;
name = n;
}
Student5(int i, String n, int a)// constructor 2 has three parameters
{
id = i;
name = n;
age=a;
}
void display()
{
[Link](id+" "+name+" "+age);

- 222 -
}
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Umubyeyi");
Student5 s2 = new Student5(222,"Shyaka",25);
[Link]();
[Link]();
}
}
Output
111 Umubyeyi 0
222 Shyaka 25
11.2.5. Difference between constructor and method in java
There are many differences between constructors and methods.
They are given in the following table.
Java Constructor Java Method
Constructor is used to initialize the state of an object. Method is used to expose behavior of An
object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if Method is not provided by compiler in any case.
you don't have any constructor.
Constructor name must be same as the class name Method name may or may not be same as class
name

11.3. The use of “new” and “This” keywords in java


11.3.1 The use of “new” keyword
The new operator instantiates a class by allocating memory for a new object and returning a reference to that
memory. The new operator also invokes the object constructor.
Example:
Student s1=new Student ( );
The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor
provides the name of the class to instantiate. The new operator returns a reference to the object it created. There
are above many examples containing the new operator.
11.3.2 The use of “This” keywords in java
In java, this is a reference variable that refers to the current object.
This keyword is used in three (3) different circumstances:
 this can be used to refer current class instance variable.
 This can be used to invoke current class method (implicitly)
 this( ) can be used to invoke current class constructor.
1. this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance
variables and parameters, this keyword resolves the problem of ambiguity.
a)Understanding the problem without this keyword Example: This keyword is not used
Class student{

- 223 -
int rollno;
string name;
float fee;
Student(int rollno, string name, float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display()
{
[Link](rollno+" "+name+" "+fee+ “frw”);}
}
class StudentThis
{
}
public static void main(String args[])
{
Student s1=new Student(111,"Umubyeyi",5000);
Student s2=new Student(112,"Kalinda",6000);
[Link]();
[Link]();
}
}

Output
111 Umubyeyi 5000 frw
222 Kalin 6000 frw
Explanation: In the above example, parameters (formal arguments) and instance variables are same. So, this
keyword needs to be used to distinguish local variable and instance variable.
Example: Solution of the above problem by this keyword
class Student
{
int rollno;
string name;
float fee;
Student(int rollno, String name, float fee)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display()
{
[Link](rollno +" "+ name +" "+ fee + “frw”);
}
}
class StudentThis {
}
public static void main(String args[])
{
Student s1=new Student(111,"Umubyeyi",5000);

- 224 -
Student s2=new Student(112,"Kalinda",6000 );
[Link]();
[Link]();
}
}
Output
111 Umubyeyi 5000 frw
222 Kalinda 6000 frw
Notice that if local variables (formal arguments) and instance variables are different, there is no need to use this
keyword.
Example: Program where this keyword is not required
class Student
{
int rollno;
string name;
float fee;
Student(int r, string n, float f)
{
rollno=r;
name=n;
fee=f;
}
void display()
{[Link](rollno+" "+name+" "+fee “frw”);
}
}
class TestThis3
{
public static void main(String args[])
{
Student s1=new Student(111,"Umubyeyi",5000);
Student s2=new Student(112,"Kalinda",6000);
[Link]();
[Link]();
}}
It is a better approach to use meaningful names for variables. So we use same name for instance variables and
parameters in real time, and always use this keyword.
2. this: to invoke current class method
The method of the current class can be invoked by using the keyword. If this keyword is not used, the compiler
automatically adds this keyword while invoking the method.

Example: Program where this keyword is not required


class A
{
void m()
{
[Link]("Amakuru Yanyu");
}
void n()
{

- 225 -
[Link]("Muraho Neza ");
this.m();
}
}
class TestThis4
{
public static void main(String args[])
{
A a=new A();
a.n();
}
}
Output
Amakuru Yanyu
Muraho Neza

3. this() : to invoke current class constructor


The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor.
In other words, it is used for constructor chaining.
Example: Calling default constructor from parameterized constructor
Class A
{
A()
{
[Link]("Amakuru yanyu");
}
A(int x)
{
this( );
[Link](x);
}
}
class TestThis5{
public static void main(String args[])
{
A a=new A(10);
}
}
Output
Amakuru yanyu
10

11.4. Arrays in Java


11.4.1 Understanding Array in Java
An array is a container that holds data (values) of the same data type.
Array is a fundamental construct in Java that allows you to store and access large number of values conveniently.
a. Array syntax in Java
dataType[ ] arrayName;
 dataType can be a primitive data such as : int, char, Double, byte .
 arrayName is an identifier.
Example:

- 226 -
int[ ] age;
age = new int[5];
age array can hold 5 values of type int.
Note: You can replace two statements above with a single statement.
int[ ] age = new int[5];
b. Initialize arrays in Java
In Java, arrays can be initialized during declaration or it can be initialized (or change values) later in the program.
Example:
int[ ] age = {12, 4, 5, 2, 5};
This statement creates an array and initializes it during declaration. The length of the array is determined by the
number of values provided which is separated by commas. In our example, the length of age array is 5.

Example : Array initialization


class ArrayExample {
public static void main(String[] args)
{
int[ ] age = {12, 4, 5, 2, 5};
for (int i = 0; i < 5; ++i)
{
[Link]("Element at index " + i+": " + age[i]);
}}}
Output
Element at index 0: 12
Element at index 1: 4
Element at index 2: 5
Element at index 3: 2
Element at index 4: 5
Example: Program that computes sum and average of arrays elements in Java
public class SumAverage {
public static void main(String[ ]args)
{
int[ ]numbers={2,-9,0,5,12,-25,22,9,8,12};
double sum = 0;
double average;
for(int i=0;i<[Link];i++)
{
sum=sum+numbers[i];
}
int arrayLength = [Link];
// Change sum and arrayLength to double as average is in double
average=((double)sum/(double)arrayLength);
[Link]("Sum = " + sum);
[Link]("Average ="+ average);
}}

11.4.2 Array of object in Java


An object of class represents a single record in memory, if we want more than one record of class type, we have to
create an array of class or object. As we know, an array is a collection of similar type, therefore an array can be a
collection of class type.

- 227 -
a. Syntax for creating an array of object
class ClassName
{
datatype var1; datatype var2;
----------
datatype varN;
method1( ); method2( );
----------
methodN( );
}
Syntax of array of object
Class-Name [ ] object = new Class-Name [size];
Example: Creating an array of object
import [Link];
class Employee
{
Int Id;
String Name;
int Age;
long Salary;
void GetData() // Defining GetData()
{
Scanner sc=new Scanner([Link]);
[Link]("\n\tEnter Employee Id : ");
Id = [Link]([Link]());
[Link]("\n\tEnter Employee Name : ");
Name = [Link]();
[Link]("\n\tEnter Employee Age : ");
Age = [Link]([Link]());
[Link]("\n\tEnter Employee Salary : ");
Salary = [Link]([Link]());
}
void PutData() // Defining PutData()
{
[Link]("\n\t" + Id + "\t"+Name + "\t" +Age + "\t" +Salary);
}
public class Arrayofobject {
public staticvoid main(String args[])
{
Employee[] Emp=new Employee[3];
int i;
for(i=0;i<3;i++)
Emp[i] = new Employee();// Allocating memory to each object
for(i=0;i<3;i++)
{
[Link]("\nEnter details of "+ (i+1) +" Employee\n");
Emp[i].GetData();
}
[Link]("\nDetails of Employees\n");
for(i=0;i<3;i++)
Emp[i].PutData();
}}

- 228 -
11.5. Inheritance in Java
10.5.1 Understanding inheritance in java
a. Definition
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
It is an important part of Object Oriented programming system.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes.

b. Terms used in Inheritance


Below are some of terms used in inheritance:
i. Class: A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created.
ii. Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class,
extended class, or child class.
iii. Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
iv. Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class. You can use the same fields and methods already
defined in previous class.
c. Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
11.5.2 The use of “extends “keyword in Java
The extends is a Java keyword used in inheritance and it indicates that you are making a new class that derives
from an existing class.
Note: In the terminology of Java, a class which is inherited is called parent or super class and the new class is
called child or subclass.
Example: Inheritance in Java
Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-
A Employee. It means that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Output:
Programmer salary is:40000.0
Bonus of Programmer is:10000.
Note: In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.
11.5.3. Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
Note: Multiple inheritance is not supported in java through class.

- 229 -
a. Single Inheritance

Single inheritance enables a derived class to inherit properties and behavior from a single parent class. It allows a
derived class to inherit the properties and behavior of a base class, thus enabling code reusability as well as
adding new features to the existing code.
Example: Single Inheritance
class Animal{
void eat(){
[Link]("Eating...");
}
}
class Dog extends Animal{
void bark()
{
[Link]("Barking...");
}
}
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Output:
Barking
Eating
b. Multilevel Inheritance

Multiple Inheritance refers to the concept of one class extending (or inherits) more than one base class. The
inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple
inheritance” is that the derived class will have to manage the dependency on two base classes.
Example : Multilevel Inheritance
class Animal{

- 230 -
void eat(){
[Link]("eating...");
}
}
class Dog extends Animal{
void bark()
{
[Link]("barking...");
}
}
class BabyDog extends Dog{
void weep()
{
[Link]("weeping...");
}
}
public static void main(String args[])
{
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
Output:
weeping…
barking…
eating…
c. Hierarchical inheritance in java
Class A

Class B Class C

Consider the above figure, there are three classes A, B and C . Class C and B inherits class A.
Example : Hierarchical inheritance
class Animal
{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()

- 231 -
{
[Link]("barking...");
}
}
class Cat extends Animal{
void meow(){
[Link]("meowing...");
}
}
class TestInheritance3{
public static void main(String args[])
{
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output
meowing...
eating...
Note: Java doesn’t support Multiple Inheritance through classes. Multiple Inheritance is a feature of object
oriented concept, where a class can inherit properties of more than one parent class. The problem occurs
when there exist methods with same signature in both the super classes and subclass. On calling the method,
the compiler cannot determine which class method to be called and even on calling which class method gets
the priority.

11.6. Access Modifiers in java


Access modifiers are keywords used to specify the accessibility of a class (or type) and its members. These
modifiers can be used from code inside or outside the current application.
The purpose of using access modifiers is to implement encapsulation. The following are benefits of using
access modifiers:
 They regulate access to classes,fields,and methods in java.
 These specifiers determine whether a field or method in a class,can be used or invoked by another method
in another class or sub-class.
 They can be used to restrict access.
There are 4 types of java access modifiers: private, default, protected, public
i) Default access modifier
When no access modifier is specified for a class, method or data member, then it is said to be having the
default access modifier by default. The data members, class or methods which are not declared using any
access modifiers i.e. having default access modifier are accessible only within the same package.
Example: Default access modifier
We are going to create two packages pack and mypack and access the A class from outside its package.
Since A class is not public, so it cannot be accessed from outside the package.
package pack;
class A{
void msg()
{
[Link]("Hello");
}
package mypack;
import pack.*;
class B{

- 232 -
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
[Link](); //Compile Time Error
}
}

Output
Running error

Note: The scope of class A and its method msg() is default so it cannot be accessed from outside the package.
ii. Private access modifier
The private access modifier is specified using the keyword private.
 The methods or data members declared as private are accessible only within the class in which they are declared.
 Any other class of same package will not be able to access these members.
 Classes or interface cannot be declared as private
Example: private access modifier
In this example, we will create two classes A and B within same package p1. We will declare a method in
class A as private and try to access this method from class B and see the result.
Package p1;
Class A
{
private void display()
{
[Link]("Rwanda Nziza");
}
}
class B
{
public static void main(String args[ ])
{
A obj = newA( ); //trying to access private method of another class
[Link]();
}}
Note:Role of Private Constructor
The role of a private constructor is that if you make any class constructor private, you cannot create the
instance of that class from outside the class.
Example: private used on a constructor
class A{
private A(){}//private constructor
void msg(){
[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A( );//Compile Time Error
} }
Output
Running Error

iii. Protected access modifier


The protected access modifier is accessible within package and outside the package but through inheritance
only. The protected access modifier can be applied on the data member, method and constructor. It can't be

- 233 -
applied on the class.
Example: protected access modifier
We have created two packages pack and mypack. The A class of pack package is public, so can be accessed
from outside the package. But msg () method of this package is declared as protected, so it can be accessed
from outside the class only through inheritance.
//save by [Link]
package pack;
public class A{
protected void msg( ){
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[])
{
B obj = new B( );
[Link]();
}
}
iv. Public access modifier
The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access modifiers.
 Classes, methods or data members which are declared as public are accessible from everywhere in the
program. There is no restriction on the scope of a public data member.
Example: public access modifier
//save by [Link]
package pack;
public class A{
public void msg(){
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A( );
[Link]( );
}
}
Output
Running Error
11.7. Overloading and overriding Method in Java

11.7.1 .Method Overloading


Method Overloading is a feature that allows a class to have more than one method having the same name, if their
argument lists are different.

- 234 -
Three ways to overload a method:
i) Number of parameters
Example:
Add(int,int)
Add(int,int,int)
This a valid case overloading
ii) Data type of parameters
Example:
Add(int,int)
Add(int,float)
iii) Sequence of data type of parameters
Example:
Add(int,float)
Add(float,int)
Note: if two methods have the same name,same parameters and have different return type,then this is not a valid
method overloading [Link] will throw compilation error.
Example:
int add(int,int)
float add(int,int)

11.7.2 Method Overriding in Java


a. Definition Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in
java.
In other words, if subclass provides the specific implementation of the method that has been provided by one of
its parent class, it is known as method overriding.
b. Rules for Method Overriding
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original overridden method
in the superclass.
 The access level cannot be more restrictive than the overridden method's access level.
For example: If the superclass method is declared public then the overriding method in the sub class cannot be
either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any superclass method that is
not declared private or final.
 A subclass in a different package can only override the non-final methods declared public or protected.
 Constructors cannot be overridden.
c. Usage of Java Method Overriding
Method overriding is used to provide specific implementation of a method that is already provided by its super
class. If a class inherits a method from its superclass, then there is a chance to override the method provided that it
is not marked final.
Example: Method Overriding
class Animal {
public void move( ) {
[Link](“Animals can move”);
}
}
class Dog extends Animal {

- 235 -
public void move( ) {
[Link](“Dogs can walk and run”);
}
}
public class Animaltest {
public static void main(String args[]) {
Animal a = new Animal( ); // Animal reference and object
Animal b = new Dog( ); // Animal reference but Dog object
[Link](); // runs the method in Animal class
[Link]();// runs the method in Dog class
}}
Output
Animal can move
Dogs can walk and run
11.7.3 .The use the “super” keyword in Java
When invoking a superclass version of an overridden method the super keyword is used.
Example: use of super keyword
class Animal {
public void move() {
[Link]("Animals can move");
}
}
class Dog extends Animal { public void move() {
[Link](); // invokes the super class method
[Link]("Dogs can walk and run");
}
}
public class Animaltest {
public static void main(String args[]) {
Animal b = new Dog();// Animal reference but Dog object
[Link](); // runs the method in Dog class
}
11.7.4. The use of “final” keyword in java.
Final keyword in Java has three different uses: final variable, prevent inheritance and prevent methods from
being overridden.
a. Final variable
Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized.
If you want to make a local variable, class variable (static field), or instance variable (non-static field)
constant, declare it final. A final variable may only be assigned to once and its value will not change and can
help avoid programming errors.
Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference
to an object, then the state of the object may be changed by operations on the object, but the variable will
always refer to the same object.
Example: Use final to define constant
class Demo{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
} }
public static voidmain(String args[]){
Demo obj=new Demo( );
[Link]();

- 236 -
} }
There is a compilation error in the above program because of the change the value of a final variable
“MAX_VALUE”.
Note: It is considered as a good practice to have constant names in UPPER CASE (CAPS)
Note: Blank final variable
A final variable that is not initialized at the time of declaration is known as blank final variable. Let
initialize the blank final variable in constructor of the class otherwise it will throw a compilation error
(Error: variable MAX_VALUE might not have been initialized).
Example: blank final variable is used in a class.

class Demo{
final int MAX_VALUE; //Blank final variable
Demo(){ //It must be initialized in constructor
MAX_VALUE=100;
}
void myMethod(){
[Link](MAX_VALUE);
}}
public class Finaltest1 {
public static voidmain(String[] args) {
Demo obj=new Demo( );
[Link]();
}}

Output
100
b. Final method
When a class is extended by other classes, its methods can be overridden for reuse. There may be
circumstances when you want to prevent a particular method from being overridden, in that case, declare
that method final. Methods declared as final cannot be overridden which means even though a sub class can
call the final method of parent class without any issues but it cannot override it.
Example
class XYZ{
final void demo(){
[Link]("XYZ Class Method");
}
}
class ABC extends XYZ{ }
public class Finaltest2 {
public static voidmain(String[] args) {
ABC obj= new ABC( );
[Link]();
}
}
Output
Class XYZ Class Method

This above program runs fine because the program is not overriding the final method.
Example
class XYZ{
final voiddemo(){
[Link]("XYZ Class Method");
}}

- 237 -
class ABC extends XYZ{ void
demo(){
[Link]("ABC Class Method");
}}
public classFinaltest3 {
public static voidmain(String[] args) { ABC obj=
new ABC();
[Link]();
}}
Output:Running Error
The above program give a compilation error because the program is overriding the final method
c. Final class
If you find a class's definition is complete and you don't want it to be sub-classed, declare it final. A final
class cannot be inherited, therefore, it will be a compile-time error if the name of a final class
appears in the extends clause of another class declaration; this implies that a final class cannot have
any subclasses.
Note:It is a compile-time error if a class is declared both final and abstract, because the implementation of
such a class could never be completed.
Because a final class never has any subclasses, the methods of a final class are never overridden
Example: final class
final class XYZ{
}
class ABC extends XYZ{ void demo(){
[Link]("My Method");
}
public classFinaltest4 {
public static voidmain(String[] args) { ABC obj=
new ABC();
[Link]();
}
}
Output: None
Note: The type ABC cannot subclass the final class XYZ
11.8. Encapsulation in Java
11.8.1 Understanding encapsulation in Java
a. Definition
Encapsulation simply means binding object state (fields) and behavior (methods) together. While creating class,
you are doing encapsulation.
To implement encapsulation,do the following:
 Make the instance variables private so that they can not be accessed directly from outside the class
 Have getter and setter method in thew class to set and get the values of the fields.
Example: Encapsulation in Java
class Employee{
private int ssn;
private String empName;
private int empAge;
//Getter and Setter methods
public int getEmpSSN(){
return ssn;
}
public String getEmpName(){
return empName;
}

- 238 -
public int getEmpAge(){ returnempAge;
}
public void setEmpAge(int newValue){
empAge = newValue;
}
public void setEmpName(String newValue){
empName = newValue;
}
public void setEmpSSN(int newValue){
ssn = newValue;
}
}
public class Employeetest{
public static void main(String args[]){
Employee obj = new Employee();
[Link]("Rukundo");
[Link](32);
[Link](233);
[Link]("Employee Name: " + [Link]( ));
[Link]("Employee SSN: " + [Link]( ));
[Link]("Employee Age:"+ [Link]( ));
}
}
Explanation:
In above example all the three data members (or data fields) are private which cannot be accessed directly.
These fields can be accessed via public methods only. Fields empName, ssn and empAge are made hidden data
fields using encapsulation.
The below are Advantages of encapsulation
 It improves maintainability and flexibility and re-usability.
 The fields can be made read-only or write-only.
 A class can have total control over what is stored in its fields. The user would not be knowing on behind the
scene.
11.8.2 Understand use of getter and setter method in Java
In Java, getter and setter method are two conventional methods that are used for retrieving and updating value of a
variable.

Example: simple class with a private variable and a couple of getter and setter methods
public class Add {
private int number;
public int getNumber()
{
return [Link];
}
public void setNumber(int num)
{
[Link] = num;
}
}
In above example, Add class declares a private variable, number. Since number is private, code from outside this
class cannot access the variable directly like this:
Add obj = new Add ();
[Link] = 10;// compile error, since number is private

- 239 -
int num = [Link]; // same as above
Instead, the outside code have to invoke the getter, getNumber() and the setter, setNumber() in order to read or
update the variable.
Example:
Add obj = new Add ();
[Link](10); // OK
int num = [Link](); // fine
Note: a setter is a method that updates value of a variable. And a getter is a method that reads value of a
variable. Getter and setter methods are also known as accessor and mutator in Java.

11.9. Abstract class in java


11.9.1. Understanding abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user. In other
words, it shows only important things to the user and hides the internal details.
Example: sending sms, you just type the text and send the message. You don't know the internal processing about
the message delivery.
Note: Abstraction focuses on what the object does instead of how it does it.
a. Abstract class in Java

A class that is declared as abstract is known as abstract class. A class that is declared with abstract keyword.
It needs to be extended and its method [Link] Abstract class cannot be instantiated.
Abstract class syntax
abstract class name {}
Note:The important features of abstract classes are:
 Abstract classes cannot be instantiated
 An abstract classes contains abstract methods,concrete methods or both.
 Any class with extends abstract class must override all methods of abstarct class.
b. abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract method syntax
abstract void methodname ();
Example : abstract class that has abstract method
In below program, there is a class which is the abstract class and it contains only one abstract method with
the method name run. There is a class Honda that is derived from Bike class. The implementation of the
abstract class Bike is provided by the Honda class.
abstract class Bike{
abstract void run();
}
class Honda extends Bike{
void run()
{
public class AbstractionTest {
[Link]("running safely..");
} }
public static voidmain(String args[]){
Bike obj = new Honda();
[Link]();
} }

Output:
Running safely..
c. Understanding the real scenario of abstract class

- 240 -
In below program, Shape is the abstract class, its implementation is provided by the Rectangle and Circle
classes. The end user don't know about the implementation class and object of the implementation class is
provided by the factory method.
Example: abstraction
abstract class Shape{
abstract void draw( );
}
class Rectangle extends Shape{
void draw()
{
[Link]("drawing rectangle");
}}
class Circle1 extends Shape{
void draw()
{
[Link]("drawing circle");
}}
class TestAbstraction1{
public static voidmain(String args[]){
Shape s=new Circle1( );
[Link]();
}}
Output
drawing circle
Abstract class having constructor, data member, methods
An abstract class can have data member, abstract method, method body, constructor and even main() method.
Example: abstract class that have method body
abstract class Bike{
Bike(){
[Link]("bike is created");
}
abstract void run( );
void changeGear(){
[Link]("gear changed");
}}
class Honda extends Bike{
void run(){
[Link]("running safely..");
}}
class Abstraction2test{
public static void main(String args[ ]){
Bike obj = new Honda( );
[Link]();
[Link]();
} }
Output:
Bike is created
Running safely..
Gear changed

- 241 -
UNIT 12: IO and Java
12.1. Introduction to IO Streams
The term stream refers to a sequence of values from any input source of data (keyboard, file, port,and so
on), or to any output destination for data (screen, file, port, and so on). The [Link] contains nearly
every class needed to perform input and output(I/O) in Java.
All these streams represent an input source and an output destination.
Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of characters.
12.1.1. Definition of InputStream
The InputStream is an abstract class that describes stream input. In Java programming language the
InputStream is used to read data from a source.
This class defines several methods among which include read( ) that reads byte of data
12.1.2. Definition of OutputStream
Output stream is an abstract class that describes stream output. In Java programming language, the
OutputStream is used for writing data to a destination.
This class defines several methods among which include write( ) that reads byte of data
12.1.3 Role of I/O Stream
IO Streams provide convenient ways of handling data input and output in a java program.
While writing java programs, three IO objects are provided implicitly for performing data Input and
Output. They are;
 [Link] (input stream)
 [Link] (output stream for normal results)
 [Link] (output stream for error messages)
Generally [Link] is connected to the keyboard and inputs character data*, and [Link] and
[Link] are connected to the monitor and output character data.
12.2. InputStream, OutputStream and FileStream
The goal of InputStream and OutputStream is to abstract different ways to input and output.
12.2.1 OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral
device or socket.
Code of Printing “WELCOME WORLD” without advancing to a new line
[Link](“ WELCOME WORLD”);
Code of Printing “WELCOME WORLD " and advance to a new line.
[Link](“ WELCOME WORLD”);

- 244 -
Example
class FirstProgram{
public static void main(String[] args){
[Link]("Good morning Sir" );
[Link]("welcome to java programming " );
}}
12.2.2. InputStream
Java application uses an input stream to read data from a source, it may be data, a file, and an array. There
are different input stream classes that can be applied to input data from user.
 scanner( )
 BufferedReader( )
 DataInputStream( )
a. Using Scanner class.
Java has a number of predefined classes which can be used. Predefined classes are organized in the form
of packages.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and namespace management.
In Java, data can be input with the help of the Scanner class.
This Scanner class is found in [Link] package. So, to use the Scanner class, [Link] package needs to
be included first in the program. Apackage is included in a program with the help of import keyword. The
[Link] class or the entire [Link] package are then imported.
The advantage of using Scanner class is that it provides convenient methods for capturing primitives
(nextInt(), nextFloat(), …) from input devices whereas its disadvantage is that reading methods are not
synchronized .
To import a class or a package, one of the following lines should be added to the very beginning of the
code.
import [Link]; // This will import just the Scanner class
import [Link].*; // This will import the entire [Link] package
After importing, the following statement will be valid when written in the program.
Scanner k = new Scanner ([Link]);
Scanner k, here K is declared as an object of Scanner class. [Link] within the round brackets tells
Java that this will be System Input i.e. input will be given to the system.
The main purpose of the Scanner class is to parse primitive types and strings using regular expressions,
however it can also be used to read input from the user in the command line. Here is an example:
Scanner scanner = new Scanner( [Link] ); // Create a Scanner using the InputStream available.
[Link]( "Type some data for the program: " ); // Don't forget to prompt the user String
input = [Link]( );// Use the Scanner to read a line of text from the user.
[Link]( "input = " + input );// Now, you can do anything with the input string that you need to.

- 245 -
List of datatypes.

Method Inputs
nextInt() Integer
nextFloat() Float
nextDouble() Double
nextLong() Long
nextShort() Short
next() Single word
nextLine() Line of Strings
nextBoolean() Boolean
Example 1: A programme that asks to enter numbers from the keyboard and displays those numbers on the
screen
import [Link];
import [Link].*;
class number{
public static void main(String[] args)
{
Scanner s1 = new Scanner([Link]);
[Link]("Enter integer");
int n = [Link]();
[Link]("Enter double");
double db = [Link]();
[Link]("Integer :" + n);
[Link]("Double :" + db);
}}

n= [Link](); [Link]() will take integer input from the user and it assigns it to n. . So, this
statement will be like n = 14; when user entered 14.
b. Using BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can be used to
read data line by line by readLine() method. It makes the performance fast. It inherits Reader class.
BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter your name: ");
String name = [Link](); [Link]("Your name is: " + name);
- 246 -
In the above example, the readLine() method reads a line of text from the command line. Advantages:
The input is buffered for efficient reading and its disadvantage is that the wrapping code is hard to
remember.
Example of program using BufferedReader
import [Link];
import [Link];
import [Link];
class BufferedReaderExample{
public static void main(String args[])throws IOException{
int a,b,sum;
InputStreamReader p = new InputStreamReader([Link]);
BufferedReader br = new BufferedReader(p);
[Link]("Enter Two Numbers :");
a = [Link]([Link]());
b=[Link]([Link]());
sum = a + b;
[Link]("Sum is :"+sum);
}}
OUTPUT

Notice that a "keyboard object" for reading from the console keyboard can therefore be instantiated as
follows:
InputStreamReader p = new InputStreamReader([Link]);
BufferedReader keyboard = new BufferedReader(p);
Note:The intermediate variable p could be eliminated and it can be done in one step like this:
BufferedReader keyboard =new BufferedReader(new InputStreamReader([Link]));
c. DataInputStream
InputStream uses readLine() method of DataInputStream to read data from the keyboard. Java
InputStreams are used for reading byte based data, one byte at a time.
The following example describes how to useDataInputStream with different data types:

- 247 -
Example 1
import [Link].*;
public class KeyboardReading1
{
public static void main(String args[]) throws IOException
{
DataInputStream dis = new DataInputStream([Link]);
{
[Link]("Enter your name:");
String str1 = [Link]();
[Link]("I know your name is "+ str1);
[Link]("Enter the first number:");
String str2 = [Link]();
int x = [Link](str2);
[Link]("Enter a second number:");
String str3 = [Link]();
double y = [Link](str3);
if(x<y)
[Link]("First number " +x + " is less than second number " + y);
else
[Link]("First number " +x + " is greater than second number " + y);
} }}

Example 2
import [Link].*;
public class KeyboardReading1{
public static void main(String args[]) throws IOException
{
try (DataInputStream dis = new DataInputStream([Link])) {
[Link]("Enter your name: ");
String str1 = [Link]();
[Link]("I know your name is " +str1);
[Link]("Enter a whole number:”)
String str2 = [Link]();
int x = [Link](str2);
[Link]("Enter a double value: ");
String str3 = [Link]();
double y = [Link](str3);
if(x > y)
[Link]("First number " +x + " is greater than second number " + y);
else
[Link]("First number " +x + " is less than second number " + y);
}}}
- 248 -
Explanations:
The readLine() method of DataInputStream reads a line at a time and returns a string, irrespective of
what the line contains. Depending on the input value, the string is to be parsed into an int or double etc.
This is extra work in the keyboard reading when compared to C/C++. In C/C++, parsing is done
implicitly by %d, %f, etc.
What is "[Link]"?
" in" is an object of " InputStream" class defined in System class (like "out" is an object of
PrintStream class defined in System class). It is declared as static and final object. The in object is
connected implicitly to the " standard input stream" of the underlying OS.
DataInputStream dis = new DataInputStream([Link]); [Link]
is a byte stream which is automatically connected to the keyboard reading mechanism of operating
system. It is chained to DataInputStream to facilitate the reading of user input with its readLine() method.
Like [Link] is connected to the keyboard mechanism of OS, the [Link] is connected to the
standard output mechanism of OS.
12.3 FileStreams
a. FileInputStream
This FileInputStream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
The following constructor takes a file name as a string to create an input stream object to read the file:
InputStreamf=newFileInputStream("C:/java/hello");
The following constructor takes a file object to create an inputstream object to read the file.
First a file object using File()methods created as follows:
Filef=newFile("C:/java/hello"); InputStreamf=newFileInputStream(f);
Once InputStream object is in hand, then there is a list of helper methods which can be used to read
from the stream or to do other operations on the stream.
Methods used for file Input Stream public void close() throws IOException{}
This method closes the file outputstream. Releases any system resources associated with The file.
Throws an IOException
1. Protected void finalize()throws IOException{}
This method cleans up the connection to the file. It ensures that the close method of this file output
stream is called when there are no more references to this stream. It throws an IOException.
2. Public int read(intr)throws IOException{}
This method readsthespecified byteofdatafromtheInputStream and returns the next byte of data and-
1will be returned if it is end of file.
3. Public in tread(byte[]r)throws IOException{} This method reads [Link] from the input
stream into an [Link] returns the total number of bytes [Link] end of file-1will be returned.
4. Public int available()throws IOException{}
Gives the number of bytes that can be read from this file [Link] returns an integer.
12.3.1 FileOutputStream:
FileOutputStreamis used to create a file and write data into [Link] stream would create a file,if it
doesn't already exist,before opening it for output.
a. File output stream constructors
The following constructor takes a file name as a string to create an outputstream object to write the
file: OutputStreamf=newFileOutputStream("C:/java/hello")
- 249 -
The following constructor takes a file object to create an outputstream object to write the file.
First,a file object using File()method is createdas follows:
Filef=newFile("C:/java/hello"); OutputStreamf=newFileOutputStream(f);
Once the OutputStream object is in hand,then there is a list of helper methods,which can be used to write
to stream or to do other operations on the stream.
b. File output stream methods
1. Public void close() throws IOException{}
This method closes the file outputstream. Releases any systemresources associatedwith the [Link]
anIOException.
2. Protected void finalize()throwsIOException{}
This method cleans up the connection to the file. Ensures that the close method of this file outputstream
is called when there are no more references to this [Link] an IOException.
3. Public void write(intw)throws IOException{}
This methods writes the specified byte to the outputstream.
4. Public void write(byte[]w)
It writes [Link] bytes from the mentioned byte array to the OutputStream.
The following is the example to demonstrate FileInputStreamand FileOutputStream:
Example: Java FileInputStream to read single character import [Link];
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\[Link]");
int i=[Link](); [Link]((char)i); [Link]();
}catch(Exception e)
{
[Link](e);
}}
}
Notice that before running the code, a text file named as "[Link]" is required to be created.
If in n this file there are the following contents:
Hello Programmers.
After executing the above program, a single character from the file which is 87 (in byte form) is gotten.
To see the text, the byte form converted into character.
Output:
H
12.4 Readers and writer
The Java Reader ([Link]) and Java Writer class ([Link]) in Java IO work much like the
InputStream and OutputStream with the exception that Reader and Writer are character based. They are
intended for reading and writing text while the InputStream and OutputStream are byte based.
12.4.1 Reader
The Java Reader is the base class of all Readers in the Java IO. The subclasses include a
BufferedReader, PushbackReader, InputStreamReader, StringReader and several others.

- 250 -
Combining Readers With InputStream
A Java Reader can be combined with an InputStream. To read characters from an
InputStream , wrap it in an InputStreamReader and pass the InputStream to the constructor of the
InputStreamReaderas follows;
Reader reader = new InputStreamReader(inputStream);

12.4.2 Writer
The Java Writer class is the base class of all Writers in the Java IO API. The subclasses include
BufferedWriter and PrintWriter among others.
Here is a simple Java IO Writer example:
Writer writer = new FileWriter("c:\\data\\[Link]");
[Link]("Hello World Writer");
[Link]();
Combining Writers With OutputStreams
A Java Writer can be combined with an OutputStream just like Readers and InputStream's.
Wrap the OutputStream in an OutputStreamWriter and all characters written to the Writer are passed on
to the OutputStream.
Here is an OutputStreamWriterexample:
Writer writer = new OutputStreamWriter(outputStream);
Combining Readers and Writers
Just like with streams, Readers and Writers can be combined into chains to achieve more interesting IO.
It works just like combining the Reader with InputStream's or the Writer with OutputStream's.
For instance, buffering is achieved by wrapping a Reader in a BufferedReader, or a Writer in a
BufferedWriter.
Here are two such examples:
Reader reader = new BufferedReader(new FileReader(...));
Writer writer = new BufferedWriter(new FileWriter(...));
12.5 Character stream
Java Byte streams are used to perform input and output of 8-bit in one byte, whereas Java Character
streams are used to perform input and output for16-bit [Link] there are many classes related to
character streams but the most frequently used classes are, FileReader and [Link] internally
FileReader uses FileInputStream and File Writer uses FileOutputStream but here major difference is that
FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
Example:
package javaLesson;
import [Link];
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\[Link]");
[Link]("Welcome to java Lesson 12.");
[Link]();
}catch(Exception e){[Link](e);}
[Link]("Success...");
}
}
Output: Welcome to java Lesson 12.
- 251 -
252
253

You might also like