Laptop and Portable Devices Overview
Laptop and Portable Devices Overview
HIGH SCHOOL
STUDENT’S NAME:
[Link]:
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.
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
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.
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.
-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.
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).
b) Multi-dimensional arrays
Example:
• Two dimensional array ex: a[2][7]as integer
• Three dimensional array ex: a[3][2][5]as Integer
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];
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.
4
end for
end
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
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
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
9
In the list you can do the following operations:
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.
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).
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
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.
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
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:
18
Fig:Array representation in binary 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.
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.
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.
20
Figure:Binary tree search.
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
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:
[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:
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.
- 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.
- 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.
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.
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.
- 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
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.
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.
- 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.
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.
- 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
- 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.
- 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.
- 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
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.
- 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
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
- 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.
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.
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
- 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.
- 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.
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
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.
- 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.
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
[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.
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.
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.
- 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.
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.
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.
- 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
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
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.
- 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.
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).
- 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).
- 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.
- 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:
Husband Wife
- 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.”
Total Participation
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.
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.
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.
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
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
Table: PRODUCTS
ProductName Manufacturer
Digital Camera Nikon
Printer Canon
Laptop HP
Hair Dryer Panasonic
Electric shaver Phillips
Modem Huawei
Mobile Phone Samsung
- 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:
- 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:
- 90 -
}
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.
- 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.
- 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.
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
- 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;
- 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
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.
- 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.
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.
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;
}}
- 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.
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.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:
- 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
- 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.
[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:
- 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.
- 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 john : private person john inherits uniquely from the person class in
private.
- 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
- 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
- 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
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.
- 172 -
[Link] = average
End Sub
PrivateSub Command3_Click()
[Link] = ""
[Link] = ""
[Link] = ""
[Link] = ""
[Link] = "" End Sub
Private Sub Command4_Click()
Unload Me
End Sub
- 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
- 176 -
> Greater than txtValue > 20.45
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
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.
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
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:
- 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:
- 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:
- 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:
(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.
- 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
- 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:
- 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:
- 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.
- 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.
- 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
- 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.
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.
- 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
- 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
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.
- 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
- 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.
- 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.
- 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:”
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:
- 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.
- 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].
- 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.
- 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.
- 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
- 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
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.
- 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..
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
- 215 -
Example:
- 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
- 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
- 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
- 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.
- 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
- 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.
- 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.
- 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.
- 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
- 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
- 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)
- 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.
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