IT Professional Knowledge PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 203

www.BankExamsToday.

com

IT Officer
Professional
Knowledge Guide
By Ramandeep Singh and Deepak Arora

Ramandeep Singh
11/3/2016
IT Officer Professional Knowledge Guide

Table of Contents
Chapter – Networking ................................................................................................................................. 17
Network Infrastructure Devices and Topologies ........................................................................................ 17
Hub ............................................................................................................................................................. 17
Switch ......................................................................................................................................................... 17
Router ........................................................................................................................................................ 18
Differences between Hub, Switch and Router ..................................................................................... 18
Firewall ....................................................................................................................................................... 18
Network Topologies ................................................................................................................................. 19
Bus Topology ............................................................................................................................................ 19
Ring Topology ........................................................................................................................................... 19
Star Topology............................................................................................................................................ 19
Mesh Topology ......................................................................................................................................... 20
Advantages: .......................................................................................................................................... 20
Disadvantages: ..................................................................................................................................... 20
Tree Topology ............................................................................................................................................. 20
Hybrid Topology ....................................................................................................................................... 21
Advantages: .......................................................................................................................................... 21
Disadvantages: ..................................................................................................................................... 21
Peer to Peer Networks ............................................................................................................................ 21
Client Server Network .............................................................................................................................. 21
Centralized Network................................................................................................................................. 22
Distributed Network .................................................................................................................................. 22
Type of servers used in a network ......................................................................................................... 22
File Server ............................................................................................................................................. 22
Print Server ........................................................................................................................................... 22
Mail Server ............................................................................................................................................ 23
Application Server ................................................................................................................................ 23
Database Server................................................................................................................................... 23
Directory Server.................................................................................................................................... 23
Open System Interconnection (OSI) Model ......................................................................................... 23
Layer 1: The Physical Layer ................................................................................................................... 24

www.BankExamsToday.Com Page 1
IT Officer Professional Knowledge Guide

Layer 2: Data Link Layer ......................................................................................................................... 24


Layer 3: Network Layer ........................................................................................................................... 24
Layer 4: Transport Layer ......................................................................................................................... 25
Layer 5: Session Layer ............................................................................................................................ 25
Layer 6: Presentation Layer ................................................................................................................... 25
Layer 7: Application Layer ...................................................................................................................... 25
TCP/IP........................................................................................................................................................ 25
Encapsulation and Decapsulation ......................................................................................................... 26
Encapsulation ....................................................................................................................................... 26
Decapsulation ....................................................................................................................................... 26
TCP connection establishment .............................................................................................................. 26
What is an IPv4 address? ....................................................................................................................... 27
Classes of IPv4 addresses ..................................................................................................................... 27
Class A ....................................................................................................................................................... 27
Class B ....................................................................................................................................................... 28
Class C ...................................................................................................................................................... 28
Class D ...................................................................................................................................................... 28
Class E ....................................................................................................................................................... 28
NetID and HostID representation of classes ........................................................................................ 28
Subnetting ................................................................................................................................................. 29
Variable Length Subnet Mask (VLSM).................................................................................................. 29
Classless Inter-Domain Routing (Supernetting) .................................................................................. 30
Routing Algorithms ................................................................................................................................... 30
Bellman-Ford Algorithm....................................................................................................................... 30
Dijkstra's Algorithm .............................................................................................................................. 30
Flyod Warshall Algorithm .................................................................................................................... 31
What is a Firewall? ................................................................................................................................... 31
Types of Firewalls .................................................................................................................................... 31
Packet Filtering Firewall ...................................................................................................................... 31
Application Level Gateway Firewall ................................................................................................... 32
Circuit Level Gateway Firewall ........................................................................................................... 32

www.BankExamsToday.Com Page 2
IT Officer Professional Knowledge Guide

What is a Bastion Host? .............................................................................................................................. 33


Network Address Translation (NAT) & its Forms ................................................................................ 33
Static NAT ............................................................................................................................................. 33
Dynamic NAT ........................................................................................................................................ 33
Port Address Translation (NAT Overloading) .................................................................................. 33
Main Uses of NAT .................................................................................................................................... 34
Pooling of IP addresses ...................................................................................................................... 34
Migration between service providers ................................................................................................. 35
IP Masquerading (Network address and port translation) ............................................................. 35
Load Balancing of Servers .................................................................................................................. 36
Computer Architecture - Professional Knowledge .............................................................................. 36
1. CPU.................................................................................................................................................... 36
2. Memory.............................................................................................................................................. 36
3. I/O unit ............................................................................................................................................... 36
Microprocessor ......................................................................................................................................... 37
Arithmetic and Logical Unit (ALU) ..................................................................................................... 37
Control Unit ........................................................................................................................................... 37
Register Sets......................................................................................................................................... 37
Accumulator .......................................................................................................................................... 37
Condition Code Register (CCR)......................................................................................................... 38
Program Counter (PC)......................................................................................................................... 38
Stack Pointer (SP) ................................................................................................................................ 38
Data Bus ................................................................................................................................................ 38
Address Bus .......................................................................................................................................... 38
Control Bus............................................................................................................................................ 38
Microprocessor Clock .......................................................................................................................... 38
Interesting fact about India ..................................................................................................................... 39
Multiplexing and Wireless Transmission - Computer Networks........................................................ 39
Multiplexing ............................................................................................................................................... 39
1. Frequency Division Multiplexing .................................................................................................... 39
2. Time Division Multiplexing .............................................................................................................. 39

www.BankExamsToday.Com Page 3
IT Officer Professional Knowledge Guide

3. Wavelength Division Multiplexing .................................................................................................. 40


4. Code Division Multiplexing ............................................................................................................. 40
Wireless Transmission ............................................................................................................................ 40
1. Radio Transmission ......................................................................................................................... 41
2. Microwave Transmission ................................................................................................................ 41
3. Infrared Transmission ..................................................................................................................... 41
4. Light Transmission........................................................................................................................... 42
Iptables - Network Security ..................................................................................................................... 42
What is Iptable? ........................................................................................................................................ 42
Iptable Tables ........................................................................................................................................... 42
1. Filter table ......................................................................................................................................... 42
2. NAT table .......................................................................................................................................... 42
3. Mangle Table .................................................................................................................................... 43
4. Raw table .......................................................................................................................................... 43
Iptable Rules ............................................................................................................................................. 43
Target Values........................................................................................................................................ 43
Cryptography - Network Security ........................................................................................................... 44
Cryptography............................................................................................................................................. 44
1. Secret Key Encryption..................................................................................................................... 44
2. Public Key Encryption ..................................................................................................................... 45
3. Message Digest ............................................................................................................................... 45
Web Security - Secure Socket Layer (SSL) ......................................................................................... 46
Protocols - Computer Networks ............................................................................................................. 47
Telnet Protocol.......................................................................................................................................... 47
FTP ............................................................................................................................................................. 47
SMTP ......................................................................................................................................................... 47
POP3 .......................................................................................................................................................... 47
IMAP ........................................................................................................................................................... 47
HTTP .......................................................................................................................................................... 48
UDP ............................................................................................................................................................ 48
LDAP .......................................................................................................................................................... 48

www.BankExamsToday.Com Page 4
IT Officer Professional Knowledge Guide

Network Programming Notes ................................................................................................................. 48


What is Inter Process Communication (IPC)? ..................................................................................... 48
What is a file descriptor? ......................................................................................................................... 49
What is a socket? ..................................................................................................................................... 49
Types of Sockets ...................................................................................................................................... 49
 SOCK_STREAM .......................................................................................................................... 49
 SOCK_DGRAM ............................................................................................................................ 49
System Calls using Sockets ................................................................................................................... 49
1. socket( ) ............................................................................................................................................. 49
System Calls using Sockets ................................................................................................................... 50
6. send( ) & recv( ) ............................................................................................................................... 50
7. sendto( ) & recvfrom( ) .................................................................................................................... 50
8. close( ) & shutdown( ) ..................................................................................................................... 51
9. getpeername( ) ................................................................................................................................. 51
10. gethostname( ) ............................................................................................................................... 51
11. gethostbyname( ) ........................................................................................................................... 51
Client Server communication for connection oriented protocols....................................................... 52
Client Server communication for connectionless protocols ............................................................... 52
MCQs ......................................................................................................................................................... 52
Communication Protocols - DHCP and DNS ....................................................................................... 53
Domain Name System (DNS) ................................................................................................................ 53
Firewalls - Computer Networks .............................................................................................................. 55
What is a Firewall? ................................................................................................................................... 55
Types of Firewalls .................................................................................................................................... 55
Packet Filtering Firewall ...................................................................................................................... 55
Application Level Gateway Firewall ................................................................................................... 56
Circuit Level Gateway Firewall ........................................................................................................... 56
What is a Bastion Host? .......................................................................................................................... 57
Communication Protocols - DHCP and DNS ....................................................................................... 57
Domain Name System (DNS) ................................................................................................................ 57
Dynamic Host Configuration Protocol (DHCP) .................................................................................... 58

www.BankExamsToday.Com Page 5
IT Officer Professional Knowledge Guide

Network Address Translation - Computer Networks .......................................................................... 59


Network Address Translation (NAT) & its Forms ................................................................................ 59
Static NAT ............................................................................................................................................. 59
Dynamic NAT ........................................................................................................................................ 59
Port Address Translation (NAT Overloading) .................................................................................. 59
Main Uses of NAT .................................................................................................................................... 60
Pooling of IP addresses ...................................................................................................................... 60
Migration between service providers ................................................................................................. 60
IP Masquerading (Network address and port translation) ............................................................. 61
Load Balancing of Servers .................................................................................................................. 61
Chapter: Database Management System.................................................................................................. 62
Introduction to Database Management System .................................................................................. 62
What is Database? ................................................................................................................................... 62
What is Database Management System? ............................................................................................ 62
Advantages of a DBMS ........................................................................................................................... 62
1. Controls Data Redundancy......................................................................................................... 62
2. Data Sharing ................................................................................................................................. 62
3. Data consistency .......................................................................................................................... 62
4. Integration of Data ........................................................................................................................ 63
5. Data Security................................................................................................................................. 63
6. Backup and Recovery: ................................................................................................................ 63
7. Concurrent Access ....................................................................................................................... 63
Components of DBMS ............................................................................................................................. 63
1. Data.................................................................................................................................................... 63
2. Hardware ........................................................................................................................................... 63
3. Software ............................................................................................................................................ 63
4. Users: ................................................................................................................................................ 63
Levels of Abstraction ............................................................................................................................... 63
1. Physical Level................................................................................................................................... 63
2. Logical Level ..................................................................................................................................... 63
3. View Level ......................................................................................................................................... 64

www.BankExamsToday.Com Page 6
IT Officer Professional Knowledge Guide

The Entity-Relationship Model (ER Model) - DBMS ........................................................................... 64


ER Model ................................................................................................................................................... 64
1. Entity .................................................................................................................................................. 64
2. Attribute ............................................................................................................................................. 65
3. Relationship ...................................................................................................................................... 65
a) Binary Relationship: .................................................................................................................... 65
b) Recursive Relationship ............................................................................................................... 66
c) Ternary Relationship ................................................................................................................... 67
Keys............................................................................................................................................................ 67
Relational Model - DBMS ........................................................................................................................ 67
Relational Model ....................................................................................................................................... 67
Relational Algebra .................................................................................................................................... 67
1. SELECT ............................................................................................................................................ 68
Example: ............................................................................................................................................ 68
2. PROJECT ......................................................................................................................................... 68
Example: ............................................................................................................................................ 68
3. UNION ............................................................................................................................................... 68
4. INTERSECTION .............................................................................................................................. 68
5. DIFFERENCE................................................................................................................................... 69
6. CARTESIAN PRODUCT ................................................................................................................ 69
7. JOIN ......................................................................................................................................................... 70
a) Inner Join ...................................................................................................................................... 70
b) Equi Join ....................................................................................................................................... 70
c) Outer Join ...................................................................................................................................... 70
Normalization in DBMS - PK Series ...................................................................................................... 72
Normalization ............................................................................................................................................ 72
1. First Normal Form (1NF)................................................................................................................. 72
2. Second Normal Form (2NF) ........................................................................................................... 73
3. Third Normal Form (3NF) ............................................................................................................... 74
4. Boyce and Codd Normal Form (BCNF)........................................................................................ 74
SQL in DBMS - PK Series ...................................................................................................................... 75

www.BankExamsToday.Com Page 7
IT Officer Professional Knowledge Guide

SQL Commands ....................................................................................................................................... 75


1. Data Definition Language (DDL) ................................................................................................... 76
2. Data Manipulation Language (DML) ............................................................................................. 76
3. Data Control Language (DCL) ....................................................................................................... 76
4. Data Query Language (DQL) ............................................................................................................. 76
Clauses in SQL ......................................................................................................................................... 76
1. WHERE clause................................................................................................................................. 76
2. LIKE clause ....................................................................................................................................... 76
3. TOP clause ....................................................................................................................................... 77
4. ORDER BY Clause .......................................................................................................................... 77
5. GROUP BY Clause ......................................................................................................................... 77
6. HAVING Clause ............................................................................................................................... 77
SQL Transactions..................................................................................................................................... 78
Advanced SQL in DBMS - PK Series.................................................................................................... 78
User defined types ................................................................................................................................... 78
Integrity Constraints ................................................................................................................................. 79
Types of constraints ................................................................................................................................. 79
ODBC and JDBC...................................................................................................................................... 79
1. Open Database Connectivity (ODBC) .......................................................................................... 79
2. Java Database Connectivity (JDBC) ............................................................................................ 80
SQL Functions .......................................................................................................................................... 80
Aggregate Functions............................................................................................................................ 80
Scalar Functions ................................................................................................................................... 80
Chapter: Operating system ....................................................................................................................... 80
Operating System - Part 1 ...................................................................................................................... 80
Operating System (OS) ........................................................................................................................... 80
Functions of an Operating System ........................................................................................................ 81
1. Boot up the computer ...................................................................................................................... 81
2. Basic computer tasks ...................................................................................................................... 81
3. Provides a user interface ................................................................................................................ 81
4. Handling of System Resources ..................................................................................................... 81

www.BankExamsToday.Com Page 8
IT Officer Professional Knowledge Guide

5. File management ............................................................................................................................. 81


 File Allocation Table (FAT/FAT32) - ...................................................................................... 81
 New Technology file system (NTFS) - .................................................................................. 81
Types of Operating Systems .................................................................................................................. 81
1. Single user, single task OS ............................................................................................................ 81
2. Single user, multi tasking OS ......................................................................................................... 82
3. Multi user OS .................................................................................................................................... 82
4. Real time OS .................................................................................................................................... 82
5. Time sharing OS .............................................................................................................................. 82
6. Distributed OS .................................................................................................................................. 82
7. Network OS....................................................................................................................................... 82
8. Embedded OS .................................................................................................................................. 82
9. Mobile OS ......................................................................................................................................... 82
Operating Systems - Part 2 .................................................................................................................... 83
Graphical User Interface ......................................................................................................................... 83
Microsoft Disk Operating System (MS DOS) ....................................................................................... 83
Processes in OS ....................................................................................................................................... 83
Process State............................................................................................................................................ 84
Process Control Block ............................................................................................................................. 84
Operating Systems - Part 3 .................................................................................................................... 84
Threads ...................................................................................................................................................... 84
What's so good about them? .................................................................................................................. 85
Types of Threads ..................................................................................................................................... 85
1. User level threads ............................................................................................................................ 85
2. Kernel level threads ......................................................................................................................... 85
Multi threading models ............................................................................................................................ 85
1. Many to One ..................................................................................................................................... 85
2. One to One ....................................................................................................................................... 86
3. Many to Many ................................................................................................................................... 86
Thread Libraries ....................................................................................................................................... 87
Issues related to Threads ....................................................................................................................... 87

www.BankExamsToday.Com Page 9
IT Officer Professional Knowledge Guide

1. Fork ( ) system call .......................................................................................................................... 87


2. Signal Handling ................................................................................................................................ 87
3. Thread Cancellation ........................................................................................................................ 87
Operating Systems - Part 4 .................................................................................................................... 88
Critical Section .......................................................................................................................................... 88
1. Mutual Exclusion .............................................................................................................................. 88
2. Progress ............................................................................................................................................ 88
3. Bounded Waiting .............................................................................................................................. 88
Semaphores .......................................................................................................................................... 89
Deadlock and Starvation ......................................................................................................................... 89
CPU Scheduling ....................................................................................................................................... 89
Dispatcher ................................................................................................................................................. 90
Operating System (CPU Scheduling) - Part 5 ..................................................................................... 90
Scheduling Criteria for Processes ......................................................................................................... 90
Scheduling Algorithms ............................................................................................................................. 90
1. First Come First Served Scheduling (FCFS) ............................................................................... 90
2. Shortest Job First Scheduling (SJF) ............................................................................................. 91
3. Priority Scheduling ........................................................................................................................... 91
4. Round Robin Scheduling ................................................................................................................ 92
5. Multi Level Queue Scheduling ....................................................................................................... 93
6. Thread Scheduling........................................................................................................................... 93
Practice MCQs.......................................................................................................................................... 93
Operating System (Memory Management) - Part 6 ............................................................................ 94
Dynamic Loading and Linking ................................................................................................................ 94
Swapping ................................................................................................................................................... 94
Paging ........................................................................................................................................................ 94
Virtual Memory.......................................................................................................................................... 95
Page Replacement................................................................................................................................... 95
Operating Systems (File System) - Part 7 ............................................................................................ 96
What is a file? ........................................................................................................................................... 96
File Format and File Access Methods ................................................................................................... 96

www.BankExamsToday.Com Page 10
IT Officer Professional Knowledge Guide

File system Layers ................................................................................................................................... 97


Partitions and Mounting........................................................................................................................... 98
Chapter: C Programming ........................................................................................................................... 98
C Programming ........................................................................................................................................... 98
C PROGRAMMING LANGUAGE STANDARDS:.............................................................................................. 99
C11 AND EMBEDDED C LANGUAGE: ........................................................................................................... 99
FEATURES OF C PROGRAMMING LANGUAGE: ........................................................................... 99
USES OF C PROGRAMMING LANGUAGE: ..................................................................................... 99
C LANGUAGE IS A STRUCTURED LANGUAGE: ......................................................................... 100
KEY POINTS TO REMEMBER IN C LANGUAGE: ......................................................................... 100
C – Programming Basics ................................................................................................................... 101
1. C PROGRAMMING BASICS TO WRITE A C PROGRAM: ....................................................... 101
2. A SIMPLE C PROGRAM: ................................................................................................................ 102
3. STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT: ................................................. 102
4. CREATION, COMPILATION AND EXECUTION OF A C PROGRAM: ................................... 103
5. BASIC STRUCTURE OF A C PROGRAM: .................................................................................. 103
EXAMPLE C PROGRAM TO COMPARE ALL THE SECTIONS: ................................................ 103
DESCRIPTION FOR EACH SECTION OF THE C PROGRAM: ................................................... 104
KEY POINTS TO REMEMBER IN C PROGRAMMING BASICS: ................................................ 106
Declaration of Variable ................................................................................................................... 110
Declaration of variable in c can be done using following syntax: ............................................... 110
data_type variable name; or data_type variable1, variable2,…,variablen; ............................... 110
Where data_type is any valid c data type and variable_name is any valid identifier............... 110
For example, ....................................................................................................................................... 110
 Initialization of Variable .......................................................................................................... 111
C variables declared can be initialized with the help of assignment operator „=‟. .................... 111
 Syntax ......................................................................................................................................... 111
data_type variable name=constant/literal/expression; or variable
name=constant/literal/expression; ................................................................................................... 111
Example ............................................................................................................................................... 111
Constant and Volatile Variables ....................................................................................................... 111
Constant Variables ......................................................................................................................... 111

www.BankExamsToday.Com Page 11
IT Officer Professional Knowledge Guide

Volatile Variables ............................................................................................................................ 111


C – Array.................................................................................................................................................. 112
Dynamic memory allocation ................................................................................................................. 115
C++ PROGRAMMING ....................................................................................................................... 123
C++ and Object Oriented Programming.................................................................................................... 124
OOPS Concept Definitions ........................................................................................................... 125
Chapter : C++ Programming .................................................................................................................... 126
Data Encapsulation Example: ................................................................................................................ 127
Base & Derived Classes:........................................................................................................................ 129
Access Control and Inheritance: ............................................................................................................. 130
Type of Inheritance: ................................................................................................................................ 130
Multiple Inheritances: .............................................................................................................................. 131
The Class Constructor:........................................................................................................................... 133
Parameterized Constructor:.................................................................................................................... 134
Using Initialization Lists to Initialize Fields:................................................................................................ 135
The Class Destructor:............................................................................................................................. 135
Opening a File: ....................................................................................................................................... 137
Closing a File.......................................................................................................................................... 138
Writing to a File:...................................................................................................................................... 138
Reading from a File: ............................................................................................................................... 138
Read & Write Example: .......................................................................................................................... 138
File Position Pointers: ............................................................................................................................. 140
Operators overloading in C++:................................................................................................................ 140
Overloadable/Non-overloadableOperators: ............................................................................................ 142
Operator Overloading Examples: ........................................................................................................... 143
Function overloading in C++: .................................................................................................................. 144
Function Template:................................................................................................................................. 146
Class Template: ..................................................................................................................................... 147
Throwing Exceptions: ............................................................................................................................. 150
Catching Exceptions:.............................................................................................................................. 151
C++ Standard Exceptions:...................................................................................................................... 152

www.BankExamsToday.Com Page 12
IT Officer Professional Knowledge Guide

The new and delete operators: ............................................................................................................... 155


Dynamic Memory Allocation for Arrays: .................................................................................................. 156
Dynamic Memory Allocation for Objects: ................................................................................................ 157
Chapter: Java Programming ...................................................................................................................... 157
Java Tutorial .............................................................................................................................................. 157
Audience.................................................................................................................................................... 158
Prerequisites .............................................................................................................................................. 158
Execute Java Online .................................................................................................................................. 158
Java – classes............................................................................................................................................ 158
Nested Classes................................................................................................................................... 158
Inner Classes (Non-static Nested Classes) ................................................................................... 158
Inner Class ...................................................................................................................................... 159
Accessing the Private Members .................................................................................................. 159
Method-local Inner Class .................................................................................................................. 160
 Anonymous Inner Class ............................................................................................................ 160
Anonymous Inner Class as Argument ............................................................................................ 161
Static Nested Class............................................................................................................................ 161
Nested Classes................................................................................................................................... 161
Inner Classes (Non-static Nested Classes) ................................................................................... 162
Inner Class ...................................................................................................................................... 162
Accessing the Private Members .................................................................................................. 162
Method-local Inner Class .................................................................................................................. 163
Anonymous Inner Class .................................................................................................................... 163
Anonymous Inner Class as Argument ............................................................................................ 164
Static Nested Class............................................................................................................................ 164
Loop Control............................................................................................................................................ 164
Loop Control Statements .................................................................................................................. 165
Enhanced for loop in Java ................................................................................................................ 165
Syntax .............................................................................................................................................. 165
Example ........................................................................................................................................... 165
Output............................................................................................................................................... 166

www.BankExamsToday.Com Page 13
IT Officer Professional Knowledge Guide

Multithreading ......................................................................................................................................... 166


Life Cycle of a Thread ....................................................................................................................... 166
Thread Priorities ................................................................................................................................. 167
Create a Thread by Implementing a Runnable Interface ............................................................. 167
Step 1 ............................................................................................................................................... 167
Step 2 ............................................................................................................................................... 167
Step 3 ............................................................................................................................................... 167
Example ........................................................................................................................................... 167
Output............................................................................................................................................... 168
Access Modifiers .................................................................................................................................... 168
Default Access Modifier - No Keyword ........................................................................................... 168
Example ........................................................................................................................................... 168
Private Access Modifier - Private ..................................................................................................... 169
Example ........................................................................................................................................... 169
Public Access Modifier - Public ........................................................................................................ 169
Example ........................................................................................................................................... 169
Protected Access Modifier - Protected............................................................................................ 169
Example ........................................................................................................................................... 170
Access Control and Inheritance ................................................................................................... 170
Assignment Operators ........................................................................................................................... 170
Example ............................................................................................................................................... 170
Output .................................................................................................................................................. 171
Java Garbage Collection ....................................................................................................................... 171
Advantage of Garbage Collection ................................................................................................ 171
How can an object be unreferenced? ............................................................................................. 171
1) By nulling a reference: .............................................................................................................. 171
2) By assigning a reference to another: ...................................................................................... 171
3) By annonymous object: ............................................................................................................ 171
finalize() method ................................................................................................................................. 172
gc() method ......................................................................................................................................... 172
Simple Example of garbage collection in java ........................................................................... 172

www.BankExamsToday.Com Page 14
IT Officer Professional Knowledge Guide

Exceptions ............................................................................................................................................... 172


Example ........................................................................................................................................... 173
Output............................................................................................................................................... 173
Example ........................................................................................................................................... 173
Output............................................................................................................................................... 174
Exception Hierarchy ........................................................................................................................... 174
Exceptions Methods........................................................................................................................... 174
Catching Exceptions .......................................................................................................................... 175
Syntax .............................................................................................................................................. 175
Example ........................................................................................................................................... 175
Output............................................................................................................................................... 175
Multiple Catch Blocks ........................................................................................................................ 176
Syntax .............................................................................................................................................. 176
Example ........................................................................................................................................... 176
Catching Multiple Type of Exceptions ............................................................................................. 176
The Throws/Throw Keywords........................................................................................................... 176
Example ........................................................................................................................................... 177
Example ........................................................................................................................................... 177
The Finally Block ................................................................................................................................ 177
Syntax .............................................................................................................................................. 177
Example ........................................................................................................................................... 177
Output............................................................................................................................................... 178
The try-with-resources ....................................................................................................................... 178
Example ........................................................................................................................................... 178
Syntax .............................................................................................................................................. 178
Example ........................................................................................................................................... 179
User-defined Exceptions ................................................................................................................... 179
Example ........................................................................................................................................... 179
Output............................................................................................................................................... 180
Common Exceptions .......................................................................................................................... 180
Data Structure and Algorithms - Linked List ...................................................................................... 180

www.BankExamsToday.Com Page 15
IT Officer Professional Knowledge Guide

Linked List Representation ............................................................................................................... 181


Types of Linked List ........................................................................................................................... 181
Basic Operations ................................................................................................................................ 181
Insertion Operation............................................................................................................................. 181
Deletion Operation ............................................................................................................................. 181
Reverse Operation ............................................................................................................................. 182
What is a Stack?..................................................................................................................................... 182
Basic operations of Stacks ................................................................................................................... 182
Example of using Stacks ....................................................................................................................... 183
Heap Data Structures ............................................................................................................................ 190
Max Heap Construction Algorithm ................................................................................................... 190
Max Heap Deletion Algorithm........................................................................................................... 191
Hashing, Hash Data Structure and Hash Table ........................................................................ 191
Data Structure - Graph Data Structure ............................................................................................... 192
Graph Data Structure......................................................................................................................... 192
Basic Operations ................................................................................................................................ 193
Chapter : Data Structures ......................................................................................................................... 194
Data Structure and Algorithms Tutorial .................................................................................................... 194
Audience.................................................................................................................................................... 194
Prerequisites .............................................................................................................................................. 194
Compile and Execute C Online................................................................................................................... 194
1. Arrays declarations and initialization .............................................................................................. 195
2. Multi-dimensional arrays ................................................................................................................... 196
3. Arrays Manipulation ........................................................................................................................... 196
Algorithms Basics ...................................................................................................................................... 198
Characteristics of an Algorithm ........................................................................................................ 198
How to Write an Algorithm? .............................................................................................................. 198
Example ........................................................................................................................................... 198
Algorithm Analysis .............................................................................................................................. 199
Algorithm Complexity ......................................................................................................................... 199
Space Complexity .............................................................................................................................. 200

www.BankExamsToday.Com Page 16
IT Officer Professional Knowledge Guide

Time Complexity ................................................................................................................................. 200


Data Structure - Sorting Techniques ................................................................................................... 200
In-place Sorting and Not-in-place Sorting ...................................................................................... 200
Stable and Not Stable Sorting .......................................................................................................... 201
Adaptive and Non-Adaptive Sorting Algorithm .............................................................................. 201
Important Terms ................................................................................................................................. 201
Increasing Order ............................................................................................................................. 201
Decreasing Order ........................................................................................................................... 201
Non-Increasing Order .................................................................................................................... 201
Non-Decreasing Order .................................................................................................................. 202

Chapter – Networking

Network Infrastructure Devices and Topologies

Hub
Hub is a common connection point for devices in a network. Hubs are commonly used to
connect segments of a LAN. It contains multiple ports. When a packet arrives at one of its ports,
it transmits that packets to all the ports. Hence you may have poor response times in a network
where Hubs are used. If two network devices on the same network try to send packets at the
same time, a collision is said to occur. Hubs are considered to operate at physical layer (layer 1
of OSI model). Network switches are rapidly replacing Hubs.

Switch
A device that filters and forwards packets between LAN Segments. It receives incoming data
packets and redirects them to a particular destination. It uses hardware address (MAC) for

www.BankExamsToday.Com Page 17
IT Officer Professional Knowledge Guide

this purpose. A switch typically operates at data link layer (Layer 2) of OSI model but it can
support all types of packet protocols.

Router
It uses information from network layer (Layer 3) to direct packets through the network. Also it
uses a combination of hardware and software to route datafrom source to destination.It
segments large networks in to logical segments called subnets. We'll be dealing with subnetting
in a separate article.

Differences between Hub, Switch and Router


Network communications in a hub might result in collisions as many devices may attempt to
communicate at the same time while in a switch a kind of electronic tunnel is created between
source and destination in which on other traffic can enter. Router on the other hand, has an
additional ability to forward packets between different networks while Hubs and Switches cater
to one same network.

Firewall
A firewall is used to protect network's data and resources from outside threats or unauthorized
access. Firewalls can be hardware of software but an ideal one is a combination of two.

www.BankExamsToday.Com Page 18
IT Officer Professional Knowledge Guide

Network Topologies

Bus Topology
A network type in which every computer and network device is connected to a single cable. It
transmits data in only one direction.

Advantages: cost effective, useful in small networks, easy to understand and expand joining 2
cables together.

Disadvantages: network crashes if cable fails, in heavy traffic-performance decreases.

Ring Topology
A network type in which each computer is connected to another computer forming a ring. Each
device will have 2 neighbors. Data transfer is sequential i.e bit by bit. Repeaters are used to
avoid packet loss and signal strength.

Advantages: Transmitting not affected by heavy traffic, cheap to install and expand.

Disadvantages: Difficult troubleshooting, whole network disturbed if one computer fails.

Star Topology
All computers (nodes) are connected to a single hub (central node) through a cable. Each node
has a dedicated network to the hub. It can be set up with twisted pair, coaxial and optical fibre
cable, all.

Advantages: Easy troubleshooting (failed computer can be detected easily), Easy to set up and
modify, Fast performance.

www.BankExamsToday.Com Page 19
IT Officer Professional Knowledge Guide

Disadvantages: High cost of installation, problem in central node affects whole network,
performance based entirely on capacity of hub.

Mesh Topology
Point to point connection to other nodes and devices. Packets are transmitted only between
connected nodes. While setting up, partial mesh or full mesh can be implemented depending
upon if you want to connect all or some nodes.

Advantages: Each connection carries its own data load, easy to troubleshoot, provides security
and privacy.

Disadvantages: difficult installation and configuration, bulk wiring required.

Tree Topology
All nodes are connected to root node forming a hierarchy. It should have at least 3 levels to
hierarchy. It is mostly used in WANs.

Advantages: Easy expansion, Easy maintenance, Easy troubleshooting.

Disadvantages: Costly, Bulk cabling required.

www.BankExamsToday.Com Page 20
IT Officer Professional Knowledge Guide

Hybrid Topology
A network type where two or more topologies are mixed. Mostly used in WANs. Mostly used
hybrid topology is a combination of Star-Bus or Star-Ring networks.

Advantages: Reliable, good points of both increases scalability.

Disadvantages: Design complexity, High cost of setting up.

Computer networks can be logically classified into the following:

1. Peer to Peer Networks


2. Client- Server Networks
3. Centralized Networks
4. Distributed Networks

Peer to Peer Networks


Peer to peer network is created when 2 or more PCs are connected and share resources
without going through a separate server computer. In this each party has same capabilities and
any of them can start a communication session unlike client/server model where client makes a
request and server responds. Most P2P applications are used for media sharing. E.g. -
BitTorrent.

Client Server Network


Designed for end users, clients make requests to server for browsing, emailing and accessing
resources such as files, songs and other data. Often clients and servers have separate
hardware but they can reside in one system also. Advantage of this mechanism is the central
management of the server which hosts resources to serve various clients.

www.BankExamsToday.Com Page 21
IT Officer Professional Knowledge Guide

Centralized Network
A network where all users connect to the central server. This server would usually store both
communications and user account information. This central server would usually be set up in
Head Office or Data Centres in a dedicated server room with multiple terminals attached to
central server. It provides better security over decentralized network due to all processing being
managed at a single location. Major disadvantage would be saving that central server from
catastrophes which might crash the entire system.

Difference between a client server and centralized network would be that in centralized network,
database having all the data is located at one place, not distributed among various databases
across different locations. A mainframe network architecture can be considered to be
centralized network

Distributed Network
The network resources are placed and managed from different geographical locations or spread
over more than one computer. Client Server architecture is an example of distributed network
only. These days most of the enterprise network are distributed networks.

Type of servers used in a network

File Server
File servers are used to store the documents and files centrally. An ideal file server should have
large amount of memory and storage space, fast hard disks, multiple processors, redundant
power supplies. A file server runs File Transfer Protocol (FTP) on port 20 usually for FTP data
transfer.

Print Server
It redirects print jobs from client computers to specific printers.

www.BankExamsToday.Com Page 22
IT Officer Professional Knowledge Guide

Mail Server
Main Servers are used to transmit emails using email protocols like SMTP on port 25 (simple
mail transfer protocol) which is an outgoing mail server. Incoming mail server is POP3 on port
110 (post office protocol, version 3)

Application Server
It provides the business logic for an application program.It is usually viewed as a part of 3 tier
application consisting of GUI at first layer, application server at second later and database
server at third layer. Application servers work with HTTP (Hyper text transfer protocol, port 80)

Database Server
It allows authorized clients to create, view, modify, update or delete an organization's data,
stored in common database. E.g. - IBM DB2, MySQL, Sybase, Oracle.

Directory Server
They allow the central administration and management of network users and network
resources. Directory servers provide the basic functions of network security, authentication,
authorization and accounting. E.g. - MS active directory, Open LDAP.

Open System Interconnection (OSI) Model


International Standards Organization (ISO) in 1977 proposed the OSI model. It was done so
that national and worldwide communication systems can be designed which are compatible to
each other.

With this model, we can understand how software and hardware work with each other and
troubleshooting gets easier with known functions of respective layers.

It consists of a 7 layer architecture as follows:

www.BankExamsToday.Com Page 23
IT Officer Professional Knowledge Guide

Layer 1: The Physical Layer


It activates, maintains and deactivates the physical connection. Although transmission of
each bit of data is a responsibility of this layer but its not that reliable as there is no error
detection mechanism at this layer. Network design is an integral part of this layer. Remember
we learned about infrastructure devices and topologies in last article!

Layer 2: Data Link Layer


It provides a reliable transmission of packets using the services of physical layer. Major
functions are as follows:

 Framing- breaks input data into frames, frame size and boundaries are also taken care of
by this layer.
 Acknowledgement- from receiver to source confirming the frame received without error or
with error.
 Retransmission- Frame is retransmitted if source fails to receive acknowledgement.
 Sequence Numbering- to acknowledge which frame was received.
 Error detection- Frames may be lost, damaged or duplicated leading to errors. Detection
is on a link to link basis.
 Flow Control- Necessary for a fast transmitter to keep pace with a slower one.

Layer 3: Network Layer


Basic functions of this layer are routing and congestion control. It routes the signals through
different channels/routes thereby acting like a network controller. It divides the outgoing
messages into packets and incoming packets in to messages for higher layers.

Please note that network layer doesn't guarantee that packet will reach its intended destination.

www.BankExamsToday.Com Page 24
IT Officer Professional Knowledge Guide

Layer 4: Transport Layer


It decides if data transmission should be parallel path or single path. Other major functions
are multiplexing/demultiplexing (using port numbers), Fragmentation/ Re-assembly,
sequencing, error control, flow control.

Layer 5: Session Layer


This layer is responsible for establishing, managing and terminating sessionsbetween end
user applications. Authentication and Authorization(implemented through remote procedure
calls) are other services provided by this layer. Sessions are usually implemented on web
browsers. Also, it works in tandem with the transport layer.

Layer 6: Presentation Layer


Data is formatted at this layer before passing down to other layers on sender's side. Formatting
functions include compression, encryption, compatible character code set (ASCII, EBCDIC
etc). It serves as data translator for the network, sometimes called syntax layer.

Layer 7: Application Layer


This layer interacts with the user and user applications. Real traffic data is generated from
this layer, that may be a browsing request from HTTP, command from TELNET or a file
download request from FTP. It only standardizes communication but depends on transport layer
for establishing data transfer channels.

TCP/IP
Transmission control protocol/Internet Protocol (TCP/IP) is suite of communication protocols
used to connect hosts on the internet. It uses several protocols, two main ones
being TCP and IP. Lets quickly understand the differences between OSI model and TCP/IP
model:

 OSI is a generic, protocol independent standard while TCP/IP is the standard around
which Internet has developed.
 TCP/IP has 4 in comparison to 7 layers of OSI.
 OSI uses bottom up approach while TCP/IP uses top down approach.
 TCP/IP combines the OSI Data link and Physical layer into Network access layer.
 OSI is reference model while TCP/IP is an implementation of it.
Take a look at the diagram below to understand effectively.

www.BankExamsToday.Com Page 25
IT Officer Professional Knowledge Guide

The higher layer i.e TCP assembles the message into smaller packets. A header is added to the
data which includes source and destination addresses, a sequence number, acknowledgement
number and a checksum for error detection. At receiving end, TCP reassembles the packets in
the correct order and routes them up to application. It retransmits a packet if error occurs. TCP's
main job is to pack and unpack (encapsulation and decapsulation) the data and provide a
reliable transmission of error free data.

IP layer transmits the packets over a physical layer connection. IP adds its ownheader (IPv4) to
the packet, well known as IP address (32 bit addresses). This is the address assigned to device
by Internet Assigned Numbers Authority (IANA).

Encapsulation and Decapsulation

Encapsulation
Packing of data at each layer of TCP/IP protocol stack is known as encapsulation. When data
moves from upper to lower layers (outgoing), each layer includes some information (header) at
the start of the block which is repackaged at lower and further lower layers with their own
headers thus making data packet an encapsulated one.

Decapsulation
When data is received on destination's side, reverse process happens. Data moves up the
layers (incoming) and each layer unpacks the corresponding header and delivers the packet to
exact network application data waiting for it.

TCP connection establishment


The 'three way handshake' procedure is used to establish a connection as it reduces the
possibility of false connections. SYNchronize and ACKnowledgement segments are used as
per figure below:

www.BankExamsToday.Com Page 26
IT Officer Professional Knowledge Guide

As you can see Host A initiates the connection request with SYN which is received and
acknowledged by Host B. A then sends acknowledgement for B's acknowledgement along with
data. Data transfer between the two begins then.

TCP connection is duplex. There is no difference between two sides once the connection is
established.

What is an IPv4 address?


IPv4 address is a 32 bit address that uniquely defines the connection of a host to internet.
Each byte, or 8 bit segment of the address, is divided by a period and typically expressed as a
number 0-255. Each segment is referred to as an octet.

A typical IPv4 address looks like 192.168.0.2 (lowest value - 0, highest value- 255).

The address space of IPv4 is 2^32 (2 raise to power 32).

Classes of IPv4 addresses


IPv4 addresses are divided into 5 classes, named A through E, meant to differentiate segments
of the available addressable IPv4 space. These are defined by first 4 bits of each address.
Below, we find the description of classes.

Class A
The range of class A addresses is from 0.0.0.0 to 127.255.255.255. The first octet is used to
identify the network and remaining three octets for identifying host (network.host.host.host).

This class is usually used for large networks. The address 127.0.0.1 is known as loopback
address (localhost) and is used for testing network testing.

Class A addressing can have 126 networks (27-2) and (224-2) hosts as here 8 bits are for
network and 24 bits are for hosts. we must also know that first IP of the network is network

www.BankExamsToday.Com Page 27
IT Officer Professional Knowledge Guide

number and last IP is reserved for broadcast IP. Hence we have decreased 2 IP addresses
above.

Class B
Class B includes addresses from 128.0.0.0 to 191.255.255.255. Here, first 16 bits are used to
identify network and remaining 16 bits for identifying hosts (network.network.host.host)

This class is usually used for mid-size networks.

Class B has 214 network addresses and 216-2 host addresses.

Class C
Class C includes addresses from 192.0.0.0 to 223.255..255.255. This class is used for small to
mid sized networks.

Class C has 221 network addresses and 28-2 host addresses.

Class D
Class D includes addresses from 224.0.0.0 to 239.255.255.255. These are known as multicast
addresses. In multicasting, data is not destined for a particular host that is why no need to
extract host address from the IP address.

Class E
This class includes addresses from 240.0.0.0 to 255.255.255.255. These addresses are
reserved for future and experimental use and are largely not used.

NetID and HostID representation of classes


The figure below will give you a fair amount of idea about what we discussed about octets
reserved for networks and hosts in each class.

www.BankExamsToday.Com Page 28
IT Officer Professional Knowledge Guide

Subnetting
Subnetting is used to divide a single physical network into more than smaller logical
subnetworks (Subnets). It allows more efficient utilization of the addresses. As we know an ip
address contains a network part and a host part. In subnetting, host bits are borrowed by
network bits to represent the sub networks inside a network. Class A,B and C have default
subnet masks as follows:

Class A - 255.0.0.0 | 11111111 00000000 00000000 00000000

Class B - 255.255.0.0 | 11111111 11111111 00000000 00000000

Class C - 255.255.255.0 | 11111111 11111111 11111111 00000000

Example

Apply subnet mask 255.255.0.0 to IP 10.0.0.0 (A class). The 255.255.0.0 borrows borrows a
portion of host space of A and applies to network space thereby splitting one large network into
256 subnets from 10.0.0.0 to 10.255.0.0. Each subnetwork then will have 16 bits for host
addresses instead of 24 bits which is default for A class addresses.

Variable Length Subnet Mask (VLSM)


According to this concept, the same network can be configured with different masks. We
can have subnets of different sizes depending upon the requirement.

Lets consider a case where we have a class C network 192.203.17.0. We are required to divide
it into 3 subnets for 3 diff departments of an office with 110, 45 and 50 hosts respectively.

Default subnet mask for C class is of the form 255.255.255.X.

We'll use the mask 255.255.255.128 to divide it into 2 subnets with 128 hosts each.

192.203.17.0 (.0 to .127) - 110 hosts for Dept 1 will be handled with this.

192.203.17.0 (.128 to .255) - requires further subnetting.

www.BankExamsToday.Com Page 29
IT Officer Professional Knowledge Guide

We'll now subnet the second one using a mask of 255.255.255.192 which will have 64 hosts for
each subnet of 2nd subnet.

192.213.17.128 (.128 to .191) - 45 hosts for Dept 2

192.213.17.128 (.192 to .255) - 50 hosts for Dept 3

Here a diagrammatic representation below will make it more clear to you.

Classless Inter-Domain Routing (Supernetting)


 Introduced due to growing demand of IP addresses and wastage of addresses space.
 More flexible way of allocating IPs than traditional class based approach.
 Reduces size of routing tables.
 An IP address is followed by '/ number' called the IP network prefix.
 'Number' represents the leftmost bits that make the network part of the address leaving
remaining bits for hosts. Ex- 192.60.128.0 / 22 indicates that 22 bits are for network and
remaining 10 for hosts.
 Supported by BGP and OSPF, not supported by RIP

Routing Algorithms

Bellman-Ford Algorithm
In this algorithm, routers know about their neighbors and their costs to different subnets that
they have to reach.

Time Complexity- O(N3)

Dijkstra's Algorithm
In this algorithm, all the routers in a network have knowledge of complete network. This is also
called link state algorithm.

www.BankExamsToday.Com Page 30
IT Officer Professional Knowledge Guide

Time Complexity - O(N2)

Flyod Warshall Algorithm


In this algorithm, all nodes can be a source and it finds the shortest path between all pairs of
vertices in a graph. It is much slower than the other two algorithms.

Time complexity- O(N3)

What is a Firewall?
A firewall is a device designed to control the flow of traffic into and out-of a network. In
general, firewalls are installed to prevent attacks. It disrupts free communication between a
trusted and un-
trusted network in order to mange the information flow and restrict unwarranted dangerous
access.

Hardware firewall is a physical device between internet and your computer while Software
firewall is installed as a program on computer.

Types of Firewalls
Packet Filtering Firewall

It applies a set of rules to each incoming packet and then forwards/discards(two default
policies) the packet. It filters packets going in both directions. The packet filter is typically set
up as a list of rules based on matches to fields in IP or TCP header. Some of the attacks that
can be made on packet filtering routers are: IP address spoofing, Source Routing attacks,
Tiny Fragment attacks.

Advantages: Simplicity, transparency to users and high speed.


Disadvantages: Difficult to set up, lack of authentication.

www.BankExamsToday.Com Page 31
IT Officer Professional Knowledge Guide

Application Level Gateway Firewall

In this, when a client establishes connection with the destination service, it connects to an
application gateway. It is also called a proxy server. The proxy then establishes the connection
with destination behind the firewall and acts on behalf of client, making all packet forwarding
decisions. It acts as a relay of application level traffic. Also, it needs separate proxies for
each service- SMTP, DNS and other custom services.

Advantages: Higher security than packet filters, Easy to log and audit all incoming traffic.
Disadvantages: Requires great memory and processor resources.

Circuit Level Gateway Firewall

This firewall works at session layer of OSI model. Traffic is allowed only if a session request is
legitimate. It sets up two TCP connections. The gateway typically relays TCP segments from
one connection to other without examining the contents and security function determines
whether to allow it further or not. A proxy server as explained above is a security barrier
between internal and external computers while a circuit level gateway is a virtual circuit
between proxy server and internal hosts.

Advantages: Hides private network data, doesn't need a separate proxy server for each

www.BankExamsToday.Com Page 32
IT Officer Professional Knowledge Guide

application, simple to implement.


Disadvantages: Doesn't filter individual packets, attacker may take advantage after
establishing a connection.

What is a Bastion Host?


It is a system identified by firewall administrator as a crucial point in network's security. It
executes a secure version of OS and is trusted. It requires additional authentication before
access is allowed. It is designed specifically to withstand attacks as it is on public side of the
network. Firewalls and Routers can be considered as Bastion Hosts.

Network Address Translation (NAT) & its Forms


Allows a single device to act as an agent between Internet and private network. Only 1
unique IP address is required to represent an entire group of computers.

Static NAT
It has one to one mapping between private and public addresses i.e one public IP for every
private IPs in private network. The only benefit is that it allows a server inside private network to
be reachable over internet through one to one translation.

Dynamic NAT
It has many to many mapping between private and public addresses. It maps an unregistered
IP address to a registered one from a pool of registered IP addresses in NAT router. Addresses
are assigned dynamically.

Port Address Translation (NAT Overloading)


It maps multiple private IPs to a single public IP i.e many to one mapping. Each computer on
private network gets translated to the same public IP but with a different port number
assignment.

Suppose an internal host A tries to connect to a web server outside. NAT enabled router will
save private IP and source port from A's packet to an Address Translation Table (ATT). It then

www.BankExamsToday.Com Page 33
IT Officer Professional Knowledge Guide

replaces private IP with the router's IP address, generates a new port for new connection and
forwards the packet over internet. Now when the return packet from web server reaches the
router, it uses destination port to search ATT, obtains the private address and port numbers
mapped to it and sends it to original sender.

The Address Translation Table looks like:

Main Uses of NAT

Pooling of IP addresses
Suppose a corporate network has many hosts but only a small number of public IP addresses. It
uses private address space for hosts and when a host send an IP datagram to a host in public
internet, NAT device picks up a public IP from the pool and binds it to private address of the
host.

www.BankExamsToday.Com Page 34
IT Officer Professional Knowledge Guide

Migration between service providers


In CIDR, IP addresses in a corporate network are obtained from service provider. Changing the
service provides requires changing all IP addresses in the network. Now, this NAT device has
static address translation entries which bind the private addresses to public addresses.
Migration to a new service provider merely requires an update of NAT device and this migration
won't be noticeable to hosts on the network.

IP Masquerading (Network address and port translation)


As we have assigned private addresses to hosts of the network above, NAT device will modify
the port numbers for outgoing traffic. The literal meaning of masquerading is- pretending to
be someone/something which you're not.

www.BankExamsToday.Com Page 35
IT Officer Professional Knowledge Guide

Load Balancing of Servers


Suppose we have to balance the load on a set of identical servers, which are accessible from a
single IP address. With concept of NAT, we will assign them pvt addresses and NAT device will
act as a proxy for requests to server from public network. It will change the destination IP of
incoming packets to one of pvt address of a server. Usually the servers are assigned addresses
in a round robin fashion.

One more important thing to learn is that NAT is not a proxy server. NAT is transparent to both
source and destination hosts but proxy server is not transparent. Also NAT is a layer 3 (network)
protocol while proxy server works at layer 4 (transport) or higher.

Computer Architecture - Professional Knowledge


A basic computer system consists of the following components :-

1. CPU
Central processing unit is that core element of a computer system that carries out instructions of
a computer program by performing basic arithmetic, logical, control and I/O operations.

2. Memory
Every computer has 2 types of main memories - RAM and ROM

Random Access Memory can be read and written to anytime the CPU instructs it. Contents of
RAM are erased when the computer is turned off whereas Read Only Memory is pre-loaded
with data and software that never changes. ROM is typically used to store computer's initial
start up instructions.

3. I/O unit
I/P refers to the communication between a computer and outer world. Input are signals/data
received by system and Output are signals sent by it. Peripheral devices provide input/output to
the system. Peripherals include input devices like keyboard, mouse and output devices like

www.BankExamsToday.Com Page 36
IT Officer Professional Knowledge Guide

display screen or printer. Hard disk and optical disk devices act as both input and output
devices.

Block diagram for basic computer architecture is given below:

Microprocessor
It is a programmable integrated device which has the capacity of computing & decision making.
It communicates with the system in binary numbers 0 &1. Every microprocessor has fixed set
of instruction in the form of binary patterns known as machine language. Various components of
a microprocessor are described below:

Arithmetic and Logical Unit (ALU)


It is the most important component of a microprocessor that performs the arithmetical and
logical operations like AND, OR, NAND, NOR, Addition and Subtraction.

Control Unit
Its the circuit that controls the flow of information through processor and coordinates the
activities of other units within it. With a regular processor, control unit performs tasks of fetching,
decoding, managing execution and storing results.

Register Sets
Register sets temporarily store data and program codes until they are sent to ALU or control
section. More registers per cpu results in programming tasks easily. Registers are measured by
no of bits i.e 8 bit, 16 bit, 32 bit.

Accumulator
Its a register in which intermediate arithmetic and logical results are stored. Initially set to zero,
each number after operation is added into it and finally results are sent to main memory or to
another register.

www.BankExamsToday.Com Page 37
IT Officer Professional Knowledge Guide

Condition Code Register (CCR)


Its an 8 bit register used to store the status of CPU such as carry, zero, overflow and half carry.

Program Counter (PC)


Its a 16 bit register used to store the next address of the operation code to be fetched by CPU

Stack Pointer (SP)


Stack is a data structure that grows downward from high memory to low memory. SP holds the
16 bit address of the next free location in the stack. On a subroutine call or interrupt it pushes
the return address and retrieves it when the operation is complete.

Data Bus
A subsystem which transfer the data between different components of a computer. Its bi
directional in nature and depending upon the microprocessor it can handle 8 bit or 16 bit data.

Address Bus
It is unidirectional in nature over which microprocessor sends an address code to the memory
or I/O. The more bits in an address bus enables microprocessor to access more locations. A 16
bit address bus is capable of handling 64K addresses.

Control Bus
Control bus is used by microprocessor to send out or receive timing and controlsignals in
order to coordinate and regulate its operation and to communicate with other devices.

Microprocessor Clock
Its the speed at which microprocessor executes instructions, also called clock rate. Clock rate
is expressed in MHz or GHz.

Block diagram for microprocessor is given below for further understanding:

www.BankExamsToday.Com Page 38
IT Officer Professional Knowledge Guide

8085 is an 8 bit microprocessor introduced by Intel in 1977 while 8086 is a 16


bit microprocessor chip by Intel only which gave rise to x86 architecture.

Interesting fact about India


The art of navigation and navigating was born in river Sindh over 6000 years ago. The very
word 'navigation' is derived from Sanskrit word 'Navgatih'. The word navy is also derived from
Sanskrit word 'Nou'.

Multiplexing and Wireless Transmission - Computer Networks

Multiplexing
Its a technique by which different analog and digital streams of transmission can be
simultaneously processed over a shared link. All medias of communication i.e air, physical
media and light are capable of multiplexing.

A device called multiplexer divides the physical channel when multiple senders try to send over
a single medium and allocated one to each. On the other side, de-multiplexer receives,
identifies and sends to different receivers.

1. Frequency Division Multiplexing


In this frequency is used as a carrier. FDM divides the carrier bandwidth in logical channels
and allocates one user to each channel. All channels are divided in a way that they don't
overlap with each other. How do they achieve that? - Each channel is separated by guard bands
which is a frequency not used by either channel. E.g. Radio channels that you listen to use FDM
(Bajate Rahoo.... Red FM)

2. Time Division Multiplexing


In this, time slots are used for dividing the shared channel among users. Each user can
transmit data within the provided time slot. Digital signals are divided in frames equivalent to
that of time slot. in TDM, both multiplexer and de-multiplexer are synchronized and switch to

www.BankExamsToday.Com Page 39
IT Officer Professional Knowledge Guide

next time slot simultaneously. Imagine crudely that Red Fm can play from 9:00 to 10:00 only
and 10:00 to 11:00 is fixed for Radio Mirchi.

3. Wavelength Division Multiplexing


In this, light is used as signals. As light has different wavelengths multiple optical carrier signals
are multiplexed into an optical fibre by using different wavelengths. This is an analog
multiplexing technique.

4. Code Division Multiplexing


FDM divides the frequency in smaller channels but CDM allow its users full bandwidth and
transmit signals all the time using a unique code called chip. Signals travel with these codes
independently, inside the whole bandwidth. Receiver knows in advance which chip code signal
it has to receive. Again imagine crudely that Red FM uses a code word 'bajatey raho' with which
it sends signals and Red FM uses 'Its hot'!!

Wireless Transmission
Wireless communication doesn't involve any physical link between two or more devices. Signals
are spread in the air, received and interpreted by antennas. An antenna connected to circuit of a

www.BankExamsToday.Com Page 40
IT Officer Professional Knowledge Guide

computer converts digital data into wireless signals and on receiving end, another antenna will
reconvert it back to digital data.

An electromagnetic spectrum is the range of all possible frequencies of electromagnetic


radiations. Some part of this spectrum can be used for wireless communication. An noteworthy
point regarding EM waves is that their wavelength and frequencies are inversely
proportional to each other. Look at the figure below for classification of EM waves followed by
which we will discuss them in brief.

1. Radio Transmission
Important points regarding Radio waves are as follows:

 Can penetrate through walls and structures due to high wavelength and low frequency.
 Sub divided into 6 bands, out of which VLF (very low freq), LF and MF can travel on
ground along the curvature of earth while HF and VHF bands use Ionosphere for use i.e
they are refracted back to earth.
 wavelength range: 1 mm - 1,00,000 km, frequency range: 3 Hz to 300 GHz

2. Microwave Transmission
 Travel in straight line and receiver must be strictly in line of sight.
 Can't penetrate wall like obstacles due to high frequency
 Depends upon weather conditions
 wavelength range: 1 mm - 1 m, frequency range: 300 MHz - 300 GHz

3. Infrared Transmission
 Lie between visible light spectrum and microwaves.
 Used for very short range communication such as TV and Remote.
 Travel in straight line and can't pass wall like obstacles
 wavelength range: 700nm - 1 mm, frequency range: 300 GHz - 430 THz

www.BankExamsToday.Com Page 41
IT Officer Professional Knowledge Guide

4. Light Transmission
 travels strictly in straight line e.g. LASER
 Can't penetrate obstacles like walls or rain. Also distorted by wind or temperature.
 LASER beam is generally 1 mm wide, difficult to tap hence comparatively safe for data
transmission.

Iptables - Network Security

What is Iptable?
Iptable is the building block of a framework inside the Linux Kernel. It is represented by a
generic table structure for definition of rulesets. Each rule with an Iptable consists of a number
of classifiers (iptable matches) and one connection action (iptable target). The security functions
that can be achieved with Iptables are as follows:
 Build internet firewalls based on stateless and stateful packet filtering- In stateful filtering
ports are opened and closed as clients use the internet in such a way that it mostly
presents a blank wall to attackers.
 NAT and masquerading for sharing internet access
 NAT to implement transparent proxies - transparent proxies are intermediary systems that
sit between user and content providers. Upon request by a user, they perform functions
like caching, redirection and authentication.
 Packet manipulation like altering the bits of IP header.
 Provides for improved logging options by using user defined prefixes

Iptable Tables

1. Filter table

Its the default table i.e if you haven't defined your own one, you will be using the default. It has
following built in chains:
 INPUT chain - for packets coming to local server.
 OUTPUT chain - for packets going out of the server.
 FORWARD chain - packets for another interface i.e packets routed through the server.

2. NAT table

It has following built in chains:


 PREROUTING chain - packet translation happens immediately after packet comes to the
system and before it is routed further. This helps to translate the destination IP address of
packets to something that matches on local server.
 POSTROUTING chain - packet translation happens when packets are leaving the system.
It translates the source IP address to something which matches on server.

www.BankExamsToday.Com Page 42
IT Officer Professional Knowledge Guide

 OUTPUT chain - NAT for locally generated packets on the firewall.

3. Mangle Table

It is for specialized packet alteration. This alters QOS bits in TCP header. Quality of service
(QOS) is a group of components that can differentiate traffic flows so that high priority traffic
receives preferential treatment. Mangle table has following built in chains:
 PREROUTING chain
 OUTPUT chain
 FORWARD chain
 INPUT chain
 POSTROUTING chain

4. Raw table

It is used for configuration exemptions. It has following built in chains:


 PREROUTING chain
 OUTPUT chain
The following flowchart will help you better understand the flow using Iptables:

Iptable Rules
Rules contain a criteria and a target. If criteria is matched, it executes values mentioned in the
target and if criteria is not matched, it moves to the next rule.

Target Values
 ACCEPT - firewall will accept the packet
 DROP - drop the packet
 QUEUE - pass the packet to user space

www.BankExamsToday.Com Page 43
IT Officer Professional Knowledge Guide

 RETURN - stop executing next set of rules in current chain and control is returned to
calling chain.
Let's see some commands we use for Iptables:

1. To see all firewall rules in system:

# iptables -t filter --list (or)


# iptables --list (will display default filter table)

2. To view NAT table:

# iptables -t nat --list

3. To view Raw table:

# iptables -t raw --list

4. To view the Mangle Table:

# iptables -t mangle --list

Cryptography - Network Security

Cryptography
Its a technique to encrypt the plain text data into cipher text using keys which makes it difficult to
understand and interpret. Decryption is the reverse of encryption. There are several
cryptographic algorithms available as described below:
 Secret Key
 Public Key
 Message Digest

1. Secret Key Encryption


In this process, both sender and receiver have one secret key. This secret key is used to
encrypt the data at sender's end. After the data is encrypted, it is sent on public domain to the
receiver. Now using the same secret key receiver decrypts the data. Algorithms encrypt/decrypt
the message block by block, a block referring to group of bits. It is also called symmetric key
system. The algorithms using this system are faster and the only problem is that key
management is not easy.

www.BankExamsToday.Com Page 44
IT Officer Professional Knowledge Guide

E.g.- Data Encryption Standard (DES), Advanced Encryption Standard (AES), International
data encryption algorithm (IDEA).

DES: block size - 64 bits, key size - 56 bits


IDEA: block size - 64 bits, key size - 128 bits
AES: block size - 128,192,256 bits, key size - 128,192,256 bits

2. Public Key Encryption


In this process, every user has its own secret key which is never made public. Along with that,
every user has its own public key which is always in public domain and is used by sender to
encrypt the data. Upon receiving, receiver decrypts that data by using its own secret key. In
other words, every communication node will have a pair of keys.

E.g.- RSA algorithm: Based on the principles of number theory, it involves 4 steps - key
generation, key distribution, encryption, decryption. This algorithm was invented in 1978 by
Rivest, Shamir and Adleman. DES is about 100 times faster than RSA.

3. Message Digest
In this method, actual data is not sent, instead a hash value (128 bits) is calculated and sent.
Receiver computes its own hash value and compare with the one it receives. If both hash

www.BankExamsToday.Com Page 45
IT Officer Professional Knowledge Guide

values match, message is accepted otherwise rejected. This method was designed by Ronald
Rivest in 1991.

E.g. - MD5 hashing - mostly used in authentication where user password is cross checked with
the one saved on server.

Web Security - Secure Socket Layer (SSL)


SSL is a cryptographic protocol to secure the network across a connection oriented layer. It was
first developed by NetScape in 1994 and became an internet standard in 1996. It uses
a dedicated TCP/IP socket (e.g - 443 for https). Along with that it also provides built in data
compression. Look at the SSL architecture below.

SSL handshake verifies the server and allows client and server to agree on anencryption
set before any data is send out.

Compression and decompression are functions of this record layer. Encryption of data occurs
after compression.
Alert protocol explains the severity of the message and a description (e.g. 'fatal' - then
terminate immediately).
Function of cipher spec protocol is to notify the other party to use a new cipher suite.
Some other sections of this topic will be covered in next article.

www.BankExamsToday.Com Page 46
IT Officer Professional Knowledge Guide

Protocols - Computer Networks

Telnet Protocol
It starts a remote session on another machine. Login and password are usually required to
gain entry to the remote system. Telnet is used mostly for accessing shared devices like Printer
etc on a remote host or for using software that are only available on a single secure system. By
default, connection is established over port 23.

Command for telnet is - " telnet <ip address> "

FTP
File Transfer Protocol allows a person to transfer files between two computers. At the back
end, two connections are established. One control connection overport 21 which remains
throughout and other for file transfer, over port 22. Every time a new connection will be
established for transfer. Typical ftp commands are as follows:
 ftp <ip address> - est. connection with ftp server
 put, mput - send one/more files
 get, mget - receive one/more files
 hash - indicates progress of file transfer
 prompt - prompts user before actual transfer of each file
 bin, asc - selects binary/ascii mode of transfer
 exit - terminates connection with ftp server

SMTP
Simple Mail Transfer Protocol is used when email is delivered from a mail agent like outlook
or gmail application to mail server . It send messages in simple text only. It uses port 25.

POP3
Post office Protocol allows a mail agent to download email from mail server. Two modes are
used in this - 1) Delete mode - read emails and delete them. 2) Keep mode - emails remain in
the mailbox. It normally uses port 110.

IMAP
Internet Message Access Protocol is similar in functions to that of POP3 but with some extra
features. A user can check email header before downloading, a user can search contents of
email for a specific string prior to downloading, a user can create, delete, or rename mailboxes
on mail server, a hierarchy of mailboxes can also be created. It requires more disk space and
more CPU resources than POP3 as all emails are stored on server. It normally uses port 143.

www.BankExamsToday.Com Page 47
IT Officer Professional Knowledge Guide

HTTP
Hyper Text Transfer Protocol is a protocol using which web browsers interact with the web
servers. Client opens socket connection to HTTP server on port 80and sends HTTP requests to
server. Server sends back response and closes the connection afterwards. Common status
codes for HTTP are: 401 - unauthorized, 403 - forbidden, 404 - Not Found, 500- Internal Server
Error.

UDP
User Datagram Protocol is used for sending packets that doesn't guarantee delivery. It also
doesn't guarantee against lost packets, duplicate packets or our of order packets. It is used for
transfer of bulk data where sequencing of packets doesn't matter much. It has a formal packet
structure though with details like source, destination and size of the packet.

LDAP
Lightweight Directory Access Protocol is an internet protocol that email and other programs
use to look up information from a server. It is mostly used by medium to large size organizations
for example if you want to look up contact info or email ids of persons in your organizations,
LDAP server comes into picture which fetches you all that information. It uses port 389 by
default.

Network Programming Notes

What is Inter Process Communication (IPC)?


IPC is a mechanism that allows exchange of data between processes, by using a set of
programming interfaces. The IPC mechanism can be classified into Pipes (FIFO) and Shared

www.BankExamsToday.Com Page 48
IT Officer Professional Knowledge Guide

memory (Semaphores). In pipes, data flow is unidirectional. A pipe is generally created by


invoking a pipe system call which generates a pair of file descriptors. We'll learn about shared
memory concepts and semaphores in Operating Systems.

What is a file descriptor?


In simple words, when you open a file, OS creates an entry to represent that file and stores
information about that file (somewhere in kernel). These entries are integers and are called file
descriptors. So if your process opens 10 files, your process table will 10 entries for file
descriptors. Similarly, when you open a network socket, it is represented by an integer which is
called socket descriptor.

What is a socket?
The socket is a BSD method for accomplishing IPC. It allows one process to speak to another
and works very similar to files i.e read/write on a socket is similar to that of files. A socket is
created using the socket( ) system call.

Types of Sockets
Two most common types are:
 SOCK_STREAM: Stream sockets, which provide reliable two way connection oriented
communication streams. It uses TCP.
 SOCK_DGRAM: Datagram sockets, which provide connectionless, unreliable service,
used for packet by packet transfer of information. It uses User Datagram Protocol (UDP)

System Calls using Sockets


1. socket( ) - returns socket descriptor, -1 on error.
Syntax:
#include <sys/types.h>
#include <sys/socket.h>
int socket (int domain, int type, int protocol);
domain should be set to AF_INET (uses ip address)
type - SOCK_STREAM or SOCK_DGRAM
protocol- set to zero typically.

2. bind( ) - associates the socket with an address, -1 on error.


Syntax:
#include <sys/types.h>
#include <sys/socket.h>

www.BankExamsToday.Com Page 49
IT Officer Professional Knowledge Guide

int socket (int sockfd, struct sockaddr *my_addr, int addrlen);


sockfd- socket file descriptor returned by socket( ).
my_addr- pointer to a structure that contains information about local IP address and port
number.
addrlen- set to sizeof (struct sockaddr)

3. connect( ) - connect to a remote socket, -1 on error


Syntax:
#include <sys/types.h>
#include <sys/socket.h>
int socket (int sockfd, struct sockaddr *serv_addr, int addrlen);
serv_addr- pointer to a structure that contains the destination IP address and port number

4. listen( ) - wait for incoming connections, -1 on error


Syntax:
int listen (int sockfd, int backlog);
backlog- set max no of requests that will be queued before requests are denied.

5. accept( )- returns a new socket file descriptor for every single connection, -1 on error
Syntax:
#include <sys/socket.h>
int accept (int sockfd, void *addr, int *addrlen);
addr- pointer to a local structure sockaddr_in, here information about incoming connection will
be stored
addrlen- should be set to sizeof(struct sockaddr_in) before accept( ) is called.
Other systems calls along with rest of the topic will be covered in next article.

System Calls using Sockets


6. send( ) & recv( ) - used for communicating over stream sockets or connected datagram
sockets, -1 on error.
Syntax:
int send (int sockfd, char *buffer, int buf_len, int flags);
int recv (int sockfd, char *buffer, int buf_len, int flags)
buffer- buffer to read the information into
buf_len - length of data in bytes
flags - typically set to 0
send( ) returns the number of bytes actually sent out and recv ()returns the number of bytes
actually read into the buffer.

7. sendto( ) & recvfrom( )- transmit and receive data packets over unconnected datagram
sockets, -1 on error.
Syntax:

www.BankExamsToday.Com Page 50
IT Officer Professional Knowledge Guide

int sendto (int sockfd, char *buffer, int buf_len, int flags, const struct sockaddr *to, int tolen);
int recvfrom (int sockfd, char *buffer, int buf_len, int flags, struct sockaddr *from, int *fromlen);
to- address of the target
tolen- size of the structure pointed to by to
from- socket address structure from which data is received
fromlen- size of from in bytes

8. close( ) & shutdown( ) - used to close the connection on socket descriptor


Syntax:
close (sockfd); //prevents anymore reads/writes to the socket
int shutdown (int sockfd, int how);
how =0 - prohibits further receives
how=1 - prohibits further sends
how = 2 - prohibits further sends/receives

9. getpeername( ) - this will tell you who is at the other end of a connection stream socket
Syntax:
#include <sys/socket.h>
int getpeername (int sockfd, struct sockaddr *addr, int *addrlen)
addr - pointer to a structure that holds information about other side of connection
addrlen - pointer to an int that is initialized to sizeof(struct sockaddr)

10. gethostname( ) - returns name of the computer on which your program is running
Syntax:
#include <unistd.h> //header for standard symbolic constants and types
int gethostname (char *hostname, size_t size);
hostname- pointer to an array of chars which contains the hostname
size - length of hostname array in bytes

11. gethostbyname( ) - returns the IP address of a host given its name, invokes the DNS
Syntax:
#include <netdb.h> //header for network database operations
struct hostent *gethostbyname (const char *name); //returns a pointer to struct hostend

www.BankExamsToday.Com Page 51
IT Officer Professional Knowledge Guide

Client Server communication for connection oriented protocols

Client Server communication for connectionless protocols

MCQs

1. SOCK_STREAM sockets are used by which processes?


a) UDP
b) TCP
c) SCTP
d) none of the above

2. SOCK_DGRAM sockets are used by which processes?

www.BankExamsToday.Com Page 52
IT Officer Professional Knowledge Guide

a) UDP
b) TCP
c) SCTP
d) none of the above

Communication Protocols - DHCP and DNS

Domain Name System (DNS)


DNS is usually used to translate a host name into an IP address. E.g. - when you hit
'google.com' in your browser, it actually hits IP 216.58.196.14 on internet and fetches us the
home page (may vary depending upon geographies as google has many servers). Domain
names comprise a hierarchy so that names are unique and easy to remember. Some points
about DNS are as below:
 Stores other information other than simple host-IP mappings.
 Root servers are maintained throughout the world and are responsible for all of top level
domains. When you register a domain, an entry for that domain is added to appropriate
root server.
 An administration zone is a subtree of DNS tree that is independently managed. E.g-
("co.in") and ("ac.in") belong to one independent zone for administration.
 A zone must provide for multiple name servers which record the members in the domain.
 The kind of records that can be requested are- Address Translation, Caching
Information, Mail Server Information.
 DNS uses distributed database as there is one primary server for a domain and typically
a number of secondary servers containing replicated databases.
 The organization that owns the domain name is responsible for running a DNS server that
provides for the mapping.
 A DNS client is called a resolver.
 Most Unix workstations have the file /etc/resolv.conf that contains local domain and
addresses of DNS servers for that domain.
 nslookup, usually available on unix workstations, is an interactive resolver that allows the
user to communicate directly with a DNS server. (hit nslookup followed by yahoo.com for a
feel of it)
 If a server is asked to provide the mapping for a host outside its domain, it finds the
nameserver for target domain and asks it to provide the translation.
 Common DNS library functions - 'gethostbyname' & 'gethostbyaddr'
 Uses port number 53
A DNS tree looks like:

www.BankExamsToday.Com Page 53
IT Officer Professional Knowledge Guide

Dynamic Host Configuration Protocol (DHCP)


DHCP is used to dynamically assign configuration parameters (IP address, subnet mask,
default gateway, DNS information) to network devices. Some points about DHCP are as below:
 A host without a valid IP address communicated with DHCP server, DHCP server then
dynamically allocates address. It may reuse the addresses.
 Eliminates the need for manual host configuration.
 It can co-exist with other pre assigned IP addresses and hots which don't participate in
DHCP.
 DHCP client uses port number 68.
 Messages exchanged between Client and Server are as follows:
 Client sends a DISCOVER message to all computers.
 DHCP server upon receiving that message sends an OFFER
 Client then sends REQUEST to obtain an IP address.
 Server responds with ACK (request accepted) and NACK(something wrong
with REQUEST)
 DECLINE message may be sent by client in case it finds that IP address
assigned to it is already in use.
 INFORM message may be send by client in case IP is statically configured on
client and it needs other configuration settings only.
 Finally, Client may send RELEASE when its done with using that IP, not
necessary.

www.BankExamsToday.Com Page 54
IT Officer Professional Knowledge Guide

Firewalls - Computer Networks

What is a Firewall?
A firewall is a device designed to control the flow of traffic into and out-of a network. In
general, firewalls are installed to prevent attacks. It disrupts free communication between a
trusted and un-
trusted network in order to mange the information flow and restrict unwarranted dangerous
access.

Hardware firewall is a physical device between internet and your computer while Software
firewall is installed as a program on computer.

Types of Firewalls
Packet Filtering Firewall

It applies a set of rules to each incoming packet and then forwards/discards(two default
policies) the packet. It filters packets going in both directions. The packet filter is typically set
up as a list of rules based on matches to fields in IP or TCP header. Some of the attacks that
can be made on packet filtering routers are: IP address spoofing, Source Routing attacks,

www.BankExamsToday.Com Page 55
IT Officer Professional Knowledge Guide

Tiny Fragment attacks.

Advantages: Simplicity, transparency to users and high speed.


Disadvantages: Difficult to set up, lack of authentication.

Application Level Gateway Firewall

In this, when a client establishes connection with the destination service, it connects to an
application gateway. It is also called a proxy server. The proxy then establishes the connection
with destination behind the firewall and acts on behalf of client, making all packet forwarding
decisions. It acts as a relay of application level traffic. Also, it needs separate proxies for
each service- SMTP, DNS and other custom services.

Advantages: Higher security than packet filters, Easy to log and audit all incoming traffic.
Disadvantages: Requires great memory and processor resources.

Circuit Level Gateway Firewall


This firewall works at session layer of OSI model. Traffic is allowed only if a session request is
legitimate. It sets up two TCP connections. The gateway typically relays TCP segments from
one connection to other without examining the contents and security function determines
whether to allow it further or not. A proxy server as explained above is a security barrier
between internal and external computers while a circuit level gateway is a virtual circuit

www.BankExamsToday.Com Page 56
IT Officer Professional Knowledge Guide

between proxy server and internal hosts.

Advantages: Hides private network data, doesn't need a separate proxy server for each
application, simple to implement.
Disadvantages: Doesn't filter individual packets, attacker may take advantage after
establishing a connection.

What is a Bastion Host?


It is a system identified by firewall administrator as a crucial point in network's security. It
executes a secure version of OS and is trusted. It requires additional authentication before
access is allowed. It is designed specifically to withstand attacks as it is on public side of the
network. Firewalls and Routers can be considered as Bastion Hosts.

Communication Protocols - DHCP and DNS

Domain Name System (DNS)


DNS is usually used to translate a host name into an IP address. E.g. - when you hit
'google.com' in your browser, it actually hits IP 216.58.196.14 on internet and fetches us the
home page (may vary depending upon geographies as google has many servers). Domain
names comprise a hierarchy so that names are unique and easy to remember. Some points
about DNS are as below:
 Stores other information other than simple host-IP mappings.
 Root servers are maintained throughout the world and are responsible for all of top level
domains. When you register a domain, an entry for that domain is added to appropriate
root server.
 An administration zone is a subtree of DNS tree that is independently managed. E.g-
("co.in") and ("ac.in") belong to one independent zone for administration.
 A zone must provide for multiple name servers which record the members in the domain.
 The kind of records that can be requested are- Address Translation, Caching
Information, Mail Server Information.

www.BankExamsToday.Com Page 57
IT Officer Professional Knowledge Guide

 DNS uses distributed database as there is one primary server for a domain and typically
a number of secondary servers containing replicated databases.
 The organization that owns the domain name is responsible for running a DNS server that
provides for the mapping.
 A DNS client is called a resolver.
 Most Unix workstations have the file /etc/resolv.conf that contains local domain and
addresses of DNS servers for that domain.
 nslookup, usually available on unix workstations, is an interactive resolver that allows the
user to communicate directly with a DNS server. (hit nslookup followed by yahoo.com for a
feel of it)
 If a server is asked to provide the mapping for a host outside its domain, it finds the
nameserver for target domain and asks it to provide the translation.
 Common DNS library functions - 'gethostbyname' & 'gethostbyaddr'
 Uses port number 53
A DNS tree looks like:

Dynamic Host Configuration Protocol (DHCP)


DHCP is used to dynamically assign configuration parameters (IP address, subnet mask,
default gateway, DNS information) to network devices. Some points about DHCP are as below:
 A host without a valid IP address communicated with DHCP server, DHCP server then
dynamically allocates address. It may reuse the addresses.
 Eliminates the need for manual host configuration.
 It can co-exist with other pre assigned IP addresses and hots which don't participate in
DHCP.
 DHCP client uses port number 68.
 Messages exchanged between Client and Server are as follows:
 Client sends a DISCOVER message to all computers.
 DHCP server upon receiving that message sends an OFFER
 Client then sends REQUEST to obtain an IP address.
 Server responds with ACK (request accepted) and NACK(something wrong
with REQUEST)

www.BankExamsToday.Com Page 58
IT Officer Professional Knowledge Guide

 DECLINE message may be sent by client in case it finds that IP address


assigned to it is already in use.
 INFORM message may be send by client in case IP is statically configured on
client and it needs other configuration settings only.
 Finally, Client may send RELEASE when its done with using that IP, not
necessary.

Network Address Translation - Computer Networks

Network Address Translation (NAT) & its Forms


Allows a single device to act as an agent between Internet and private network. Only 1
unique IP address is required to represent an entire group of computers.

Static NAT
It has one to one mapping between private and public addresses i.e one public IP for every
private IPs in private network. The only benefit is that it allows a server inside private network to
be reachable over internet through one to one translation.

Dynamic NAT
It has many to many mapping between private and public addresses. It maps an unregistered
IP address to a registered one from a pool of registered IP addresses in NAT router. Addresses
are assigned dynamically.

Port Address Translation (NAT Overloading)


It maps multiple private IPs to a single public IP i.e many to one mapping. Each computer on
private network gets translated to the same public IP but with a different port number
assignment.

www.BankExamsToday.Com Page 59
IT Officer Professional Knowledge Guide

Suppose an internal host A tries to connect to a web server outside. NAT enabled router will
save private IP and source port from A's packet to an Address Translation Table (ATT). It then
replaces private IP with the router's IP address, generates a new port for new connection and
forwards the packet over internet. Now when the return packet from web server reaches the
router, it uses destination port to search ATT, obtains the private address and port numbers
mapped to it and sends it to original sender.

The Address Translation Table looks like:

Main Uses of NAT

Pooling of IP addresses
Suppose a corporate network has many hosts but only a small number of public IP addresses. It
uses private address space for hosts and when a host send an IP datagram to a host in public
internet, NAT device picks up a public IP from the pool and binds it to private address of the
host.

Migration between service providers


In CIDR, IP addresses in a corporate network are obtained from service provider. Changing the
service provides requires changing all IP addresses in the network. Now, this NAT device has
static address translation entries which bind the private addresses to public addresses.

www.BankExamsToday.Com Page 60
IT Officer Professional Knowledge Guide

Migration to a new service provider merely requires an update of NAT device and this migration
won't be noticeable to hosts on the network.

IP Masquerading (Network address and port translation)


As we have assigned private addresses to hosts of the network above, NAT device will modify
the port numbers for outgoing traffic. The literal meaning of masquerading is- pretending to
be someone/something which you're not.

Load Balancing of Servers


Suppose we have to balance the load on a set of identical servers, which are accessible from a
single IP address. With concept of NAT, we will assign them pvt addresses and NAT device will
act as a proxy for requests to server from public network. It will change the destination IP of
incoming packets to one of pvt address of a server. Usually the servers are assigned addresses
in a round robin fashion.

www.BankExamsToday.Com Page 61
IT Officer Professional Knowledge Guide

One more important thing to learn is that NAT is not a proxy server. NAT is transparent to both
source and destination hosts but proxy server is not transparent. Also NAT is a layer 3 (network)
protocol while proxy server works at layer 4 (transport) or higher.

Chapter: Database Management System

Introduction to Database Management System

What is Database?
A database is a collection of information that is organized so that it can easily be accessed,
managed and updated.

What is Database Management System?


DBMS is a software package designed to define, manipulate, retrieve and manage data in a
database. It defines rules for validating and manipulating that data. Fourth generation query
languages like SQL are used along with DBMS package to interact with database.
Some of the real time applications using DBMS are Banking (transactions), Airlines
(reservations and schedules), Universities (registration and grades), Manufacturing (production,
inventory, orders, supply chain) etc.

Advantages of a DBMS
1. Controls Data Redundancy: All of the data is integrated into a single centralized file and
no duplicates are created.
2. Data Sharing: Database administrator upon granting access allows for sharing of data
across different platforms and different users.
3. Data consistency: As a data item appears only once, update has to be done once only
and updated value is immediately available for use.

www.BankExamsToday.Com Page 62
IT Officer Professional Knowledge Guide

4. Integration of Data: In DBMS, data is stored in tabular form and various relationships can
be created among tables. This makes it easy to retrieve and update data.
5. Data Security: The access to critical information can be restricted and access privileges
are required for updating/manipulating important information. E.g.-access to financial data
is restricted providing for security of data.
6. Backup and Recovery: It has subsystems which deal with back up and recovery in case
of hardware/software failure or in case of a natural calamity which endangers the data in
any way.
7. Concurrent Access: It provides for concurrent access to multiple users at one time
making it more efficient for business applications.

Components of DBMS
A database system consists of 4 components usually:
 Data
 Hardware
 Software
 Users
1. Data: It is the most important component of a database which acts like a bridge between
hardware and software. Different types of data are- User data (actual/workable data stored in
tables), Metadata ( data about data i.e no of tables, no of fields), application metadata (structure
and format of queries)

2. Hardware: Storage devices on which data is stored with i/o operations (hard disks, optical
disks, magnetic tapes etc)

3. Software: It acts a bridge between user and database. It interacts with both user and
database and acts a medium for data exchange. For performing various operations on the data,
we use query languages like SQL etc.

4. Users: They are the ones who need information from a database to carry out their primary
business responsibilities. Various types of users are: Database administrators, Database
designers, End users, Application Programmers.

Levels of Abstraction

1. Physical Level
It describes how a record (e.g. customer) is stored in the database.

2. Logical Level
It describes the data stored in database and the relationships among themselves. Lets look at
the description of customer data below:

www.BankExamsToday.Com Page 63
IT Officer Professional Knowledge Guide

cust_id: int;
cust_name: string;
cust city: string;

3. View Level
At this level, application programs hide details of data types. Views can also hide information
such as employee salary for security purposes.

The Entity-Relationship Model (ER Model) - DBMS

ER Model
ER model is a data model for describing the data or information, visually, as a collection of
entities and relationships. It was developed by Peter Chen in 1976.The symbols and notations
used in ER model are as follows:

Components of ER Diagram
E-R Diagram has 3 main components:

1. Entity

Entity is a thing in the real world with an independent existence, and entity set is a collection of
all entities of particular entity type in the database. E.g. Employees of a company can be

www.BankExamsToday.Com Page 64
IT Officer Professional Knowledge Guide

defined as entities and employees have same attributes can be put under an entity set. All
entities have some attributes that give them identity.

2. Attribute

An attribute describes a property or characteristic of an entity. E.g. Name, age , address can
be attributes of an employee. Types of attributes are discussed below:
 Simple attribute- Its an atomic value which can not be divided further. E.g employee's
phone number.
 Key Attribute - it represents main characteristic of an entity. It is used to represent
primary key.
 Composite Attribute - An attribute can have its own attributes as well. E.g. Address
attribute is usually composed of city, state and zip code attributes.
 Derived attribute - These attributes don't exist in the physical database and their values
are derived from other

3. Relationship

A relationship describes relations between entities. 3 types of relationships exist between


entities:

a) Binary Relationship: is a relationship between 2 separate entities or entity sets. It is further


of 3 types:

 One to One: Let's say one student can enroll only in one course and one course will only
have one student. This type of relationship is rarely seen in real world.

 One to Many - As per this relationship, one student can enroll to many courses but one
course will have one student only. Example might sound weird but this is for explanation
purpose.

www.BankExamsToday.Com Page 65
IT Officer Professional Knowledge Guide

 Many to One - As per this, a student can enroll for one course only but a course can have
many students.

 Many to Many - As per this, many students can enroll for more than one course.

b) Recursive Relationship: is when an entity is related with itself. E.g. each employee has a
manager in a organization which is further managed by a manager. Thus an employee
manages other
employees and is managed by some employee as well.

www.BankExamsToday.Com Page 66
IT Officer Professional Knowledge Guide

c) Ternary Relationship: is when three entities participate in a relationship i.e relationship of


degree three. E.g A university might maintain data about which teacher taught
which subjects under which course.

Keys
Key is an attribute or a collection of attributes that uniquely identifies an entity. Various types of
keys are discussed below:
 Super key - a set of attributes ( one or more ) that collectively identifies an entity
 Composite key- a key requiring more than one attribute
 Candidate key - a minimal super key is called candidate key. An entity set may have more
than one candidate key.
 Primary key - the candidate key chosen to be used for identifying entities and accessing
records. Key by default means primary key.
 Alternate key - a candidate key not used for primary key
 Secondary key - attribute or set of attributes commonly used for accessing records but
not necessarily unique
 Foreign key - is a tern used in relational databases (not ER model) for an attribute that is
primary key of another table and is used to establish a relationship with that table

Relational Model - DBMS

Relational Model
Some important points to note here about attributes in a relation are as follows:

1. Each attribute of a relation has a name.

2. The set of allowed values for each attribute is called the domain of the attribute

3. Attribute values are required to be atomic i.e indivisible.

4. Domain is said to be atomic if all its members are atomic.

5. The special value NULL is a member of every domain.

6. A relation is a set of n tuples (a1, a2, a3...) where each attribute belongs to corresponding
domain.

Relational Algebra
The basic operators used in relational algebra are as follows:

www.BankExamsToday.Com Page 67
IT Officer Professional Knowledge Guide

1. SELECT
It is used to obtain a subset of the tuples of a relation that satisfy a select condition. The
SELECT operator is denoted by symbol σ (sigma). The syntax for SELECT statement would be
as follows:

σ<Selection condition>(R) ( R would represent the relation or table from which selection is made )

Example:

SELECT dob '01/jan/1978' (employee)

2. PROJECT
It is used to select a subset of attributes of a relation by specifying the namesof required
attributes. The symbol used for PROJECT operator is ∏ (pie). The syntax is as follows:

∏<attribute list>(R)

Example:

PROJECT surname, empno (employee)

3. UNION
UNION of two relations r and s designated as r s is a relation that includes all the tuples that
are either in r or in s or in both r and s. Duplicate tuples are eliminated.

4. INTERSECTION
INTERSECTION of two relations r and s denoted by r both r
and s

www.BankExamsToday.Com Page 68
IT Officer Professional Knowledge Guide

5. DIFFERENCE
DIFFERENCE of two relation r and s denoted by r - s, includes all tuples that are in r but not in
s

6. CARTESIAN PRODUCT
It is also referred to as cross product or cross join denoted by r x s, creates a relation that has
all attributes of r and s i.e allowing all combinations of tuples from r and s

www.BankExamsToday.Com Page 69
IT Officer Professional Knowledge Guide

7. JOIN
It is used to combine related tuples from two relations. It can be further studies in three forms:

a) Inner Join

It joins two tables according to matching of a certain criteria using a comparison operator.
SQL representation is as follows:

SELECT * from tab1

JOIN tab2

ON tab1.col_name = tab2.col_name

b) Equi Join

It joins two tables based on matching of certain criteria using equal sign (=) as the comparison
operator in WHERE clause.

SELECT col_name

FROM tab1, tab2

WHERE tab1.col_name = tab2.col_name.

c) Outer Join

It joins all rows from both tables which satisfy the join condition and which do not satisfy the join
condition thereby avoiding loss of information. It is of 3 types further:

www.BankExamsToday.Com Page 70
IT Officer Professional Knowledge Guide

 LEFT OUTER JOIN - keep data from left hand table


 RIGHT OUTER JOIN - keep data from right hand table
 FULL OUTER JOIN - keep data from both tables
Lets look at the example figures below to solidify the understanding of outer joins.

www.BankExamsToday.Com Page 71
IT Officer Professional Knowledge Guide

The figures have been taken from the DBMS book by Korth, for a better understanding.

Normalization in DBMS - PK Series

Normalization
Normalization is a refinement process where it helps in removing anomalies in insert, update
and delete operations. It is also called bottom up approach, because this technique requires
full knowledge of every participating attribute and its dependencies on key attributes. If you try
to add new attributes after normalization is done, it may change the normal form of database
design itself. It is mainly used for two purposes:

 Eliminate redundant data


 Ensure data is logically stored.
Normalization rules are divided into following normal forms:

1. First Normal Form (1NF)


A relation is in 1NF if all of its attributes have domains that are atomic or indivisible. It leads to
data redundancy. A table in 1NF should satisfy following five conditions:

 There is no top to bottom ordering of the rows


 There is no left to right ordering to the columns.
 There are no duplicate rows.
 Every row and column intersection contains exactly one value from application domain.
 All columns are regular (no hidden components)
Consider the table below which is not in 1NF:

www.BankExamsToday.Com Page 72
IT Officer Professional Knowledge Guide

Now, for it to be in 1NF, any row must not have a column with more than one values in it. Such
data should be separated into multiple rows. So in 1NF, it will look like:

2. Second Normal Form (2NF)


A relation is in 2NF when it is in 1NF and there is no such non key attribute that depends on part
of the candidate key (no partial dependency), but on the entire candidate key i.e a relation that
has a single attribute as its candidate key is always in 2NF.

Look at the table in 1NF above, there are 2 rows for Adam to show different subjects he has
opted for. This is inefficient use of space. Also the candidate key is {student, subject} but age
depends only on student which doesn't follow 2NF rules. Therefore to make it in 2NF, its better
to split the subjects into a different table and match it up using student's name as foreign key.
Now, the new student table will look like:

Candidate key is student column on which age depends.

And new subject table looks like:

www.BankExamsToday.Com Page 73
IT Officer Professional Knowledge Guide

Candidate key here is {student, subject}. This way the tables above would never suffer from
update anomalies.

3. Third Normal Form (3NF)


A relation is in 3NF if it is in 2NF and every attribute depends directly on primary key and not
through a transitive relation when an attribute A may depend on a non key attribute B and B in
turn depends on primary key C. Non key attributes are mutually independent.Through this,
data duplication is removed and data integrity is achieved. Lets learn it from the example
below:

Consider the table Student_Details below:

student_id is primary key here but street, city, state depends on zip. This dependency between
zip and other fields is called transitive dependency. To make it in 3NF, we need to move street,
city and state into a new table with zip as primary key. Therefore, the new table will look like:

Zip table

4. Boyce and Codd Normal Form (BCNF)


This is a higher version of 3NF. A 3NF table which doesn't have multiple overlapping candidate
keys is said to be in BCNF. Following two conditions must be satisfied for BCNF:

 Relation (R) must be in 3NF


 For each functional dependency (A->B), A should be the super key for R.
Consider the database, Classes (course, teacher, book) where (c,t,b) Classes, means t is
qualified to teach c and b is required textbook for that.

Logically, for any course C, database should list all teachers anyone of whom can be the course
instructor and list of books to be followed for teaching.

www.BankExamsToday.Com Page 74
IT Officer Professional Knowledge Guide

But if Tom is new teacher who teaches database, then we might face an insertion anomaly i.e
we will need to insert two tuples (database, Tom, DB concepts) and (database, Tom, Ullman).
Therefore, its better to break classes into 2 tables:

SQL in DBMS - PK Series

SQL Commands
Basic SQL commands cane be classified in following groups based on their nature:

www.BankExamsToday.Com Page 75
IT Officer Professional Knowledge Guide

1. Data Definition Language (DDL)

 CREATE - create a new table, a view of table or other objects in database


 ALTER - modifies an existing database object, such as table
 DROP - deletes an entire table, a view of table or other objects.

2. Data Manipulation Language (DML)


 INSERT - creates a record
 UPDATE - modifies records
 DELETE - deletes records

3. Data Control Language (DCL)


 GRANT - gives a privilege to user
 REVOKE - take back a privilege from user

4. Data Query Language (DQL)

 SELECT - retrieves certain records from one or more tables

Clauses in SQL

1. WHERE clause
It is used to specify a condition while fetching data from single table or multiple tables. WHERE
clause is used with SELECT, UPDATE & DELETE statements.

Basic Syntax:

SELECT col_1 col_2


FROM table_name
WHERE <condition>

Condition can be specified using comparison or logical operators like >, <, =, NOT, LIKE etc.

2. LIKE clause
It is used to compare a value to similar values using wildcard operators. There are 2 wildcards
used in conjunction with LIKE operator:

 Percent sign (%) - represents zero, one or multiple characters


 Underscore ( _ ) - represents a single number or character
Basic Syntax:

SELECT from table_name

www.BankExamsToday.Com Page 76
IT Officer Professional Knowledge Guide

WHERE column LIKE ' %xxx% '


and
SELECT from table_name
WHERE column LIKE ' _xxx_ '

3. TOP clause
It is used to fetch TOP N numbers or X percents records from a table. All the databases do not
support TOP clause. MySQL uses LIMIT to fetch limited number of records and Oracle uses
ROWNUM to produces similar results.
Basic Syntax:
SELECT TOP number|percent col_name
FROM table_name
WHERE <condition>
e.g. SELECT TOP 3 * FROM employee - this would fetch first 3 rows with all columns from
employee table

4. ORDER BY Clause
It is used to sort the data in ascending or descending order, based on one or more columns.
Usually ascending order is chosen by default.
Basic Syntax:
SELECT * from Employee
ORDER BY salary DESC;

5. GROUP BY Clause
It is used in combination with SELECT statement to arrange identical data into groups. It follows
the WHERE clause and precedes the ORDER BY clause.
Basic Syntax:
SELECT col_1 col_2
FROM table_name
WHERE <condition>
GROUP BY col_1 col_2
ORDER BY col_1

6. HAVING Clause
It enables you to specify conditions that filter which group results appear in final results.
WHERE clause places conditions on selected columns but HAVING clause places conditions on
groups created by GROUP BY clause.
Basic Syntax:
SELECT col1, col2
FROM tab1, tab2
WHERE <conditions>
GROUP BY col1, col2

www.BankExamsToday.Com Page 77
IT Officer Professional Knowledge Guide

HAVING <conditions>
ORDER BY col1, col2

SQL Transactions
Transactions are sequences of work accomplished in logical order whether manually or by a
database automatically.
All the transactions should maintain following properties/achieve following ends after occurring:
 Atomicity
 Consistency
 Isolation
 Durability
Following transaction control statements are used in SQL:

1. COMMIT command
It saves all changes to the database since the last COMMIT or ROLLBACK command.
syntax - COMMIT;

2. ROLLBACK command
It is used to undo transactions that have not already been saved to the database.
syntax - ROLLBACK;

3. SAVEPOINT command
It is a point in transaction control when you can roll the transaction back to a certain point
without rolling back the entire transaction
syntax - SAVEPOINT savepoint_name;

4. RELEASE_SAVEPOINT command
It removes a savepoint that you have created.
syntax - RELEASE SAVEPOINT savepoint_name;

5. SET TRANSACTION command


It can be used to specify characteristics for the transaction that follows.
syntax - SET TRANSACTION [ read write | read only ];

Advanced SQL in DBMS - PK Series

User defined types


1. Create type - creates user defined type
create type Dollars as numeric (12,2) final

2. Create domain - creates user defined domain types


create domain person_name char (20) not null

www.BankExamsToday.Com Page 78
IT Officer Professional Knowledge Guide

Difference between both is that domains can have constraints, such as NOT NULL, on them.
We'll discuss constraints in next section.

Integrity Constraints
Integrity constraints protect against accidental damage to database, by ensuring the authorized
changes to database do not result in loss of data consistency. E.g - Employee must have NOT
NULL phone number, Number of leaves shouldn't be more than 20 etc.

Types of constraints
1. NOT NULL - indicates that a column can not store NULL value
Emp_name char(15) NOT NULL

2. UNIQUE - ensures that each row for a column must have a unique value
emp_id int NOT NULL UNIQUE

3. CHECK - ensures that value in a column meets a specific condition like limit the value range
etc
emp id int NOT NULL,
CHECK (emp_id >999)

4. DEFAULT - It is used to insert a default value into a column. It will be added to all new
records, if no other value is specified.
emp_id int NOT NULL,
city varchar(255) DEFAULT 'Mumbai'

5. Referential Integrity - It ensures that value that appears in one relation for a given set of
attributes also appears for a certain set of attributes in another relation. It is achieved through
primary key and unique key.

ODBC and JDBC

1. Open Database Connectivity (ODBC)


ODBC is a standard for application program to communicate with a database server. Application
program interface (API) opens a connection with database using SQLConnect( ), sends queries
using SQLExecDirect & gets back results using SQLFetch( ). ODBC first provides an SQL
environment and then a database connection handle.
Application such as GUI, Spreadsheets etc can use ODBC. It works with C,C++, VisualBasic
and C#.

www.BankExamsToday.Com Page 79
IT Officer Professional Knowledge Guide

2. Java Database Connectivity (JDBC)


Its a JAVA API for communicating with database systems supporting SQL. JDBC also supports
metadata retrieval such as querying about relations present in database and names, types of
relation attributes. Flow of communication goes as follows:
 Open a connection
 create a statement object
 execute queries using statement object to send queries and fetch results
 exception mechanisms to handle error
It works with Java language.

SQL Functions

Aggregate Functions
SQL aggregate functions return a single value calculated from values in the column. Some
important aggregate functions are as follows:

 AVG( ) - return avg value


 COUNT( ) - return number of rows
 FIRST( ) - first value
 LAST( ) - last value
 MAX( ) - largest value
 MIN( ) - smallest value
 SUM( ) - returns the sum

Scalar Functions
These return a single value based on input value. Important scalar functions are as follows:

 UCASE( ) - convert to upper case


 LCASE ( ) - lower case
 MID( ) - extract characters from a text field
 LEN( ) - return length of text field
 ROUND( ) - round off to specified decimal
 NOW( ) - return current system data and time
 FORMAT( ) - format field to be displayed

Chapter: Operating system

Operating System - Part 1

Operating System (OS)


Operating system is an essential component of the system software in a computer system. Its a
program/set of programs that acts as intermediary between a user and computer hardware. OS

www.BankExamsToday.Com Page 80
IT Officer Professional Knowledge Guide

can be found on almost all modern computing devices- from mobile phones to video game
consoles to web servers to supercomputers. E.g. MS DOS, UNIX, Windows 7, Windows 10,
Ubuntu etc

Functions of an Operating System

1. Boot up the computer


The process of starting or restarting a computer is known as booting. A cold boot is when you
turn on a computer that has been turned off completely. A warm boot is the process when you
restart the computer using OS i.e restart by Ctrl+Alt+Del or boot from sleep mode.

2. Basic computer tasks


It performs basic tasks such as managing the peripheral devices. These days most OSs use
support plug and play feature i.e a printer for example will be detected and configured
automatically without any manual intervention.

3. Provides a user interface


Two main types of UIs are: command line and GUI. With command line, user types commands
on terminal to performs various tasks. With GUI, user interacts using a mouse, icons and
menus.

4. Handling of System Resources


OS handles system resources such as computer's memory and sharing of CPU time by various
applications or peripheral devices. It ensures each application gets necessary resources it
needs to perform effectively.

5. File management
OS handles the organization and tracking of files and directories. It keeps track of user's activity
as far as file creation, updation, deletion or movement is concerned. Two main types of file
systems are:
 File Allocation Table (FAT/FAT32) - It uses a file allocation table maintained by OS on a
hard disk that provides a map of clusters (logical units of storage) that a file has been
stored in.
 New Technology file system (NTFS) - File system introduced by Microsoft. It also allows
permissions (read, write, execute) to be set for individual files and directories.

Types of Operating Systems

1. Single user, single task OS


It is designed in a way that one user can effectively do one thing at a time. E.g. - Palm OS for
palm handheld devices.

www.BankExamsToday.Com Page 81
IT Officer Professional Knowledge Guide

2. Single user, multi tasking OS


It allows a single user run several programs at the same time. Personal computers/ Laptops are
mostly used with this kind of OS. E.g - MS windows or Apple's MacOs platforms. (You see you
can write a blog and listen to music side by side when the downloading is on at back end- multi
tasking!!!)

3. Multi user OS
It allows many different users to take advantage of computer's resources simultaneously. OS
must allocate resources in a way that a problem with one user doesn't affect the entire
community of users. Main purpose is to maximize the resources. E.g. Mainframe systems.

4. Real time OS
It controls the environment as it has a data processing system. Time taken by system to
respond to an input and display the result is called a response time. It uses an advanced
algorithm for scheduling.

5. Time sharing OS
It enables many people located at various terminals, to use the system, at a particular time. In
other words, its a logical extension of multiprogramming. The main purpose is to minimize
response time.

6. Distributed OS
Distributed systems use a number of central processors to serve multiple real time applications
and different users. Data processing jobs are distributed among processors.

7. Network OS
This OS runs on a server. It is responsible for manaing data, users, groups, security,
applications and other networking functions. It allows shared file and printer access among
multiple computers in a network. E.g. Microsoft Windows Server 2003/2008, oivell NetWare.

8. Embedded OS
Its a specialized OS for use in computers which are built into larger systems. It is part of
different kind of machine. E.g. - Computers in cars, traffic lights, GPS navigation system,
elevators, ATMs etc. As compared to a general purpose OS, embedded OS has limited
functions but that single function/application is crucial to its operation.

9. Mobile OS
Its an OS specially designed to run on mobile devices such as smartphones, PDAs. E.g.-
Android, iOS etc.

www.BankExamsToday.Com Page 82
IT Officer Professional Knowledge Guide

Operating Systems - Part 2

Graphical User Interface


It's a program interface that takes advantage of computer's graphics capabilities to make
programs easier to use.
Basic components are of GUI are as follows:

1. Pointer - A symbol that appears on the display screen and which you move to select objects.
Text processing applications use an I-beam pointer that is shaped like capital I.

2. Pointing Device - A device such as mouse or trackball that enables you to select objects.

3. Icons - small pictures that represent commands, files or windows. By clicking on icons, you
execute commands

4. Desktop - The area on display screen where icons are grouped.

5. Windows - You can divide the screen into different areas and can display different
files/programs in each window.

6. Menus - Most GUIs let you execute commands by selecting a choice from menus.

Microsoft Disk Operating System (MS DOS)


Various features of MS DOS are as follows:
 Its a non graphical commands line OS.
 It was originally written by Tim Paterson and introduced by MS in 1981.
 DOS has character user interface i.e communication between a computer and the user
can be done by using characters.
 Prompt is the place where commands are issued. It looks like C:\> or C:\Windows\>

Processes in OS
A program in execution is called a process. Process execution must progress in sequential
fashion. A process is an active entity and program is a passive entity. A program becomes a
process when executable file is loaded into memory. A process is represented by 'pid' in Linux.
Multiple parts of a process are as follows:
 Program Code - text
 Program Counter - contains address of next instruction
 Stack -contains temporary data like return address and local variables
 Heap - contains memory dynamically allocated during run time
 Data Section - contains global variables

www.BankExamsToday.Com Page 83
IT Officer Professional Knowledge Guide

Process State
As a process executes, it changes states and at any given time, can be in any of the following
states:
 New - Process is being created.
 Ready - Process is waiting to be assigned to the processor.
 Running - When instructions related to that process are executed by CPU
 Waiting - Process is waiting for a resource to become available or for some event to
occur.
 Terminated - Process has finished execution and released resources that it was using.
Diagram below will make it more clear.

Process Control Block


Process control block (PCB) has information associated with each process. It is also called task
control block.
 Process State - waiting, ready, running etc.
 Process ID and Parent Process ID.
 CPU Registers - contents of all process-centric registers
 Program Counter. PC holds the address of next instruction to be executed.
 CPU Scheduling Information - priorities and scheduling queue pointers
 Memory Management Information - memory allocated to processes via page tables
 Accounting Information - clock time, time limits, number of accounts.
 I/O Status Information - I/O devices allocated to process and list of open files to be
read/written to.

Operating Systems - Part 3

Threads
A thread is a basic unit of CPU utilization, consisting of a program counter, a stack and set of
registers. It is also called a light weight process. Each thread belongs a process and can not
exist outside a process. They allow us to parallely executeapplication on shared
multiprocessors.

www.BankExamsToday.Com Page 84
IT Officer Professional Knowledge Guide

Like processes, threads share CPU and can create child threads using fork ( ) system call. All
threads can access every address in the task.

What's so good about them?


Multiple threads can share common data thereby eliminating the need for inter process
communication. Also they consume very less resources as compared to processes. Context
switching is more efficient with threads. We'll discuss about context switching in later articles.

Types of Threads

1. User level threads


 Implement in user level libraries not via system calls.
 No modification to operating system is required.
 Creation of thread, switching & sync between them can be done without interrupting the
kernel.

2. Kernel level threads


 Kernel manages the threads by keeping track of all in a thread table.
 Uses system calls to create and manage threads.
 Scheduler may allocate more time to a process having more threads since kernel knows
about them all.
 Much slower than user level threads.

Multi threading models

1. Many to One
Basic features of this model are as follows:

 Many user level threads mapped to a single kernel thread.


 Blocking of one thread causes all to block.
 Multiple threads may not run in parallel as only one in kernel at a time.
 E.g. - Solaris Green Threads, GNU Portable Threads.

www.BankExamsToday.Com Page 85
IT Officer Professional Knowledge Guide

2. One to One
Basic features are as follows:

 Each user level thread is mapped to kernel thread.


 If you create a user thread, a kernel thread will be created.
 Number of threads per process are sometimes restricted.
 E.g. - Linux, Windows.

3. Many to Many
Basic features are as follows:

 Many user level threads are mapped to many kernel level threads.
 If kernel system calls are blocked, it doesn't block the entire process.
 Users have no restrictions on number of threads created.

www.BankExamsToday.Com Page 86
IT Officer Professional Knowledge Guide

Thread Libraries
A thread library provides an API to developer for creating and managing threads. There are 3
main thread libraries that are used across operating systems:

 POSIX Pthreads
 Windows threads
 Java threads

Issues related to Threads

1. Fork ( ) system call


The basic issue that arises is when a thread which forks ( ), duplicates itself only or all other
threads which are associated with the process. Unix systems handle this by having two versions
of fork ( ) system calls and an option suited to requirement is chosen.

2. Signal Handling
Signals in OS are used to notify a process that some event has occurred. A signal handler
processes all signals. Every signal has a default handler assigned by kernel. User defined
signals can over ride them.

3. Thread Cancellation
Threads can be terminated before they have finished in case they are not required anymore.
Two approaches are used for cancelling threads:

 Asynchronous cancellation - it terminates the thread immediately.


 Deferred cancellation - thread is periodically checked if it should be cancelled.
On Linux systems, thread cancellation is handled through signals.

www.BankExamsToday.Com Page 87
IT Officer Professional Knowledge Guide

Operating Systems - Part 4

Critical Section
That part of the program where the shared memory is accessed is called critical section. This
part may not be concurrently executed by more than one process at a time. Each process must
ask permission to enter critical section with ENTRY section and then with EXIT section, comes
out of that and works with remainder section. Following code snippet shows the access of
shared memory by process:

There are 3 principles involved in dealing with critical section:

1. Mutual Exclusion
If one process is executing in critical section, no other process is allowed entry to that.

2. Progress
If no process is currently in critical section and some processes want to enter then only those
processes which are not executing in their remainder section can participate in decision making
that which one will enter the critical section next.

3. Bounded Waiting
Once a process enters critical section, it can not enter again until a waiting process gets its turn.
Entry is managed as a queue.

Many systems even provide hardware support for implementing critical section code. They are
based on idea of locks. The algorithm for using locks looks something like as below:

www.BankExamsToday.Com Page 88
IT Officer Professional Knowledge Guide

Semaphores
A semaphore is a protected integer variable that can facilitate and restrict access to shared
resources in multi programming environment. They were invented by Edsger Djikstra. Two
most common kinds of semaphores are Binary and Counting semaphores.

Counting semaphores represent multiple resources and binary semaphorerepresent two


possible states i.e 0 or 1 (locked and unlocked). They are accessed by two operations i.e Wait (
) and Signal( ).

Deadlock and Starvation


Deadlock is a situation where two or more processes are waiting indefinitelyfor an event that
an be caused by only one of the waiting process.

Starvation is a situation where a process may never be removed from semaphore queue in
which it is suspended.

CPU Scheduling
CPU scheduler selects from among the processes in ready queue which are to be allocated
CPU next. CPU scheduling decision takes places when a process moves through following
states:

 Running to Waiting
 Running to Ready
 Waiting to Ready
 Termination
Scheduling for all of above transitions is non preemptive in nature. All of rest are preemptive in
nature. Non Preemptive scheduling is when CPU is given to a process, it can not be taken
away unless process finishes execution where as preemptive scheduling is when a high
priority task is allocated the CPU while interrupting the currently running process. It is based on
idea that highest priority process should always be the process that is currently utilized.

www.BankExamsToday.Com Page 89
IT Officer Professional Knowledge Guide

Dispatcher
Dispatcher gives control of CPU to process selected by the scheduler. It involves switching
context, switching to user mode and jumping to proper location to restart the
program. Dispatch latency is defined as the time it takes for dispatcher to stop one process
and start another.

More on scheduling will be covered in next article.

Operating System (CPU Scheduling) - Part 5

Scheduling Criteria for Processes


As we know that CPU scheduler selects from among the processes in ready queue and assigns
CPU to one of them. This scheduling is done on basis on certain parameters called scheduling
criteria which are as follows:

 CPU utilization - aim is to keep CPU as busy as possible.


 Throughput - It is viewed in terms of number of processes that complete their execution
per time unit.
 Turnaround Time - amount of time a process takes to execute.
 Waiting Time - amount of time a process has been waiting in the ready queue.
 Response Time - amount of time it takes for first response after a request has been
submitted.

Scheduling Algorithms
The algorithms used mostly in practice are discussed as follows:

1. First Come First Served Scheduling (FCFS)


Major attributes of FCFS are as follows :

 It queues processes in the order that they arrive in ready queue.


 Performance is usually poor as average response time is high.
Consider the process below & their burst times and lets see how their scheduling charts looks
like. (Burst time - amount of CPU time a process requires).

www.BankExamsToday.Com Page 90
IT Officer Professional Knowledge Guide

2. Shortest Job First Scheduling (SJF)


Major attributes of SJF are as follows:
Scheduler picks processes according to their burst times. Shortest one is picked first followed
by next shortest one.

 It gives minimum average waiting time for a given set of processes.

3. Priority Scheduling
Major attributes are as follows:

 A priority number is associated with each process (an integer value)


 CPU is allocated to the process with highest priority.
 Problem - low priority process may never execute. Solution to that would be to increase
the priority as time progresses for a ready process.

www.BankExamsToday.Com Page 91
IT Officer Professional Knowledge Guide

4. Round Robin Scheduling


Major attributes are as follows:

 Each process gets a small unit of CPU time called quantum.


 After that time, current process is preempted and added to end of ready queue. Next
process gets CPU for next quantum.
 It has higher avg waiting time than SJF but better response.
Example of Round Robin Scheduling with time quantum = 4 is as below:

www.BankExamsToday.Com Page 92
IT Officer Professional Knowledge Guide

5. Multi Level Queue Scheduling


Major attributes are as follows:

 In this, ready queue is partitioned into separate queues e.g queue 1 and queue 2.
 One process remains permanently in one queue and can not shift queues.
 Each queue can have its own scheduling algorithms.
 Scheduling must be done between two queues and once CPU assigned to a queue,
process in that will be executed before moving to another queue.

6. Thread Scheduling
Major attributes are as follows:

 Scheduler assigns CPU based on a distinction between user level threads and kernel
threads.
 Competition is between threads inside a process for allocation of CPU.

Practice MCQs
1. Four jobs to be executed on a single processor system arrive at time 0 in the prder A, B, C,
D. Their CPU burst time requirements are 4,1,8,1 units respectively. The completion time of A
under RR scheduling with time quantum =1 would be?
a) 10 b) 4 c) 8 d) 9
2. Which of the follwing scheduling algorithms is non preemptive?
a) FCFS b) RR c) Priority Scheduling d) Multilevel queue

www.BankExamsToday.Com Page 93
IT Officer Professional Knowledge Guide

Operating System (Memory Management) - Part 6

Dynamic Loading and Linking


In Dynamic Loading, some part of the program code which resides in some external library, is
loaded into memory during execution, mostly on demand. Dynamic loading is not controlled by
OS but rather by programmer. It encouragesbetter memory utilization as unused routines are
never loaded into memory.

In Dynamic Linking, system libraries and program code are combined by loader at execution
time. When the libraries are combined at load time itself, it is called static linking.

Swapping
In this mechanism, a process can be temporarily swapped out of memory to a backing store
(usually a hard disk drive) and then brought back into memory for continuing with execution.
Whether or not, the swapped out process will be swapped back into same physical address,
depends on address binding method used. Diagrammatic representation of swapping is as
follows:

Paging
Paging mechanism divides physical memory into fixed size blocks called frames. And it divides
the logical memory into blocks of same size called pages. Logical addresses are mapped to a
real or physical memory addresses. Logical addresses are also called virtual addresses and are
generated by CPU.
Now whenever a process has to be executed, its corresponding pages are loaded in available
memory frames. Operating system sets up a page table to translatelogical to physical
addresses. Logical addresses are divided into page number and page offset. Page number is
used as an index to page table and page offset defines the physical address associated. Page
tables are of two types further- hashed and inverted.

www.BankExamsToday.Com Page 94
IT Officer Professional Knowledge Guide

Virtual Memory
It allows separation of logical memory from physical memory. Large programs store
themselves in form of pages here and at execution, not entire programs but required pages are
loaded into main memory. It allows address space to be shared by several processes. Virtual
memory can be implemented via demand paging and demand segmentation.

Demand Paging
In this concept, pages are brought into memory only when they are needed. It provides are less
I/O and more faster response. How this works - whenever a page is needed, a reference is
made to it and brought into memory. If invalid reference, instruction is aborted and if required
page is not in memory- it is brought into it and referenced again. When the page required is not
available - an interrupt called trap is issued to operating system, this process is called page
fault.

Page Replacement
As we discussed earlier that whenever a page fault occurs, referenced page is brought into
memory. Now let's say memory has no free space and some other page needs to be swapped
out for that. This process is called page replacement.This swapped out page when referenced
later will have to be read from disk and this might involve waiting for I/O completion. This is what
defines the quality of page replacement algorithm used. Various algorithms used are as follows:

 RAND (Random)- chose any page to replace.


 OPT (Optimal) - replace the page that will be reference furthest in future.
 FIFO (Fist in, First out) - replace the page that has been longest in the memory.
 LRU (Least recently used) - replace the page that was last reference long time ago.

www.BankExamsToday.Com Page 95
IT Officer Professional Knowledge Guide

Operating Systems (File System) - Part 7

What is a file?
A file is a collection of data or information which has a name. A file system is the way in which
files are named and stored and retrieved logically. Attributes of a file are listed as below:

 Name - in human readable form


 Identifier - unique number which identifies a file within a file system.
 Type - text file, executable file, program file
 Location - pointer to location on device
 Size - file size in b/kb/mb
 Protection - authorizations about reading, writing and executing
 Time, Date and User Identification- for security and monitoring purpose
 Metadata about files stored on the disk
 Operations - create, write, read, delete, truncate, open, close etc.
Common file types and their extensions are listed below:

 executable - .exe, .com, .bin


 object - .obj
 source code - .c, .cc, .java, .pas
 text - .doc, .txt
 batch - .bat, .sh
 word processor - .wp, .rtf, .doc
 library - .lib, .dll
 print or view - .ps, .pdf, .jpg
 archive - .arc, .zip, .tar
 multimedia - .mov, .mpeg, .avi, .mp3

File Format and File Access Methods


File format is the structure of how information is stored in a file. There are different formats for
storing specific types of information as has been explained above with files and their extensions.
File access refers to the manner in which information of file can be accesses. There are three
knows ways to access a file:

1. Sequential Access
In this, information in the file is processed in a specific order i.e one record after another.
Compilers access files sequentially.

2. Direct Access
In this, records need not to be accessed in any sequence. Each record has its own
address and thus can be directly accessed by referencing that address.

3. Indexed Sequential Access

www.BankExamsToday.Com Page 96
IT Officer Professional Knowledge Guide

Its an extension of sequential access in which an index is create for a file which
contains pointers to memory blocks. These pointers are used to access files directly.

File system Layers


Let's look at the flow diagram below and then understand about roles of layers of a file system.

1. Device Drivers
They manage I/O devices at I/O control layer.

2. Basic file system


It translates the commands to device driver. Along with that, it manages memory buffers and
caches.

3. File Organization Module


It understand logical address and physical blocks and translates logical to physical . It also
manages free space and disk allocation.

4. Logical File System


It manages metadata i.e information about files in the file system by maintaining file control
blocks (inodes in unix).

5. Application Programs
They use the information with in a file and manipulate it.

www.BankExamsToday.Com Page 97
IT Officer Professional Knowledge Guide

Partitions and Mounting


A partition can be a volume on disk containing a file system or without it (raw). Root partition
contains the OS usually the primary one.
Mounting takes place before a computer can use any kind of storage device. A mount point is
a physical location in the partition. Mount point forms the connection between file system
containing the mount point and file system to be mount. File systems can be mounted in below
ways in UNIX:

 manually with 'MOUNT' command


 Automatically upon system boot. Information for that is stored in /etc/fstab file.
 Automatically when the file system is accesses, also called auto mounting. E.g.- Plug and
Play USBs when used over linux distributions. In early days of linux, external flash drives
had to be mounted manually before accessing.

Chapter: C Programming

C Programming
C Programming is an ANSI/ISO standard and powerful programming language for developing
real time applications. C programming language was invented by Dennis Ritchie at the Bell
Laboratories in 1972. It was invented for implementing UNIX operating system. C is most widely
used programming language even today. All other programming languages were derived
directly or indirectly from C programming concepts. This tutorial explains all basic concepts in C
like history of C language, data types, keywords, constants, variables, operators, expressions,
control statements, array, pointer, string, library functions, structures and unions etc.
This C programming tutorial is designed for the new learners, students and also for the
corporate level developers who want to learn and refresh their C programming skills.
 The C programming language is a structure oriented programming language, developed at Bell
Laboratories in 1972 by Dennis Ritchie
 C programming language features were derived from an earlier language called “B” (Basic
Combined Programming Language – BCPL)
 C language was invented for implementing UNIX operating system
 In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language” and commonly known as K&R C
 In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”,
was completed late 1988.

www.BankExamsToday.Com Page 98
IT Officer Professional Knowledge Guide

C PROGRAMMING LANGUAGE STANDARDS:


 C89/C90 standard – First standardized specification for C language was developed by the
American National Standards Institute in 1989. C89 and C90 standards refer to the same
programming language.
 C99 standard – Next revision was published in 1999 that introduced new features like advanced
data types and other changes.

C11 AND EMBEDDED C LANGUAGE:


 C11 standard adds new features to C programming language and library like type generic
macros, anonymous structures, improved Unicode support, atomic operations, multi-threading
and bounds-checked functions. It also makes some portions of the existing C99 library optional
and improves compatibility with C++.
 Embedded C includes features not available in C like fixed-point arithmetic, named address
spaces, and basic I/O hardware addressing.
 Operating systems, C compiler and all UNIX application programs are written in C language
 It is also called as procedure oriented programming language. The C language is reliable,
simple and easy to use. C has been coded in assembly language.

FEATURES OF C PROGRAMMING LANGUAGE:

C language is one of the powerful language. Below are some of the features of C language.

 Reliability
 Portability
 Flexibility
 Interactivity
 Modularity
 Efficiency and Effectiveness

USES OF C PROGRAMMING LANGUAGE:

The C programming language is used for developing system applications that forms a major
portion of operating systems such as Windows, UNIX and Linux. Below are some examples of
C being used.

 Database systems
 Graphics packages
 Word processors
 Spreadsheets
 Operating system development
 Compilers and Assemblers
 Network drivers
 Interpreters

www.BankExamsToday.Com Page 99
IT Officer Professional Knowledge Guide

WHICH LEVEL IS C LANGUAGE BELONGING TO?

There are 3 levels of programming languages :

1. MiddleLevellanguages:
Middle level languages don‟t provide all the built-in functions found in high level languages, but
provides all building blocks that we need to produce the result we want. Examples: C, C++
2. HighLevellanguages:
High level languages provide almost everything that the programmer might need to do as
already built into the language. Example: Java, Python
3. LowLevellanguages:
Low level languages provides nothing other than access to the machines basic instruction
set. Example: Assembler

C LANGUAGE IS A STRUCTURED LANGUAGE:

Structure oriented language:

 In this type of language, large programs are divided into small programs called functions
 Prime focus is on functions and procedures that operate on the data
 Data moves freely around the systems from one function to another
 Program structure follows “Top Down Approach”
 Examples: C, Pascal, ALGOL and Modula-2
Object oriented language:

 In this type of language, programs are divided into objects


 Prime focus is in the data that is being operated and not on the functions or procedures
 Data is hidden and cannot be accessed by external functions
 Program structure follows “Bottom UP Approach”
 Examples: C++, JAVA and C# (C sharp)

Non structure oriented language:

There is no specific structure for programming this language. Examples: BASIC, COBOL,
FORTRAN

KEY POINTS TO REMEMBER IN C LANGUAGE:

1. The C language is a structure oriented programming language developed by Dennis Ritchie.


2. The C language is belonging to middle level programming language.
3. Operating system programs such as Windows, Unix, Linux are written in C language.
4. C89/C90 and C99 are two standardized editions of C language.
C has been written in assembly language.

www.BankExamsToday.Com Page 100


IT Officer Professional Knowledge Guide

C – Programming Basics

This C programming basics section explains a simple “Hello World” C program. Also, it covers
below basic topics as well, which are to be known by any C programmer before writing a C
program.
1. C programming basic commands to write a C program
2. A simple C program with output and explanation
3. Steps to write C programs and get the output\

1. C PROGRAMMING BASICS TO WRITE A C PROGRAM:

Below are few commands and syntax used in C programming to write a simple C program. Let‟s
see all the sections of a simple C program line by line.

C Basic commands Explanation

This is a preprocessor command that


includes standard input output header
file(stdio.h) from the C library before
#include <stdio.h> compiling a C program

This is the main function from where


int main() execution of any C program begins.

This indicates the beginning of the


{ main function.

whatever is given inside the command


“/* */” in any C program, won‟t be
considered for compilation and
/*_some_comments_*/ execution.

printf command prints the output onto


printf(“Hello_World! “); the screen.

This command waits for any character


getch(); input from keyboard.

return 0;
This command terminates C program

www.BankExamsToday.Com Page 101


IT Officer Professional Knowledge Guide

(main function) and returns 0.

This indicates the end of the main


} function.

2. A SIMPLE C PROGRAM:

Below C program is a very simple and basic program in C programming language. This C
program displays “Hello World!” in the output window. And, all syntax and commands in C
programming are case sensitive. Also, each statement should be ended with semicolon (;)
which is a statement terminator.

1 #include <stdio.h>

2 int main()

3{

4 /* Our first simple C basic program */

5 printf("Hello World! ");

6 getch();

7 return 0;

8}

OUTPUT:

Hello World!

3. STEPS TO WRITE C PROGRAMS AND GET THE OUTPUT:

Below are the steps to be followed for any C program to create and get the output. This is
common to all C program and there is no exception whether its a very small C program or very
large C program.

1. Create
2. Compile
3. Execute or Run
4. Get the Output

www.BankExamsToday.Com Page 102


IT Officer Professional Knowledge Guide

4. CREATION, COMPILATION AND EXECUTION OF A C PROGRAM:

Prerequisite:

 If you want to create, compile and execute C programs by your own, you have to install C
compiler in your machine. Then, you can start to execute your own C programs in your
machine.
 You can refer below link for how to install C compiler and compile and execute C programs in
your machine.
 Once C compiler is installed in your machine, you can create, compile and execute C programs
as shown in below link.
 If you don‟t want to install C/C++ compilers in your machine, you can refer online compilers
which will compile and execute C/C++ and many other programming languages online and
display outputs on the screen. Please search for online C/C++ compilers in Google for more
details.
C – Environment Setup Using IDE tool

C – Environment Setup Using GCC compiler

5. BASIC STRUCTURE OF A C PROGRAM:

Structure of C program is defined by set of rules called protocol, to be followed by programmer


while writing C program. All C programs are having sections/parts which are mentioned below.

1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section

EXAMPLE C PROGRAM TO COMPARE ALL THE SECTIONS:

You can compare all the sections of a C program with the below C program.

1 /*

2 Documentation section

3 C programming basics & structure of C programs

4 Author: fresh2refresh.com

5 Date : 01/01/2012

www.BankExamsToday.Com Page 103


IT Officer Professional Knowledge Guide

6 */

8 #include <stdio.h> /* Link section */

9 int total = 0; /* Global declaration, definition section */

10 int sum (int, int); /* Function declaration section */

11 int main () /* Main function */

12 {

13 printf ("This is a C basic program \n");

14 total = sum (1, 1);

15 printf ("Sum of two numbers : %d \n", total);

16 return 0;

17 }

18

19 int sum (int a, int b) /* User defined function */

20 {

21 return a + b; /* definition section */

22 }

OUTPUT:

This is a C basic
program
Sum of two numbers : 2

DESCRIPTION FOR EACH SECTION OF THE C PROGRAM:

 Let us see about each section of a C basic program in detail below.


 Please note that a C program mayn‟t have all below mentioned sections except main function
and link sections.
 Also, a C program structure mayn‟t be in below mentioned order.

www.BankExamsToday.Com Page 104


IT Officer Professional Knowledge Guide

Sections Description

We can give comments about the


program, creation or modified date,
author name etc in this section. The
characters or words or anything which
are given between “/*” and “*/”, won‟t
be considered by C compiler for
compilation process. These will be
ignored by C compiler during
compilation.
Documentation Example : /* comment line1 comment
section line2 comment 3 */

Header files that are required to


execute a C program are included in
Link Section this section

Definition In this section, variables are defined


Section and values are set to these variables.

Global variables are defined in this


Global section. When a variable is to be used
declaration throughout the program, can be
section defined in this section.

Function Function prototype gives many


prototype information about a function like return
declaration type, parameter names used inside
section the function.

Every C program is started from main


function and this function contains two
major sections called declaration
Main function section and executable section.

User can define their own functions in


User defined this section which perform particular
function section task as per the user requirement.

www.BankExamsToday.Com Page 105


IT Officer Professional Knowledge Guide

KEY POINTS TO REMEMBER IN C PROGRAMMING BASICS:

1. C programming is a case sensitive programming language.


2. Each C programming statement is ended with semicolon (;) which are referred as statement
terminator.
3. printf() command is used to print the output onto the screen.
4. C programs are compiled using C compilers and displays output when executed.

DATA TYPES:
There are four data types in C language. They are,
Types Data Types

Basic data types int, char, float, double

Enumeration data type enum

Derived data type pointer, array, structure, union

Void data type void

1. BASIC DATA TYPES IN C:

1.1. INTEGER DATA TYPE:

 Integer data type allows a variable to store numeric values.


 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor, 2
byte (16 bit) of memory will be allocated for int data type.
 Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit
processor is allocated for int datatype.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
 If you want to use the integer value that crosses the above limit, you can go for “long int” and
“long long int” for which the limits are very high.
Note:
 We can‟t store decimal values using int data type.
 If we use int data type to store decimal values, decimal values will be truncated and we will get
only whole number.
 In this case, float data type can be used to store decimal values in a variable.

www.BankExamsToday.Com Page 106


IT Officer Professional Knowledge Guide

1.2. CHARACTER DATA TYPE:


 Character data type allows a variable to store only one character.
 Storage size of character data type is 1. We can store only one character using character data
type.
 “char” keyword is used to refer character data type.
 For example, „A‟ can be stored using char datatype. You can‟t store more than one character
using char data type.
 Please refer C – Strings topic to know how to store more than one characters in a variable.

1.3. FLOATING POINT DATA TYPE:


Floating point data type consists of 2 types. They are,
1. float
2. double

1. FLOAT:
 Float data type allows a variable to store decimal values.
 Storage size of float data type is 4. This also varies depend upon the processor in the CPU as
“int” data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float data type.

2. DOUBLE:
 Double data type is also same as float data type which allows up-to 10 digits after decimal.
 The range for double datatype is from 1E–37 to 1E+37.

1.3.1. SIZEOF() FUNCTION IN C:


sizeof() function is used to find the memory space allocated for each C data types.
#include<stdio.h>

int main() {

int ivar = 100;

char cvar = 'a';

float fvar = 10.10;

printf("%d", sizeof(ivar));

printf("%d", sizeof(cvar));

www.BankExamsToday.Com Page 107


IT Officer Professional Knowledge Guide

printf("%d", sizeof(fvar));

return 0;

}
output : #include<stdio.h>

int main() {

printf("%d", sizeof(int));

printf("%d", sizeof(char));

printf("%d", sizeof(float));

return 0;

1.3.2. MODIFIERS IN C:
 The amount of memory space to be allocated for a variable is derived by modifiers.
 Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.
 For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.
 There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long
 Below table gives the detail about the storage size of each C basic data type in 16 bit processor.
Please keep in mind that storage size and range for int and float datatype will vary depend on
the CPU processor (8,16, 32 and 64 bit)
C Data types
/ storage Size Range

char / 1 –127 to 127

int / 2 –32,767 to 32,767

www.BankExamsToday.Com Page 108


IT Officer Professional Knowledge Guide

1E–37 to 1E+37 with six


float / 4 digits of precision

1E–37 to 1E+37 with ten


double / 8 digits of precision

1E–37 to 1E+37 with ten


long double / 10 digits of precision

–2,147,483,647 to
long int / 4 2,147,483,647

short int / 2 –32,767 to 32,767

unsigned short int /


2 0 to 65,535

signed short int / 2 –32,767 to 32,767

–(2power(63) –1) to
long long int / 8 2(power)63 –1

–2,147,483,647 to
signed long int / 4 2,147,483,647

unsigned long int /


4 0 to 4,294,967,295

unsigned long long


int / 8 2(power)64 –1

2. ENUMERATION DATA TYPE IN C: Enumerated data type variables can only assume values
which have been previously declared.
enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
enum month this_month;
this_month = feb;
In the above declaration, month is declared as an enumerated data type. It consists of a set of
values, jan to dec. Numerically, jan is given the value 1, feb the value 2, and so on. The
variable this_month is declared to be of the same type as month, then is assigned the value

www.BankExamsToday.Com Page 109


IT Officer Professional Knowledge Guide

associated with feb. This_month cannot be assigned any values outside those specified in the
initialization list for the declaration of month.

#include <stdio.h>

main()

char *pwest = "west",*pnorth = "north", *peast="east", *psouth = "south";

enum location { east=1, west=2, south=3, north=4};

enum location direction;

direction = east;

if( direction == east )

printf("Cannot go %s\n", peast);

The variables defined in the enumerated variable location should be assigned initial values.

3. DERIVED DATA TYPE IN C:


 Array, pointer, structure and union are called derived data type in C language.
 To know more about derived data types, please visit “C – Array” , “C – Pointer” , “C – Structure”
and “C – Union” topics in this tutorial.

4. VOID DATA TYPE IN C:


 Void is an empty data type that has no value.
 This can be used in functions and pointers.

Declaration of Variable
Declaration of variable in c can be done using following syntax:
data_type variable name;
or
data_type variable1, variable2,…,variablen;
Where data_type is any valid c data type and variable_name is any valid identifier.
For example,

int a;

float variable;

www.BankExamsToday.Com Page 110


IT Officer Professional Knowledge Guide

float a, b;

 Initialization of Variable
C variables declared can be initialized with the help of assignment operator „=‟.

 Syntax
data_type variable name=constant/literal/expression;
or
variable name=constant/literal/expression;
Example

int a=10;

int a=b+c;

a=10;

a=b+c;

multiiple variables can be initialized in a single statement by single value, for example,
a=b=c=d=e=10;

 NOTE: C variables must be declared before they are used in the c program. Also, since c is a
case sensitive programming language, therefore the c variables, abc, Abc and ABC are all
different.
Constant and Volatile Variables
Constant Variables
C variables having same or unchanged value during the execution of a program are called
constant variables. A variable can be declared as constant using keyword const.
For example,

const int a=100;

Now, if we try to change its value, then it is invalid.


Volatile Variables
Those variables that can be changed at any time by some external sources from outside or
same program are called volatile variables.
Any variable in c can be declared as volatile using keyword volatile.
 Syntax
volatile data_type variable_name;

 NOTE: If the value of a variable in the current program is to be maintained constant and desired
not to be changed by any other external operation, then the variable declaration will be volatile
const d=10;

www.BankExamsToday.Com Page 111


IT Officer Professional Knowledge Guide

C – Array
C Array is a collection of variables belongings to the same data type. You can store group of
data of same data type in an array.
 Array might be belonging to any of the data types
 Array size must be a constant value.
 Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
 It is a best practice to initialize an array to zero or null while declaring, if we don‟t assign any
values to array.
EXAMPLE FOR C ARRAYS:
 int a[10]; // integer array
 char b[10]; // character array i.e. string

TYPES OF C ARRAYS:
There are 2 types of C arrays. They are,
 One dimensional array
 Multi dimensional array
 Two dimensional array
 Three dimensional array
 four dimensional array etc…

1. ONE DIMENSIONAL ARRAY IN C:


Syntax: data-type arr_name[array_size];
Array declaration,
initialization and
accessing Example

Integer array
Array declaration example:
syntax:
data_type arr_name int age [5];
[arr_size]; int age[5]={0, 1, 2,
Array initialization 3, 4};
syntax: age[0]; /*0 is
data_type arr_name accessed*/
[arr_size]=(value1, age[1]; /*1 is
value2, value3,….); accessed*/
Array accessing age[2]; /*2 is
syntax: accessed*/

www.BankExamsToday.Com Page 112


IT Officer Professional Knowledge Guide

arr_name[index]; Character array


example:

char str[10];
char
str[10]={„H‟,„a‟,„i‟};
(or)
char str[0] = „H‟;
char str[1] = „a‟;
char str[2] = „i;
str[0]; /*H is
accessed*/
str[1]; /*a is
accessed*/
str[2]; /*i is
accessed*/

EXAMPLE PROGRAM FOR ONE DIMENSIONAL ARRAY IN C:


1 #include<stdio.h>

3 int main()

4 {

5 int i;

6 int arr[5] = {10,20,30,40,50};

8 // declaring and Initializing array in C

9 //To initialize all array elements to 0, use int arr[5]={0};

10 /* Above array can be initialized as below also

11 arr[0] = 10;

12 arr[1] = 20;

13 arr[2] = 30;

14 arr[3] = 40;

15 arr[4] = 50; */

www.BankExamsToday.Com Page 113


IT Officer Professional Knowledge Guide

16

17 for (i=0;i<5;i++)

18 {

19 // Accessing each variable

20 printf("value of arr[%d] is %d \n", i, arr[i]);

21 }

22

23 }

OUTPUT:

value of arr[0] is 10

value of arr[1] is 20

value of arr[2] is 30

value of arr[3] is 40

value of arr[4] is 50

2. TWO DIMENSIONAL ARRAY IN C:

 Two dimensional array is nothing but array of array.


 syntax : data_type array_name[num_of_rows][num_of_column];

Array declaration,
initialization and accessing Example

www.BankExamsToday.Com Page 114


IT Officer Professional Knowledge Guide

Integer array
Array declaration syntax: example:
data_type arr_name
[num_of_rows][num_of_column]; int arr[2][2];
int arr[2][2] = {1,2, 3,
Array initialization syntax: 4};
data_type arr_name[2][2] = arr [0] [0] = 1;
{{0,0},{0,1},{1,0},{1,1}}; arr [0] ]1] = 2;
Array accessing syntax: arr [1][0] = 3;
arr_name[index]; arr [1] [1] = 4;

Dynamic memory allocation


DYNAMIC MEMORY ALLOCATION FUNCTIONS IN C:
C language offers 4 dynamic memory allocation functions. They are,
1. malloc()
2. calloc()
3. realloc()
4. free()
Function Syntax

malloc () malloc (number *sizeof(int));

calloc () calloc (number, sizeof(int));

realloc () realloc (pointer_name, number * sizeof(int));

free () free (pointer_name);

1. MALLOC() FUNCTION IN C:
 malloc () function is used to allocate space in memory during the execution of the program.
 malloc () does not initialize the memory allocated during execution. It carries garbage value.
 malloc () function returns null pointer if it couldn‟t able to allocate requested amount of memory.

EXAMPLE PROGRAM FOR MALLOC() FUNCTION IN C:


1 #include <stdio.h>

2 #include <string.h>

3 #include <stdlib.h>

www.BankExamsToday.Com Page 115


IT Officer Professional Knowledge Guide

5 int main()

6 {

7 char *mem_allocation;

8 /* memory is allocated dynamically */

9 mem_allocation = malloc( 20 * sizeof(char) );

10 if( mem_allocation== NULL )

11 {

12 printf("Couldn't able to allocate requested memory\n");

13 }

14 else

15 {

16 strcpy( mem_allocation,"fresh2refresh.com");

17 }

18 printf("Dynamically allocated memory content : " \

19 "%s\n", mem_allocation );

20 free(mem_allocation);

21 }

OUTPUT:
2. CALLOC() FUNCTION IN C:
calloc () function is also like malloc () function. But calloc () initializes the allocated memory to
zero. But, malloc() doesn‟t.

EXAMPLE PROGRAM FOR CALLOC() FUNCTION IN C:


1 #include <stdio.h>

2 #include <string.h>

3 #include <stdlib.h>

www.BankExamsToday.Com Page 116


IT Officer Professional Knowledge Guide

5 int main()

6 {

7 char *mem_allocation;

8 /* memory is allocated dynamically */

9 mem_allocation = calloc( 20, sizeof(char) );

10 if( mem_allocation== NULL )

11 {

12 printf("Couldn't able to allocate requested memory\n");

13 }

14 else

15 {

16 strcpy( mem_allocation,"fresh2refresh.com");

17 }

18 printf("Dynamically allocated memory content : " \

19 "%s\n", mem_allocation );

20 free(mem_allocation);

21 }

OUTPUT
3. REALLOC() FUNCTION IN C:
 realloc () function modifies the allocated memory size by malloc () and calloc () functions to new
size.
 If enough space doesn‟t exist in memory of current block to extend, new block is allocated for
the full size of reallocation, then copies the existing data to new block and then frees the old
block.
4. FREE() FUNCTION IN C:
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns
the memory to the system.

EXAMPLE PROGRAM FOR REALLOC() AND FREE() FUNCTIONS

www.BankExamsToday.Com Page 117


IT Officer Professional Knowledge Guide

1 #include <stdio.h>

2 #include <string.h>

3 #include <stdlib.h>

5 int main()

6 {

7 char *mem_allocation;

8 /* memory is allocated dynamically */

9 mem_allocation = malloc( 20 * sizeof(char) );

10 if( mem_allocation == NULL )

11 {

12 printf("Couldn't able to allocate requested memory\n");

13 }

14 else

15 {

16 strcpy( mem_allocation,"fresh2refresh.com");

17 }

18 printf("Dynamically allocated memory content : " \

19 "%s\n", mem_allocation );

20 mem_allocation=realloc(mem_allocation,100*sizeof(char));

21 if( mem_allocation == NULL )

22 {

23 printf("Couldn't able to allocate requested memory\n");

24 }

25 else

26 {

www.BankExamsToday.Com Page 118


IT Officer Professional Knowledge Guide

27 strcpy( mem_allocation,"space is extended upto " \

28 „100 characters");

29 }

30 printf("Resized memory : %s\n", mem_allocation );

31 free(mem_allocation);

32 }

DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC MEMORY


ALLOCATION IN C:
Dynamic memory
Static memory allocation allocation

In static memory allocation,


memory is allocated while In dynamic memory
writing the C program. allocation, memory is
Actually, user requested allocated while executing
memory will be allocated at the program. That
compile time. means at run time.

Memory size can be


Memory size can‟t be modified modified while
while execution. execution.
Example: array Example: Linked list

DIFFERENCE BETWEEN MALLOC() AND CALLOC() FUNCTIONS IN C:


malloc() calloc()

It allocates multiple
It allocates only single block of blocks of requested
requested memory memory

int *ptr;Ptr = calloc( 20,


int *ptr;ptr = malloc( 20 * 20 * sizeof(int) );For
sizeof(int) );For the above, 20*4 the above, 20 blocks of
bytes of memory only allocated memory will be created
in one block. and each contains

www.BankExamsToday.Com Page 119


IT Officer Professional Knowledge Guide

Total = 80 bytes 20*4 bytes of memory.


Total = 1600 bytes

malloc () doesn‟t initializes the calloc () initializes the


allocated memory. It contains allocated memory to
garbage values zero

type cast must be done since Same as malloc ()


this function returns void pointer function int *ptr;ptr =
int *ptr;ptr = (int*)calloc( 20, 20 *
(int*)malloc(sizeof(int)*20 ); sizeof(int) )

Library Functions :

 Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library.
 Each library function in C performs specific operation.
 We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
 These library functions are created by the persons who designed and created C compilers.
 All C standard library functions are declared in many header files which are saved as
file_name.h.
Actually, function declaration, definition for macros are given in all header files.

 We are including these header files in our C program using “#include<file_name.h>” command
to make use of the functions those are declared in the header files.
 When we include header files in our C program using “#include<filename.h>” command, all C
code of the header files are included in C program. Then, this C program is compiled by
compiler and executed.
Please check the below links for actual C source code for the respective C header files.
1. C – stdio.h source code
2. C – conio.h source code
3. C – string.h source code
4. C – stdlib.h source code
5. C – math.h source code
6. C – time.h source code
7. C – ctype.h source code

 If you want to check source code for all header files, you can check inside “include” directory
after C compiler is installed in your machine.
 For example, if you install DevC++ compiler in C directory in your machine, “C:\Dev-
Cpp\include” is the path where all header files will be available.

www.BankExamsToday.Com Page 120


IT Officer Professional Knowledge Guide

Typedef:

 Typedef is a keyword that is used to give a new symbolic name for the existing name in a C
program. This is same like defining alias for the commands.
 Consider the below structure.
structstudent
{
intmark[2];
charname[10];
floataverage;
}
 Variable for the above structure can be declared in two ways.
1st way :
structstudentrecord;/*fornormalvariable*/
struct student *record; /* for pointer variable */
2nd way :
typedef struct student status;

 When we use “typedef” keyword before struct <tag_name> like above, after that we can simply
use type definition “status” in the C program to declare structure variable.
 Now, structure variable declaration will be, “status record”.
 This is equal to “struct student record”. Type definition for “struct student” is status. i.e. status =
“struct student”

AN ALTERNATIVE WAY FOR STRUCTURE DECLARATION USING TYPEDEF IN C:


typedefstructstudent
{
intmark[2];
charname[10];
floataverage;
} status;

 To declare structure variable, we can use the below statements.


status record1; /* record 1 is structure variable */
status record2; /* record 2 is structure variable */

www.BankExamsToday.Com Page 121


IT Officer Professional Knowledge Guide

EXAMPLE PROGRAM FOR C TYPEDEF:


// Structure using typedef:
1

2
#include <stdio.h>
3
#include <string.h>
4

5
typedef struct student
6
{
7
int id;
8
char name[20];
9
float percentage;
10
} status;
11

12
int main()
13
{
14
status record;
15
record.id=1;
16
strcpy(record.name, "Raju");
17
record.percentage = 86.5;
18
printf(" Id is: %d \n", record.id);
19
printf(" Name is: %s \n", record.name);
20
printf(" Percentage is: %f \n", record.percentage);
21
return 0;
22
}
23

www.BankExamsToday.Com Page 122


IT Officer Professional Knowledge Guide

C++ PROGRAMMING
Intoduction: C++ is a middle-level programming language developed by Bjarne Stroustrup
starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX.

This reference will take you through simple and practical approach while learning C++
Programming language.

Audience:

This reference has been prepared for the beginners to help them understand the basic to
advanced concepts related to C++ Programming languages.

Prerequisites

Before you start doing practice with various types of examples given in this reference, I'm
making an assumption that you are already aware about what is a computer program and what
is a computer programming language?

Execute C++ Online

For most of the examples given in this tutorial you will find Try it option, so just make use of this
option to execute your C++ programs at the spot and enjoy your learning.

Try following example using Try it option available at the top right corner of the below sample
code box −
#include <iostream>

using namespace std;

int main()

cout << "Hello World";

return 0;

www.BankExamsToday.Com Page 123


IT Officer Professional Knowledge Guide

C++ and Object Oriented Programming


Object Oriented programming is a programming style that is associated with the concept of
Class, Objects and various other concepts revovling around these two, like Inheritance,
Polymorphism, Abstraction, Encapsulation etc.

Let us try to understand a little about all these, through a simple example. Human Beings are
living forms, broadly categorized into two types, Male and Female. Right? Its true. Every Human
being(Male or Female) has two legs, two hands, two eyes, one nose, one heart etc. There are
body parts that are common for Male and Female, but then there are some specific body parts,
present in a Male which are not present in a Female, and some body parts present in Female
but not in Males.
All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs
some common functions, but there are some specifics to both, which is not valid for the other
For example : A Female can give birth, while a Male cannot, so this is only for the Female.
Human Anatomy is interesting, isn't it? But let's see how all this is related to C++ and OOPS.
Here we will try to explain all the OOPS concepts through this example and later we will have
the technical definitons for all this.

Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which
defines its properties and its functions. Like Human Being, having body parts, and performing
various actions.

Inheritance
Considering Human Being a class, which has properties like hands, legs, eyes etc, and
functions like walk, talk, eat, see etc. Male and Female are also classes, but most of the
properties and functions are included in Human Being, hence they can inherit everything from
class Human Being using the concept of Inheritance.

www.BankExamsToday.Com Page 124


IT Officer Professional Knowledge Guide

Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being,
Male or Female, we just mean a kind, you, your friend, me we are the forms of these classes.
We have a physical existence while a class is just a logical definition. We are the objects.

Abstraction
Abstraction means, showcasing only the required things to the outside workd while hiding the
details. Continuing our example, Human Being's can talk, walk, hear, eat, but the details are
hidden from the outside world. We can take our skin as the Abstraction factor in our case, hiding
the inside mechanism.

Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk.
Our hands, help us hold things. This binding of the properties to functions is called
Encapsulation.

Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either
changing how it is done or by changing the parts using which it is done. Both the ways have
different terms for them.
If we walk using our hands, and not legs, here we will change the parts used to perform
something. Hence this is called Overloading.
And if there is a defined way of walking, but I wish to walk differently, but using my legs, like
everyone else. Then I can walk like I want, this will be calles as Overriding.

OOPS Concept Definitions

Now, let us discuss some of the main features of Object Oriented Programming which you will
be using in C++(technically).
1. Objects
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Overloading
7. Exception Handling

Objects
Objects are the basic unit of OOP. They are instances of class, which have data members and
uses various member functions to perform tasks.

www.BankExamsToday.Com Page 125


IT Officer Professional Knowledge Guide

Class
It is similar to structures in C language. Class can also be defined as user defined data type but
it also contains functions in it. So, class is basically a blueprint for object. It declare & defines
what data variables the object will have and what operations can be performed on the class's
object.

Abstraction
Abstraction refers to showing only the essential features of the application and hiding the
details. In C++, classes provide methods to the outside world to access & use the data
variables, but the variables are hidden from direct access. This can be done access specifiers.

Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables and
functions together in class.

Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is
called base calls & the class which inherits is called derived class. So when, a derived class
inherits a base class, the derived class can use all the functions which are defined in base
class, hence making code reusable.

Polymorphism
It is a feature, which lets us create functions with same name but different arguments, which will
perform differently. That is function with same name, functioning in different way. Or, it also
allows us to redefine a function to provide its new definition. You will learn how to do this in
details soon in coming lessons.

Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at
runtime.

Chapter : C++ Programming

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.

www.BankExamsToday.Com Page 126


IT Officer Professional Knowledge Guide

Program data: The data is the information of the program which 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
misuse. 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.

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;

www.BankExamsToday.Com Page 127


IT Officer Professional Knowledge Guide

class Adder{
public:
// constructor
Adder(int i = 0)
{
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;

a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}

Inheritance:
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to create
and maintain an application. This also provides an opportunity to reuse the code functionality
and fast implementation time.

When creating a class, instead of writing completely new data members and member functions,
the programmer can designate that the new class should inherit the members of an existing
class. This existing class is called the baseclass, and the new class is referred to as
the derived class.

www.BankExamsToday.Com Page 128


IT Officer Professional Knowledge Guide

The idea of inheritance implements the is a relationship. For example, mammal IS-A animal,
dog IS-A mammal hence dog IS-A animal as well and so on.

Base & Derived Classes:


A class can be derived from more than one classes, which means it can inherit data and
functions from multiple base classes. To define a derived class, we use a class derivation list to
specify the base class(es). A class derivation list names one or more base classes and has the
form:

class derived-class: access-specifier base-class

Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows:

#include <iostream>

using namespace std;

// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);

www.BankExamsToday.Com Page 129


IT Officer Professional Knowledge Guide

}
};

int main(void)
{
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}

Access Control and Inheritance:


A derived class can access all the non-private members of its base class. Thus base-class
members that should not be accessible to the member functions of derived classes should be
declared private in the base class.

We can summarize the different access types according to who can access them in the
following way:

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

A derived class inherits all base class methods with the following exceptions:

 Constructors, destructors and copy constructors of the base class.


 Overloaded operators of the base class.
 The friend functions of the base class.

Type of Inheritance:

www.BankExamsToday.Com Page 130


IT Officer Professional Knowledge Guide

When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.

We hardly use protected or private inheritance, but public inheritance is commonly used.
While using different type of inheritance, following rules are applied:

 Public Inheritance: When deriving a class from a public base class,public members of the
base class become public members of the derived class and protected members of the base
class becomeprotected members of the derived class. A base class's privatemembers are
never accessible directly from a derived class, but can be accessed through calls to
the public and protected members of the base class.

 Protected Inheritance: When deriving from a protected base


class,public and protected members of the base class become protectedmembers of the
derived class

 Private Inheritance: When deriving from a private base class,public and protected members
of the base class become privatemembers of the derived class.

Multiple Inheritances:
A C++ class can inherit members from more than one class and here is the extended syntax:

class derived-class: access baseA, access baseB....

Where access is one of public, protected, or private and would be given for every base class
and they will be separated by comma as shown above. Let us try the following example:

#include <iostream>

using namespace std;

// Base class Shape


class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;

www.BankExamsToday.Com Page 131


IT Officer Professional Knowledge Guide

}
protected:
int width;
int height;
};

// Base class PaintCost


class PaintCost
{
public:
int getCost(int area)
{
return area * 70;
}
};

// Derived class
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};

int main(void)
{
Rectangle Rect;
int area;

Rect.setWidth(5);
Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

// Print the total cost of painting


cout << "Total paint cost: $" << Rect.getCost(area) << endl;

return 0;
}

www.BankExamsToday.Com Page 132


IT Officer Professional Knowledge Guide

The Class Constructor:


A class constructor is a special member function of a class that is executed whenever we
create new objects of that class.
A constructor will have exact same name as the class and it does not have any return type at
all, not even void. Constructors can be very useful for setting initial values for certain member
variables.

Following example explains the concept of constructor:


#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:

www.BankExamsToday.Com Page 133


IT Officer Professional Knowledge Guide

Object is being created


Length of line : 6

Parameterized Constructor:

A default constructor does not have any parameter, but if you need, a constructor can have
parameters. This helps you to assign initial value to an object at the time of its creation as
shown in the following example:

#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);

www.BankExamsToday.Com Page 134


IT Officer Professional Knowledge Guide

cout << "Length of line : " << line.getLength() <<endl;


return 0;
}

When the above code is compiled and executed, it produces the following result:

Object is being created, length = 10


Length of line : 10
Length of line : 6

Using Initialization Lists to Initialize Fields:

In case of parameterized constructor, you can use following syntax to initialize the fields:
Line::Line( double len): length(len)
{
cout << "Object is being created, length = " << len << endl;
}
Above syntax is equal to the following syntax:
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}

If for a class C, you have multiple fields X, Y, Z, etc., to be initialized, then use can use same
syntax and separate the fields by comma as follows:

C::C( double a, double b, double c): X(a), Y(b), Z(c)


{
....
}

The Class Destructor:

A destructor is a special member function of a class that is executed whenever an object of it's
class goes out of scope or whenever the delete expression is applied to a pointer to the object
of that class.

www.BankExamsToday.Com Page 135


IT Officer Professional Knowledge Guide

A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither
return a value nor can it take any parameters. Destructor can be very useful for releasing
resources before coming out of the program like closing files, releasing memories etc.

Following example explains the concept of destructor:

#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}

www.BankExamsToday.Com Page 136


IT Officer Professional Knowledge Guide

File handling:

Data Type Description

ofstream This data type represents the output file stream and
is used to create files and to write information to
files.

ifstream This data type represents the input file stream and
is used to read information from files.

fstream This data type represents the file stream generally,


and has the capabilities of both ofstream and
ifstream which means it can create files, write
information to files, and read information from files.

To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.

Opening a File:
A file must be opened before you can read from it or write to it. Either the of stream or f
stream object may be used to open a file for writing and ifstream object is used to open a file for
reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream,
and of stream objects.
void open(const char *filename, ios::open mode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.
Mode Flag Description

ios::app Append mode. All output to that file to be appended


to the end.

ios::ate Open a file for output and move the read/write


control to the end of the file.

ios::in Open a file for reading.

www.BankExamsToday.Com Page 137


IT Officer Professional Knowledge Guide

ios::out Open a file for writing.

ios::trunc If the file already exists, its contents will be


truncated before opening the file.

You can combine two or more of these values by Orin


g them together. For example if you want to open a file in write mode and want to truncate it in
case it already exists, following will be the syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File
When a C++ program terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.
void close();
Writing to a File:
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use anofstream or fstream object instead of the cout object.
Reading from a File:
You read information from a file into your program using the stream extraction operator (>>) just
as you use that operator to input information from the keyboard. The only difference is that you
use an ifstream or fstream object instead of the cin object.
Read & Write Example:
Following is the C++ program which opens a file in reading and writing mode. After writing
information inputted by the user to a file named afile.dat, the program reads information from the
file and outputs it onto the screen:
#include <fstream>
#include <iostream>
using namespace std;

int main ()
{

char data[100];

www.BankExamsToday.Com Page 138


IT Officer Professional Knowledge Guide

// open a file in write mode.


ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


cin >> data;
cin.ignore();

// again write inputted data into the file.


outfile << data << endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

return 0;
}
When the above code is compiled and executed, it produces the following sample input and
output:
$./a.out

www.BankExamsToday.Com Page 139


IT Officer Professional Knowledge Guide

Writing to the file


Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to read
the line from outside and ignore() function to ignore the extra characters left by previous read
statement.
File Position Pointers:
Both istream and ostream provide member functions for repositioning the file-position pointer.
These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be
specified to indicate the seek direction. The seek direction can be ios::beg (the default) for
positioning relative to the beginning of a stream,ios::cur for positioning relative to the current
position in a stream or ios::endfor positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of
bytes from the file's starting location. Some examples of positioning the "get" file-position pointer
are:
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );

// position n bytes forward in fileObject


fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n, ios::end );

// position at end of fileObject


fileObject.seekg( 0, ios::end );

Operators overloading in C++:

You can redefine or overload most of the built-in operators available in C++. Thus a
programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed by the
symbol for the operator being defined. Like any other function, an overloaded operator has a
return type and a parameter list.

Box operator+(const Box&);

www.BankExamsToday.Com Page 140


IT Officer Professional Knowledge Guide

declares the addition operator that can be used to add two Box objects and returns final Box
object. Most overloaded operators may be defined as ordinary non-member functions or as
class member functions. In case we define above function as non-member function of a class
then we would have to pass two arguments for each operand as follows:

Box operator+(const Box&, const Box&);

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;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box

www.BankExamsToday.Com Page 141


IT Officer Professional Knowledge Guide

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
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
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:

www.BankExamsToday.Com Page 142


IT Officer Professional Knowledge Guide

+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* new new [] delete delete []

Following is the list of operators, which can not be overloaded:


:: .* . ?:

Operator Overloading Examples:


Here are various operator overloading examples to help you in understanding the concept.
S.N. Operators and Example

1 Unary operators overloading

2 Binary operators overloading

3 Relational operators overloading

4 Input/Output operators overloading

5 ++ and -- operators overloading

6 Assignment operators overloading

7 Function call () operator overloading

www.BankExamsToday.Com Page 143


IT Officer Professional Knowledge Guide

8 Subscripting [] operator overloading

9 Class member access operator -> overloading

Function overloading in C++:

You can have multiple definitions for the same function name in the same scope. The definition
of the function must differ from each other by the types and/or the number of arguments in the
argument list. You can not overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types:
#include <iostream>
using namespace std;

class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}

void print(double f) {
cout << "Printing float: " << f << endl;
}

void print(char* c) {
cout << "Printing character: " << c << endl;
}
};

int main(void)
{
printData pd;

// Call print to print integer


pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");

return 0;

www.BankExamsToday.Com Page 144


IT Officer Professional Knowledge Guide

}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C+

Friend Function : A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the prototypes for
friend functions appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class template,
in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class definition
with keyword friend as follows:
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

To declare all member functions of class ClassTwo as friends of class ClassOne, place a
following declaration in the definition of class ClassOne:

friend class ClassTwo;

Consider the following program:

#include <iostream>

using namespace std;

class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};

www.BankExamsToday.Com Page 145


IT Officer Professional Knowledge Guide

// Member function definition


void Box::setWidth( double wid )
{
width = wid;
}

// Note: printWidth() is not a member function of any class.


void printWidth( Box box )
{
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}

// Main function for the program


int main( )
{
Box box;

// set box width with member function


box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return 0;
}

Template: Templates are the foundation of generic programming, which involves writing code in
a way that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library
containers like iterators and algorithms are examples of generic programming and have been
developed using template concept.
There is a single definition of each container, such as vector, but we can define many different
kinds of vectors for example, vector <int> or vector <string>.
You can use templates to define functions as well as classes, let us see how do they work:

Function Template:
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function

www.BankExamsToday.Com Page 146


IT Officer Professional Knowledge Guide

}
Here, type is a placeholder name for a data type used by the function. This name can be used
within the function definition.
The following is the example of a function template that returns the maximum of two values:
#include <iostream>
#include <string>

using namespace std;

template <typename T>


inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{

int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;

double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;

string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;

return 0;
}

If we compile and run above code, this would produce the following result:

Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
Class Template:
Just as we can define function templates, we can also define class templates. The general form
of a generic class declaration is shown here:
template <class type> class class-name {
.

www.BankExamsToday.Com Page 147


IT Officer Professional Knowledge Guide

.
.
}

Here, type is the placeholder type name, which will be specified when a class is instantiated.
You can define more than one generic data type by using a comma-separated list.
Following is the example to define class Stack<> and implement generic methods to push and
pop the elements from the stack:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>


class Stack {
private:
vector<T> elems; // elements

public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const{ // return true if empty.
return elems.empty();
}
};

template <class T>


void Stack<T>::push (T const& elem)
{
// append copy of passed element
elems.push_back(elem);
}

template <class T>


void Stack<T>::pop ()
{
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");

www.BankExamsToday.Com Page 148


IT Officer Professional Knowledge Guide

}
// remove last element
elems.pop_back();
}

template <class T>


T Stack<T>::top () const
{
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}

int main()
{
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings

// manipulate int stack


intStack.push(7);
cout << intStack.top() <<endl;

// manipulate string stack


stringStack.push("hello");
cout << stringStack.top() << std::endl;
stringStack.pop();
stringStack.pop();
}
catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}

Exceptions:

An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.

www.BankExamsToday.Com Page 149


IT Officer Professional Knowledge Guide

Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, andthrow.

 throw: A program throws an exception when a problem shows up. This is done using
a throw keyword.

 catch: A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. Thecatch keyword indicates the catching of an
exception.

 try: A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a combination
of the try and catch keywords. A try/catch block is placed around the code that might generate
an exception. Code within a try/catch block is referred to as protected code, and the syntax for
using try/catch looks like the following:

try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}

You can list down multiple catch statements to catch different type of exceptions in case
your try block raises more than one exception in different situations.
Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throwstatements. The operand
of the throw statements determines a type for the exception and can be any expression and the
type of the result of the expression determines the type of exception thrown.

Following is an example of throwing an exception when dividing by zero condition occurs:

double division(int a, int b)

www.BankExamsToday.Com Page 150


IT Officer Professional Knowledge Guide

{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

Catching Exceptions:

The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch.

try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}

Above code will catch an exception of ExceptionName type. If you want to specify that a catch
block should handle any type of exception that is thrown in a try block, you must put an ellipsis,
..., between the parentheses enclosing the exception declaration as follows:

try
{
// protected code
}catch(...)
{
// code to handle any exception
}

The following is an example, which throws a division by zero exception and we catch it in catch
block.

#include <iostream>
using namespace std;

double division(int a, int b)


{

www.BankExamsToday.Com Page 151


IT Officer Professional Knowledge Guide

if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}

int main ()
{
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}
Because we are raising an exception of type const char*, so while catching this exception, we
have to use const char* in catch block. If we compile and run above code, this would produce
the following result:
Division by zero condition!

C++ Standard Exceptions:

C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below:

www.BankExamsToday.Com Page 152


IT Officer Professional Knowledge Guide

Here is the small description of each exception mentioned in the above hierarchy:
Exception Description

std::exception An exception and parent class of all the standard


C++ exceptions.

std::bad_alloc This can be thrown by new.

www.BankExamsToday.Com Page 153


IT Officer Professional Knowledge Guide

std::bad_cast This can be thrown by dynamic_cast.

std::bad_exception This is useful device to handle unexpected


exceptions in a C++ program

std::bad_typeid This can be thrown by typeid.

std::logic_error An exception that theoretically can be detected by


reading the code.

std::domain_error This is an exception thrown when a mathematically


invalid domain is used

std::invalid_argument This is thrown due to invalid arguments.

std::length_error This is thrown when a too big std::string is created

std::out_of_range This can be thrown by the at method from for


example a std::vector and std::bitset<>::operator[]().

std::runtime_error An exception that theoretically can not be detected


by reading the code.

std::overflow_error This is thrown if a mathematical overflow occurs.

std::range_error This is occured when you try to store a value which


is out of range.

std::underflow_error This is thrown if a mathematical underflow occurs.

Memory Management: A good understanding of how dynamic memory really works in C++ is
essential to becoming a good C++ programmer. Memory in your C++ program is divided into
two parts:
 The stack: All variables declared inside the function will take up memory from the stack.

 The heap: This is unused memory of the program and can be used to allocate the memory
dynamically when program runs.

www.BankExamsToday.Com Page 154


IT Officer Professional Knowledge Guide

Many times, you are not aware in advance how much memory you will need to store particular
information in a defined variable and the size of required memory can be determined at run
time.
You can allocate memory at run time within the heap for the variable of a given type using a
special operator in C++ which returns the address of the space allocated. This operator is
called new operator.
If you are not in need of dynamically allocated memory anymore, you can use delete operator,
which de-allocates memory previously allocated by new operator.

The new and delete operators:


There is following generic syntax to use new operator to allocate memory dynamically for any
data-type.

new data-type;

Here, data-type could be any built-in data type including an array or any user defined data
types include class or structure. Let us start with built-in data types. For example we can define
a pointer to type double and then request that the memory be allocated at execution time. We
can do this using the newoperator with the following statements:
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable

The memory may not have been allocated successfully, if the free store had been used up. So it
is good practice to check if new operator is returning NULL pointer and take appropriate action
as below:

double* pvalue = NULL;


if( !(pvalue = new double ))
{
cout << "Error: out of memory." <<endl;
exit(1);

The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc()
function. The main advantage of new over malloc() is that new doesn't just allocate memory, it
constructs objects which is prime purpose of C++.
At any point, when you feel a variable that has been dynamically allocated is not anymore
required, you can free up the memory that it occupies in the free store with the delete operator
as follows:

delete pvalue; // Release memory pointed to by pvalue

www.BankExamsToday.Com Page 155


IT Officer Professional Knowledge Guide

Let us put above concepts and form the following example to show how new and delete work:

#include <iostream>
using namespace std;

int main ()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;
}
If we compile and run above code, this would produce the following result:

Value of pvalue : 29495

Dynamic Memory Allocation for Arrays:


Consider you want to allocate memory for an array of characters, i.e., string of 20 characters.
Using the same syntax what we have used above we can allocate memory dynamically as
shown below.
char* pvalue = NULL; // Pointer initialized with null
pvalue = new char[20]; // Request memory for the variable
To remove the array that we have just created the statement would look like this:
delete [] pvalue; // Delete array pointed to by pvalue
Following is the syntax of new operator for a multi-dimensional array as follows:
int ROW = 2;
int COL = 3;
double **pvalue = new double* [ROW]; // Allocate memory for rows

// Now allocate memory for columns


for(int i = 0; i < COL; i++) {
pvalue[i] = new double[COL];
}
The syntax to release the memory for multi-dimensional will be as follows:
for(int i = 0; i < COL; i++) {

www.BankExamsToday.Com Page 156


IT Officer Professional Knowledge Guide

delete[] pvalue[i];
}
delete [] pvalue;

Dynamic Memory Allocation for Objects:

Objects are no different from simple data types. For example, consider the following code where
we are going to use an array of objects to clarify the concept:
#include <iostream>
using namespace std;

class Box
{
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};

int main( )
{
Box* myBoxArray = new Box[4];

delete [] myBoxArray; // Delete array

return 0;
}

Chapter: Java Programming

Java Tutorial
Java is a high-level programming language originally developed by Sun Microsystems and
released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX. This tutorial gives a complete understanding of Java.
This reference will take you through simple and practical approaches while learning Java
Programming language.

www.BankExamsToday.Com Page 157


IT Officer Professional Knowledge Guide

Audience
This tutorial has been prepared for the beginners to help them understand the basic to
advanced concepts related to Java Programming language.
Prerequisites
Before you start practicing various types of examples given in this reference, we assume that
you are already aware about computer programs and computer programming languages.

Execute Java Online


For most of the examples given in this tutorial, you will find a „Try it‟ option, which you can use to
execute your Java programs at the spot and enjoy your learning.
Try following the example using the „Try it‟ option available at the top right corner of the
following sample code box –

public class MyFirstJavaProgram {

public static void main(String []args) {


System.out.println("Hello World");
}
}

Java – classes

Nested Classes
In Java, just like methods, variables of a class too can have another class as its member.
Writing a class within another is allowed in Java. The class written within is called the nested
class, and the class that holds the inner class is called the outer class.
Syntax
Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.
class Outer_Demo { class Nested_Demo { }}
Nested classes are divided into two types −
 Non-static nested classes− These are the non-static members of a class.
 Static nested classes− These are the static members of a class.
Inner Classes (Non-static Nested Classes)
Inner classes are a security mechanism in Java. We know a class cannot be associated with the
access modifier private, but if we have the class as a member of other class, then the inner
class can be made private. And this is also used to access the private members of a class.
Inner classes are of three types depending on how and where you define them. They are −
 Inner Class
 Method-local Inner Class
 Anonymous Inner Class

www.BankExamsToday.Com Page 158


IT Officer Professional Knowledge Guide

Inner Class

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.
Example
class Outer_Demo { int num; // inner class private class Inner_Demo { public void
print() { System.out.println("This is an inner class"); } } // Accessing he inner class
from the method within void display_Inner() { Inner_Demo inner = new
Inner_Demo(); inner.print(); }} public class My_class { public static void main(String
args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); //
Accessing the display_Inner() method. outer.display_Inner(); }}
Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner
class, display_Inner() is the method inside which we are instantiating the inner class, and this
method is invoked from the mainmethod.
If you compile and execute the above program, you will get the following result −
Output
This is an inner class.

Accessing the Private Members

As mentioned earlier, inner classes are also used to access the private members of a class.
Suppose, a class is having private members to access them. Write an inner class in it, return
the private members from a method within the inner class, say, getValue(), and finally from
another class (from which you want to access the private members) call the getValue() method
of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using
the object of the outer class, following is the way in which you can instantiate the inner class.
Outer_Demo outer = new Outer_Demo();Outer_Demo.Inner_Demo inner = outer.new
Inner_Demo();
The following program shows how to access the private members of a class using inner class.

Example
class Outer_Demo { // private variable of the outer class private int num = 175; // inner
class public class Inner_Demo { public int getNum() { System.out.println("This is the
getnum method of the inner class"); return num; } }} public class My_class2 { public
static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new
Outer_Demo(); // Instantiating the inner class Outer_Demo.Inner_Demo inner =
outer.new Inner_Demo(); System.out.println(inner.getNum()); }}
If you compile and execute the above program, you will get the following result –

www.BankExamsToday.Com Page 159


IT Officer Professional Knowledge Guide

Output
The value of num in the class Test is: 175

Method-local Inner Class


In Java, we can write a class within a method and this will be a local type. Like local variables,
the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner class is
defined. The following program shows how to use a method-local inner class.

Example
public class Outerclass { // instance method of the outer class void my_Method() { int num
= 23; // method-local inner class class MethodInner_Demo { public void print()
{ System.out.println("This is method inner class "+num); } } // end of
inner class // Accessing the inner class MethodInner_Demo inner = new
MethodInner_Demo(); inner.print(); } public static void main(String args[])
{ Outerclass outer = new Outerclass(); outer.my_Method(); }}
If you compile and execute the above program, you will get the following result –

Output
This is method inner class 23

 Anonymous Inner Class


An inner class declared without a class name is known as an anonymous inner class. In case
of anonymous inner classes, we declare and instantiate them at the same time. Generally, they
are used whenever you need to override the method of a class or an interface. The syntax of an
anonymous inner class is as follows −
Syntax
AnonymousInner an_inner = new AnonymousInner() { public void my_method()
{ ........ ........ } };
The following program shows how to override the method of a class using anonymous inner
class.
Example
abstract class AnonymousInner { public abstract void mymethod();} public class Outer_class
{ public static void main(String args[]) { AnonymousInner inner = new AnonymousInner()
{ public void mymethod() { System.out.println("This is an example of anonymous
inner class"); } }; inner.mymethod(); }}
If you compile and execute the above program, you will get the following result −
Output
This is an example of anonymous inner class
In the same way, you can override the methods of the concrete class as well as the interface
using an anonymous inner class.

www.BankExamsToday.Com Page 160


IT Officer Professional Knowledge Guide

Anonymous Inner Class as Argument


Generally, if a method accepts an object of an interface, an abstract class, or a concrete class,
then we can implement the interface, extend the abstract class, and pass the object to the
method. If it is a class, then we can directly pass it to the method.
But in all the three cases, you can pass an anonymous inner class to the method. Here is the
syntax of passing an anonymous inner class as a method argument −
obj.my_Method(new My_Class() { public void Do() { ..... ..... }});
The following program shows how to pass an anonymous inner class as a method argument.
Example
// interfaceinterface Message { String greet();} public class My_class { // method which
accepts the object of interface Message public void displayMessage(Message m)
{ System.out.println(m.greet() + ", This is an example of anonymous inner class as an
argument"); } public static void main(String args[]) { // Instantiating the class My_class
obj = new My_class(); // Passing an anonymous inner class as an
argument obj.displayMessage(new Message() { public String greet() { return
"Hello"; } }); }}
If you compile and execute the above program, it gives you the following result −
Output
Hello This is an example of anonymous inner class as an argument
Static Nested Class
A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of
the outer class. The syntax of static nested class is as follows −
Syntax
class MyOuter { static class Nested_Demo { }}
Instantiating a static nested class is a bit different from instantiating an inner class. The following
program shows how to use a static nested class.
Example
public class Outer { static class Nested_Demo { public void my_method()
{ System.out.println("This is my nested class"); } } public static void main(String
args[]) { Outer.Nested_Demo nested = new
Outer.Nested_Demo(); nested.my_method(); }}

In this chapter, we will discuss inner classes of Java.


Nested Classes
In Java, just like methods, variables of a class too can have another class as its member.
Writing a class within another is allowed in Java. The class written within is called the nested
class, and the class that holds the inner class is called the outer class.
Syntax
Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.
class Outer_Demo { class Nested_Demo { }}

www.BankExamsToday.Com Page 161


IT Officer Professional Knowledge Guide

Nested classes are divided into two types −


 Non-static nested classes− These are the non-static members of a class.
 Static nested classes− These are the static members of a class.
Inner Classes (Non-static Nested Classes)
Inner classes are a security mechanism in Java. We know a class cannot be associated with the
access modifier private, but if we have the class as a member of other class, then the inner
class can be made private. And this is also used to access the private members of a class.
Inner classes are of three types depending on how and where you define them. They are −
 Inner Class
 Method-local Inner Class
 Anonymous Inner Class

Inner Class

Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.
Example
class Outer_Demo { int num; // inner class private class Inner_Demo { public void
print() { System.out.println("This is an inner class"); } } // Accessing he inner class
from the method within void display_Inner() { Inner_Demo inner = new
Inner_Demo(); inner.print(); }} public class My_class { public static void main(String
args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); //
Accessing the display_Inner() method. outer.display_Inner(); }}
Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner
class, display_Inner() is the method inside which we are instantiating the inner class, and this
method is invoked from the mainmethod.
If you compile and execute the above program, you will get the following result −
Output
This is an inner class.

Accessing the Private Members

As mentioned earlier, inner classes are also used to access the private members of a class.
Suppose, a class is having private members to access them. Write an inner class in it, return
the private members from a method within the inner class, say, getValue(), and finally from
another class (from which you want to access the private members) call the getValue() method
of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter, using
the object of the outer class, following is the way in which you can instantiate the inner class.
Outer_Demo outer = new Outer_Demo();Outer_Demo.Inner_Demo inner = outer.new
Inner_Demo();

www.BankExamsToday.Com Page 162


IT Officer Professional Knowledge Guide

The following program shows how to access the private members of a class using inner class.
Example
class Outer_Demo { // private variable of the outer class private int num = 175; // inner
class public class Inner_Demo { public int getNum() { System.out.println("This is the
getnum method of the inner class"); return num; } }} public class My_class2 { public
static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new
Outer_Demo(); // Instantiating the inner class Outer_Demo.Inner_Demo inner =
outer.new Inner_Demo(); System.out.println(inner.getNum()); }}
If you compile and execute the above program, you will get the following result −
Output
The value of num in the class Test is: 175
Method-local Inner Class
In Java, we can write a class within a method and this will be a local type. Like local variables,
the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner class is
defined. The following program shows how to use a method-local inner class.
Example
public class Outerclass { // instance method of the outer class void my_Method() { int num
= 23; // method-local inner class class MethodInner_Demo { public void print()
{ System.out.println("This is method inner class "+num); } } // end of
inner class // Accessing the inner class MethodInner_Demo inner = new
MethodInner_Demo(); inner.print(); } public static void main(String args[])
{ Outerclass outer = new Outerclass(); outer.my_Method(); }}
If you compile and execute the above program, you will get the following result −
Output
This is method inner class 23
Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner class. In case
of anonymous inner classes, we declare and instantiate them at the same time. Generally, they
are used whenever you need to override the method of a class or an interface. The syntax of an
anonymous inner class is as follows −
Syntax
AnonymousInner an_inner = new AnonymousInner() { public void my_method()
{ ........ ........ } };
The following program shows how to override the method of a class using anonymous inner
class.
Example
abstract class AnonymousInner { public abstract void mymethod();} public class Outer_class
{ public static void main(String args[]) { AnonymousInner inner = new AnonymousInner()
{ public void mymethod() { System.out.println("This is an example of anonymous
inner class"); } }; inner.mymethod(); }}
If you compile and execute the above program, you will get the following result −
Output
This is an example of anonymous inner class

www.BankExamsToday.Com Page 163


IT Officer Professional Knowledge Guide

In the same way, you can override the methods of the concrete class as well as the interface
using an anonymous inner class.
Anonymous Inner Class as Argument
Generally, if a method accepts an object of an interface, an abstract class, or a concrete class,
then we can implement the interface, extend the abstract class, and pass the object to the
method. If it is a class, then we can directly pass it to the method.
But in all the three cases, you can pass an anonymous inner class to the method. Here is the
syntax of passing an anonymous inner class as a method argument −
obj.my_Method(new My_Class() { public void Do() { ..... ..... }});
The following program shows how to pass an anonymous inner class as a method argument.
Example
// interfaceinterface Message { String greet();} public class My_class { // method which
accepts the object of interface Message public void displayMessage(Message m)
{ System.out.println(m.greet() + ", This is an example of anonymous inner class as an
argument"); } public static void main(String args[]) { // Instantiating the class My_class
obj = new My_class(); // Passing an anonymous inner class as an
argument obj.displayMessage(new Message() { public String greet() { return
"Hello"; } }); }}
If you compile and execute the above program, it gives you the following result −
Output
Hello This is an example of anonymous inner class as an argument
Static Nested Class
A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of
the outer class. The syntax of static nested class is as follows −
Syntax
class MyOuter { static class Nested_Demo { }}
Instantiating a static nested class is a bit different from instantiating an inner class. The following
program shows how to use a static nested class.
Example
public class Outer { static class Nested_Demo { public void my_method()
{ System.out.println("This is my nested class"); } } public static void main(String
args[]) { Outer.Nested_Demo nested = new
Outer.Nested_Demo(); nested.my_method(); }}

Loop Control
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

www.BankExamsToday.Com Page 164


IT Officer Professional Knowledge Guide

Java programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.

Sr.No. Loop & Description


while loop
1 Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
for loop
2 Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
do...while loop
3
Like a while statement, except that it tests the condition at the end of the loop body.
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Java supports the following control statements. Click the following links to check their detail.
Sr.No. Control Statement & Description
break statement
1 Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
continue statement
2 Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
Enhanced for loop in Java
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of
elements including arrays.

Syntax

Following is the syntax of enhanced for loop −


for(declaration : expression) { // Statements}
 Declaration− The newly declared block variable, is of a type compatible with the elements of
the array you are accessing. The variable will be available within the for block and its value
would be the same as the current array element.
 Expression− This evaluates to the array you need to loop through. The expression can be an
array variable or method call that returns an array.

Example

publicclassTest{ publicstaticvoid main(String args[]){ int[]


numbers={10,20,30,40,50}; for(int x: numbers){ System.out.print(
x); System.out.print(","); } System.out.print("\n"); String[]

www.BankExamsToday.Com Page 165


IT Officer Professional Knowledge Guide

names={"James","Larry","Tom","Lacy"}; for(String name: names){ System.out.print(


name); System.out.print(","); } }}
This will produce the following result −

Output

10, 20, 30, 40, 50,James, Larry, Tom, Lacy


,

Multithreading
Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java. A multi-threaded program contains two or more parts that can run
concurrently and each part can handle a different task at the same time making optimal use of
the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each of the
threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed concurrently
in the same program.

Life Cycle of a Thread


A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. The following diagram shows the complete life cycle of a thread.
Following are the stages of the life cycle –

 New− A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as aborn thread.

 Runnable− After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.

 Waiting− Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.

 Timed Waiting− A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires
or when the event it is waiting for occurs.

www.BankExamsToday.Com Page 166


IT Officer Professional Knowledge Guide

 Terminated (Dead)− A runnable thread enters the terminated state when it completes its task
or otherwise terminates.

Thread Priorities
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY
(a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and are very much platform dependent

Create a Thread by Implementing a Runnable Interface


If your class is intended to be executed as a thread then you can achieve this by implementing
a Runnable interface. You will need to follow three basic steps –

Step 1

As a first step, you need to implement a run() method provided by a Runnableinterface. This
method provides an entry point for the thread and you will put your complete business logic
inside this method. Following is a simple syntax of the run() method −
public void run( )

Step 2

As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnableinterface
and threadName is the name given to the new thread.

Step 3

Once a Thread object is created, you can start it by calling start() method, which executes a call
to run( ) method. Following is a simple syntax of start() method −
void start();

Example

Here is an example that creates a new thread and starts running it −

www.BankExamsToday.Com Page 167


IT Officer Professional Knowledge Guide

class RunnableDemo implements Runnable { private Thread t; private String


threadName; RunnableDemo( String name) { threadName =
name; System.out.println("Creating " + threadName ); } public void run()
{ System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--)
{ System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for
a while. Thread.sleep(50); } }catch (InterruptedException e)
{ System.out.println("Thread " + threadName + "
interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public
void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new
Thread (this, threadName); t.start (); } }} public class TestThread { public static void
main(String args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-
1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-
2"); R2.start(); } }
This will produce the following result –

Output

Creating Thread-1Starting Thread-1Creating Thread-2Starting Thread-2Running Thread-


1Thread: Thread-1, 4Running Thread-2Thread: Thread-2, 4Thread: Thread-1, 3Thread: Thread-
2, 3Thread: Thread-1, 2Thread: Thread-2, 2Thread: Thread-1, 1Thread: Thread-2, 1Thread
Thread-1 exiting.Thread Thread-2 exiting

Access Modifiers
Java provides a number of access modifiers to set access levels for classes, variables,
methods, and constructors. The four access levels are −
 Visible to the package, the default. No modifiers are needed.
 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).

Default Access Modifier - No Keyword


Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc.
A variable or method declared without any access control modifier is available to any other class
in the same package. The fields in an interface are implicitly public static final and the methods
in an interface are by default public.

Example

Variables and methods can be declared without any modifiers, as in the following examples −
String version = "1.5.1"; boolean processOrder() { return true;}

www.BankExamsToday.Com Page 168


IT Officer Professional Knowledge Guide

Private Access Modifier - Private


Methods, variables, and constructors that are declared private can only be accessed within the
declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Variables that are declared private can be accessed outside the class, if public getter methods
are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from
the outside world.

Example

The following class uses private access control −


public class Logger { private String format; public String getFormat() { return
this.format; } public void setFormat(String format) { this.format = format; }}
Here, the format variable of the Logger class is private, so there's no way for other classes to
retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, andsetFormat(String), which sets its
value.

Public Access Modifier - Public


A class, method, constructor, interface, etc. declared public can be accessed from any other
class. Therefore, fields, methods, blocks declared inside a public class can be accessed from
any class belonging to the Java Universe.
However, if the public class we are trying to access is in a different package, then the public
class still needs to be imported. Because of class inheritance, all public methods and variables
of a class are inherited by its subclasses.

Example

The following function uses public access control −


public static void main(String[] arguments) { // ...}
The main() method of an application has to be public. Otherwise, it could not be called by a
Java interpreter (such as java) to run the class.

Protected Access Modifier - Protected


Variables, methods, and constructors, which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the
protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be
declared protected, however methods and fields in a interface cannot be declared protected.

www.BankExamsToday.Com Page 169


IT Officer Professional Knowledge Guide

Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.

Example

The following parent class uses protected access control, to allow its child class
override openSpeaker() method −
class AudioPlayer { protected boolean openSpeaker(Speaker sp) { // implementation
details }} class StreamingAudioPlayer { boolean openSpeaker(Speaker sp) { //
implementation details }}
Here, if we define openSpeaker() method as private, then it would not be accessible from any
other class other than AudioPlayer. If we define it as public, then it would become accessible to
all the outside world. But our intention is to expose this method to its subclass only, that‟s why
we have used protected modifier.

Access Control and Inheritance

The following rules for inherited methods are enforced −


 Methods declared public in a superclass also must be public in all subclasses.
 Methods declared protected in a superclass must either be protected or public in subclasses;
they cannot be private.
Methods declared private are not

Assignment Operators

The following program is a simple example that demonstrates the assignment operators. Copy
and paste the following Java program in Test.java file. Compile and run this program –

Example
public class Test { public static void main(String args[]) { int a = 10; int b = 20; int c =
0; c = a + b; System.out.println("c = a + b = " + c ); c += a ; System.out.println("c
+= a = " + c ); c -= a ; System.out.println("c -= a = " + c ); c *= a
; System.out.println("c *= a = " + c ); a = 10; c = 15; c /= a ; System.out.println("c
/= a = " + c ); a = 10; c = 15; c %= a ; System.out.println("c %= a = " + c ); c
<<= 2 ; System.out.println("c <<= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = "
+ c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c &= a ; System.out.println("c
&= a = " + c ); c ^= a ; System.out.println("c ^= a = " + c ); c |= a
; System.out.println("c |= a = " + c ); }}
This will produce the following result –

www.BankExamsToday.Com Page 170


IT Officer Professional Knowledge Guide

Output
c = a + b = 30c += a = 40c -= a = 30c *= a = 300c /= a = 1c %= a = 5c <<= 2 = 20c >>= 2 = 5c
>>= 2 = 1c &= a = 0c ^= a = 10
Java Garbage Collection

In java, garbage means unreferenced objects.


Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

Advantage of Garbage Collection

 It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.

 It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.

How can an object be unreferenced?


There are many ways:
 By nulling the reference
 By assigning a reference to another
 By annonymous object etc.

1) By nulling a reference:

1. Employee e=newEmployee();
2. e=null;

2) By assigning a reference to another:

1. Employee e1=newEmployee();
2. Employee e2=newEmployee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:

www.BankExamsToday.Com Page 171


IT Officer Professional Knowledge Guide

1. newEmployee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:

1. protectedvoid finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to perform
cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

1. publicstatic void gc(){}


Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.

Simple Example of garbage collection in java

1. publicclass TestGarbage1{
2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. gc();
9. }

Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.

An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.

 A user has entered an invalid data.


 A file that needs to be opened cannot be found.

www.BankExamsToday.Com Page 172


IT Officer Professional Knowledge Guide

 A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to know
how exception handling works in Java.

 Checked exceptions− A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored at
the time of compilation, the programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then aFileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.

Example

import java.io.File;import java.io.FileReader; public class FilenotFound_Demo { public static


void main(String args[]) { File file = new File("E://file.txt"); FileReader fr = new
FileReader(file); }}
If you try to compile the above program, you will get the following exceptions.

Output

C:\>javac FilenotFound_Demo.javaFilenotFound_Demo.java:8: error: unreported exception


FileNotFoundException; must be caught or declared to be thrown FileReader fr = new
FileReader(file); ^1 error
Note − Since the methods read() and close() of FileReader class throws IOException, you can
observe that the compiler notifies to handle IOException, along with FileNotFoundException
.
 Unchecked exceptions− An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.

For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then anArrayIndexOutOfBoundsExceptionexception occurs.

Example

www.BankExamsToday.Com Page 173


IT Officer Professional Knowledge Guide

public class Unchecked_Demo { public static void main(String args[]) { int num[] = {1, 2, 3,
4}; System.out.println(num[5]); }}
If you compile and execute the above program, you will get the following exception.

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at


Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Errors− These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.

Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Following is a list of most common checked and unchecked Java's Built-in Exceptions.

Exceptions Methods
Following is the list of important methods available in the Throwable class.
Sr.No. Method & Description
public String getMessage()
1 Returns a detailed message about the exception that has occurred.
This message is initialized in the Throwable constructor.
public Throwable getCause()
2 Returns the cause of the exception as represented by a Throwable
object.
public String toString()
3 Returns the name of the class concatenated with the result of
getMessage().
public void printStackTrace()
4 Prints the result of toString() along with the stack trace to System.err,
the error output stream.

www.BankExamsToday.Com Page 174


IT Officer Professional Knowledge Guide

public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The
5 element at index 0 represents the top of the call stack, and the last
element in the array represents the method at the bottom of the call
stack.
public Throwable fillInStackTrace()
6 Fills the stack trace of this Throwable object with the current stack
trace, adding to any previous information in the stack trace.

Catching Exceptions
A method catches an exception using a combination of the try and catchkeywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block
is referred to as protected code, and the syntax for using try/catch looks like the following −

Syntax

try { // Protected code}catch(ExceptionName e1) { // Catch block}


The code which is prone to exceptions is placed in the try block. When an exception occurs, that
exception occurred is handled by catch block associated with it. Every try block should be
immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follow the try is checked. If
the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.

Example

The following is an array declared with 2 elements. Then the code tries to access the
3rd element of the array which throws an exception.
// File Name : ExcepTest.javaimport java.io.*; public class ExcepTest { public static void
main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element
three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Exception thrown :" + e); } System.out.println("Out of the
block"); }}
This will produce the following result −

Output

www.BankExamsToday.Com Page 175


IT Officer Professional Knowledge Guide

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3Out of the block

Multiple Catch Blocks

A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following −

Syntax

try { // Protected code}catch(ExceptionType1 e1) { // Catch block}catch(ExceptionType2 e2)


{ // Catch block}catch(ExceptionType3 e3) { // Catch block}
The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try. If an exception occurs in the protected code, the exception is thrown to the first
catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets
caught there. If not, the exception passes down to the second catch statement. This continues
until the exception either is caught or falls through all catches, in which case the current method
stops execution and the exception is thrown down to the previous method on the call stack.

Example

Here is code segment showing how to use multiple try/catch statements.


try { file = new FileInputStream(fileName); x = (byte) file.read();}catch(IOException i)
{ i.printStackTrace(); return -1;}catch(FileNotFoundException f) // Not valid!
{ f.printStackTrace(); return -1;}

Catching Multiple Type of Exceptions


Since Java 7, you can handle more than one exception using a single catch block, this feature
simplifies the code. Here is how you would do it −
catch (IOException|FileNotFoundException ex) { logger.log(ex); throw ex;

The Throws/Throw Keywords


If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
The following method declares that it throws a RemoteException −

www.BankExamsToday.Com Page 176


IT Officer Professional Knowledge Guide

Example

import java.io.*;public class className { public void deposit(double amount) throws


RemoteException { // Method implementation throw new RemoteException(); } //
Remainder of class definition}
A method can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an InsufficientFundsException −

Example

import java.io.*;public class className { public void withdraw(double amount) throws


RemoteException, InsufficientFundsException { // Method implementation } //
Remainder of class definition}

The Finally Block


The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax −

Syntax

try { // Protected code}catch(ExceptionType1 e1) { // Catch block}catch(ExceptionType2 e2)


{ // Catch block}catch(ExceptionType3 e3) { // Catch block}finally { // The finally block always
executes.}

Example

public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try
{ System.out.println("Access element three :" +
a[3]); }catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception
thrown :" + e); }finally { a[0] = 6; System.out.println("First element value: " +
a[0]); System.out.println("The finally statement is executed"); } }}
This will produce the following result −

www.BankExamsToday.Com Page 177


IT Officer Professional Knowledge Guide

Output

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3First element value: 6The


finally statement is executed
Note the following −
 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.

The try-with-resources
Generally, when we use any resources like streams, connections, etc. we have to close them
explicitly using finally block. In the following program, we are reading data from a file
using FileReader and we are closing it using finally block.

Example

import java.io.File;import java.io.FileReader;import java.io.IOException; public class


ReadData_Demo { public static void main(String args[]) { FileReader fr =
null; try { File file = new File("file.txt"); fr = new FileReader(file); char [] a =
new char[50]; fr.read(a); // reads the content to the array for(char c :
a) System.out.print(c); // prints the characters one by one }catch(IOException e)
{ e.printStackTrace(); }finally { try { fr.close(); }catch(IOException ex)
{ ex.printStackTrace(); } } }}
try-with-resources, also referred as automatic resource management, is a new exception
handling mechanism that was introduced in Java 7, which automatically closes the resources
used within the try catch block.
To use this statement, you simply need to declare the required resources within the parenthesis,
and the created resource will be closed automatically at the end of the block. Following is the
syntax of try-with-resources statement.

Syntax

try(FileReader fr = new FileReader("file path")) { // use the resource }catch() { // body of


catch }}
Following is the program that reads the data in a file using try-with-resources statement.

www.BankExamsToday.Com Page 178


IT Officer Professional Knowledge Guide

Example

import java.io.FileReader;import java.io.IOException; public class Try_withDemo { public static


void main(String args[]) { try(FileReader fr = new FileReader("E://file.txt")) { char [] a =
new char[50]; fr.read(a); // reads the contentto the array for(char c :
a) System.out.print(c); // prints the characters one by one }catch(IOException e)
{ e.printStackTrace(); } }}
Following points are to be kept in mind while working with try-with-resources statement.
 To use a class with try-with-resources statement it should implementAutoCloseableinterface
and the close() method of it gets invoked automatically at runtime.
 You can declare more than one class in try-with-resources statement.
 While you declare multiple classes in the try block of try-with-resources statement these classes
are closed in reverse order.
 Except the declaration of resources within the parenthesis everything is the same as normal
try/catch block of a try block.
 The resource declared in try gets instantiated just before the start of the try-block.
 The resource declared at the try block is implicitly declared as final.
User-defined Exceptions
You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes −
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below −
class MyException extends Exception {}
You just need to extend the predefined Exception class to create your own Exception. These
are considered to be checked exceptions. The followingInsufficientFundsException class is a
user-defined exception that extends the Exception class, making it a checked exception. An
exception class is like any other class, containing useful fields and methods.

Example

// File Name InsufficientFundsException.javaimport java.io.*; public class


InsufficientFundsException extends Exception { private double amount; public
InsufficientFundsException(double amount) { this.amount = amount; } public double
getAmount() { return amount; }}
To demonstrate using our user-defined exception, the following CheckingAccount class contains
a withdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.javaimport java.io.*; public class CheckingAccount { private
double balance; private int number; public CheckingAccount(int number) { this.number =
number; } public void deposit(double amount) { balance += amount; } public void

www.BankExamsToday.Com Page 179


IT Officer Professional Knowledge Guide

withdraw(double amount) throws InsufficientFundsException { if(amount <= balance)


{ balance -= amount; }else { double needs = amount - balance; throw new
InsufficientFundsException(needs); } } public double getBalance() { return
balance; } public int getNumber() { return number; }}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods
of CheckingAccount.
// File Name BankDemo.javapublic class BankDemo { public static void main(String [] args)
{ CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing
$500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing
$100..."); c.withdraw(100.00); System.out.println("\nWithdrawing
$600..."); c.withdraw(600.00); }catch(InsufficientFundsException e)
{ System.out.println("Sorry, but you are short $" +
e.getAmount()); e.printStackTrace(); } }}
Compile all the above three files and run BankDemo. This will produce the following result −

Output

Depositing $500... Withdrawing $100... Withdrawing $600...Sorry, but you are short
$200.0InsufficientFundsException at
CheckingAccount.withdraw(CheckingAccount.java:25) at
BankDemo.main(BankDemo.java:13)

Common Exceptions
In Java, it is possible to define two catergories of Exceptions and Errors.
 JVM Exceptions− These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException.

 Programmatic Exceptions− These exceptions are thrown explicitly by the application or the
API programmers. Examples: IllegalArgumentException, IllegalStateException.

Data Structure and Algorithms - Linked List


A linked list is a sequence of data structures, which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to
another link. Linked list is the second most-used data structure after array. Following are the
important terms to understand the concept of Linked List.

 Link− Each link of a linked list can store a data called an element.
 Next− Each link of a linked list contains a link to the next link called Next.
 LinkedList− A Linked List contains the connection link to the first link called First.

www.BankExamsToday.Com Page 180


IT Officer Professional Knowledge Guide

Linked List Representation


Linked list can be visualized as a chain of nodes, where every node points to the next node.
As per the above illustration, following are the important points to be considered.
 Linked List contains a link element called first.
 Each link carries a data field(s) and a link field called next.
 Each link is linked with its next link using its next link.
 Last link carries a link as null to mark the end of the list.

Types of Linked List


Following are the various types of linked list.
 Simple Linked List− Item navigation is forward only.
 Doubly Linked List− Items can be navigated forward and backward.
 Circular Linked List− Last item contains link of the first element as next and the first element
has a link to the last element as previous.

Basic Operations
Following are the basic operations supported by a list.
 Insertion− Adds an element at the beginning of the list.
 Deletion− Deletes an element at the beginning of the list.
 Display− Displays the complete list.
 Search− Searches an element using the given key.
 Delete− Deletes an element using the given key.

Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with
diagrams here. First, create a node using the same structure and find the location where it has
to be inserted.
Imagine that we are inserting a node B (NewNode), between A (LeftNode) andC (RightNode).
Then point B.next to C −
NewNode.next −> RightNode;
It should look like this −
Now, the next node at the left should point to the new node.
LeftNode.next −> NewNode;
This will put the new node in the middle of the two. The new list should look like this −
Similar steps should be taken if the node is being inserted at the beginning of the list. While
inserting it at the end, the second last node of the list should point to the new node and the new
node will point to NULL.

Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial representation. First,
locate the target node to be removed, by using searching algorithms.

www.BankExamsToday.Com Page 181


IT Officer Professional Knowledge Guide

The left (previous) node of the target node now should point to the next node of the target node

LeftNode.next −> TargetNode.next;
This will remove the link that was pointing to the target node. Now, using the following code, we
will remove what the target node is pointing at.
TargetNode.next −> NULL;
We need to use the deleted node. We can keep that in memory otherwise we can simply
deallocate memory and wipe off the target node completely.

Reverse Operation
This operation is a thorough one. We need to make the last node to be pointed by the head
node and reverse the whole linked list.
First, we traverse to the end of the list. It should be pointing to NULL. Now, we shall make it
point to its previous node −
We have to make sure that the last node is not the lost node. So we'll have some temp node,
which looks like the head node pointing to the last node. Now, we shall make all left side nodes
point to their previous nodes one by one.
Except the node (first node) pointed by the head node, all nodes should point to their
predecessor, making them their new successor. The first node will point to NULL.
We'll make the head node point to the new first node by using the temp node.
The linked list is now reversed.

What is a Stack?

If you've ever put something on top of something else of the same type (e.g. sheets of paper),
you have created a stack! In terms of programming, stacks mean just that.
Since Stacks are practically identical to Queues (with one major difference), this article builds on
the amazing Queues tutorial. I advise you to read it first if you feel a bit confused.

Basic operations of Stacks

The following is a list of operations that can generally be performed on a stack. This of course
will depend on your implementation.
Method names for my implementation are in blue.
Descriptions are in green.

Examples are in red.


push(object) - Adds the object to the top of the stack.
(Putting another sheet of paper on top of the pile)

pop() - Removes the object from the top of the stack and returns
it to the caller.

www.BankExamsToday.Com Page 182


IT Officer Professional Knowledge Guide

(Taking a piece of paper from the top of the pile)

peek() - Returns the object at the top of the stack without


removing it.
(Only reading the sheet of paper at the top of the pile)

Example of using Stacks

The current state of the stack is highlighted in green.


Note: The top of the stack is at the right of the green boxes.
The operation being performed is in blue.
Comments are in green.
We begin with an empty stack.
peek(); would return null.
push(A);
A
A is placed on top of the empty stack.
push(B);
AB
B is placed on top. A is now under B, not on top.
peek();
AB
peek() does not change the stack itself, it only returns
the reference to the object on top, which is B.
pop();
A
B is removed from the stack and returned to the caller.
pop();
A is removed from the stack and returned to the caller.
The stack is now empty.

Queues in Java

The basic concept of queues is one people normally find easy to


understand, because we encounter them on a daily basis. When you go to
the bank, unless you're rich enough to avoid having to wait in line, you will
wait in a queue for the teller. The person at the front of the queue gets
served as soon as a teller becomes free. When a new person enters the
bank, they go to the back of the line (queue). This means that queues work
on a FIFO (first in first out) basis.

www.BankExamsToday.Com Page 183


IT Officer Professional Knowledge Guide

There is more than one way of implementing a queue. The most common
way is to use linked lists (see Linked Lists Tutorial). My implementation
uses linked lists.

The purpose of this article is to help you understand how queues are
implemented. These days, it makes more sense to use the queues from the
Java library, unless you are doing something very custom.

In my opinion, the best way to learn is by going through examples, so I


hope you will find the following example helpful.

Code being executed is in blue.

--------------------

Queue q = new Queue();

An empty queue is created.

Person alice = new Person("Alice");

Person bob = new Person("Bob");

Two objects of type Person are created.

This does not affect the queue yet.

q.enqueue(alice);

Alice has been added to the queue.

System.out.println(((Person)q.peek()).getName());

"Alice" is outputted. The peek() method returns

the object at the front of the queue without affecting

the queue itself.

q.enqueue(bob);

Bob has been added to the queue.

Bob is not at the front of the queue, and so

q.peek() would still return Alice.

www.BankExamsToday.Com Page 184


IT Officer Professional Knowledge Guide

Using the bank example, let's say a teller becomes

free.

q.dequeue();

The dequeue() method will return the 'alice' object

and remove it from the queue. Bob is now the only

one left in the queue.

System.out.println(((Person)q.peek()).getName());

"Bob" is outputted because he is next in the queue.

Fortunately for Bob, another teller becomes free,

so he is dequeued and the queue becomes empty.

q.dequeue();

The dequeue() method will return the 'bob' object

and remove it from the queue.

As mentioned above, my implementation of the queue uses linked lists. For


consistency, I've chosen to use the linked list code from my Linked Lists
Tutorial.Copy the code from there into a file and name it LinkedList.java.

This is my Queue.java:

public class Queue {

private LinkedList list;

// Queue constructor

public Queue()

// Create a new LinkedList.

list = new LinkedList();

public boolean isEmpty()

www.BankExamsToday.Com Page 185


IT Officer Professional Knowledge Guide

// Post: Returns true if the queue is empty. Otherwise, false.

return (list.size() == 0);

public void enqueue(Object item)

// Post: An item is added to the back of the queue.

// Append the item to the end of our linked list.

list.add(item);

public Object dequeue()

// Pre: this.isEmpty() == false

// Post: The item at the front of the queue is returned and

// deleted from the queue. Returns null if precondition

// not met.

// Store a reference to the item at the front of the queue

// so that it does not get garbage collected when we

// remove it from the list.

// Note: list.get(...) returns null if item not found at

// specified index. See postcondition.

Object item = list.get(1);

// Remove the item from the list.

// My implementation of the linked list is based on the

// J2SE API reference. In both, elements start at 1,

// unlike arrays which start at 0.

www.BankExamsToday.Com Page 186


IT Officer Professional Knowledge Guide

list.remove(1);

// Return the item

return item;

public Object peek()

// Pre: this.isEmpty() == false

// Post: The item at the front of the queue is returned and

// deleted from the queue. Returns null if precondition

/ not met.

// This method is very similar to dequeue().

// See Queue.dequeue() for comments.

return list.get(1);

Data Structure and Algorithms – Tree

Tree represents the nodes connected by edges. We will discuss binary tree or binary search
tree specifically.

Binary Tree is a special datastructure used for data storage purposes. A binary tree has a
special condition that each node can have a maximum of two children. A binary tree has the
benefits of both an ordered array and a linked list as search is as quick as in a sorted array and
insertion or deletion operation are as fast as in linked list.

Important Terms:

Following are the important terms with respect to tree.

www.BankExamsToday.Com Page 187


IT Officer Professional Knowledge Guide

Path− Path refers to the sequence of nodes along the edges of a tree.

Root− The node at the top of the tree is called root. There is only one root per tree and one
path from the root node to any node.

Parent− Any node except the root node has one edge upward to a node called parent.

Child− The node below a given node connected by its edge downward is called its child node.

Leaf− The node which does not have any child node is called the leaf node.

Subtree− Subtree represents the descendants of a node.

Visiting− Visiting refers to checking the value of a node when control is on the node.

Traversing− Traversing means passing through nodes in a specific order.

Levels− Level of a node represents the generation of a node. If the root node is at level 0, then
its next child node is at level 1, its grandchild is at level 2, and so on.

keys− Key represents a value of a node based on which a search operation is to be carried out
for a node.

Binary Search Tree Representation

Binary Search tree exhibits a special behavior. A node's left child must have a value less than
its parent's value and the node's right child must have a value greater than its parent value.

We're going to implement tree using node object and connecting them through references.

Tree Node

The code to write a tree node would be similar to what is given below. It has a data part and
references to its left and right child nodes.

struct node { int data; struct node *leftChild; struct node *rightChild;};

In a tree, all nodes share common construct.

BST Basic Operations

The basic operations that can be performed on a binary search tree data structure, are the
following –

Insert− Inserts an element in a tree/create a tree.

Search− Searches an element in a tree.

www.BankExamsToday.Com Page 188


IT Officer Professional Knowledge Guide

Preorder Traversal− Traverses a tree in a pre-order manner.

Inorder Traversal− Traverses a tree in an in-order manner.

Postorder Traversal− Traverses a tree in a post-order manner.

We shall learn creating (inserting into) a tree structure and searching a data item in a tree in this
chapter. We shall learn about tree traversing methods in the coming chapter.

Insert Operation

The very first insertion creates the tree. Afterwards, whenever an element is to be inserted, first
locate its proper location. Start searching from the root node, then if the data is less than the key
value, search for the empty location in the left subtree and insert the data. Otherwise, search for
the empty location in the right subtree and insert the data.

Algorithm

If root is NULL then create root nodereturn If root exists then compare the data with
node.data while until insertion position is located If data is greater than
node.data goto right subtree else goto left subtree endwhile insert
data end If

Implementation

The implementation of insert function should look like this −

void insert(int data) { struct node *tempNode = (struct node*) malloc(sizeof(struct


node)); struct node *current; struct node *parent; tempNode->data = data; tempNode-
>leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty, create root node if(root
== NULL) { root = tempNode; } else { current = root; parent = NULL; while(1)
{ parent = current; //go to left of the tree if(data < parent->data)
{ current = current->leftChild; //insert to the left if(current
== NULL) { parent->leftChild =
tempNode; return; } } //go to right of the
tree else { current = current->rightChild; //insert to the right if(current ==
NULL) { parent->rightChild = tempNode; return; } } } }}

Search Operation

Whenever an element is to be searched, start searching from the root node, then if the data is
less than the key value, search for the element in the left subtree. Otherwise, search for the
element in the right subtree. Follow the same algorithm for each node.

Algorithm

www.BankExamsToday.Com Page 189


IT Officer Professional Knowledge Guide

If root.data is equal to search.data return rootelse while data not found If data is greater
than node.data goto right subtree else goto left subtree If data
found return node endwhile return data not found end if

The implementation of this algorithm should look like this.

struct node* search(int data) { struct node *current = root; printf("Visiting elements:
"); while(current->data != data) { if(current != NULL) printf("%d ",current-
>data); //go to left tree if(current->data > data) { current = current-
>leftChild; } //else go to right tree else { current = current-
>rightChild; } //not found if(current == NULL) { return NULL; } return
current; } }

Heap Data Structures


Heap is a special case of balanced binary tree data structure where the root-node key is
compared with its children and arranged accordingly. If α has child node β then –

key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap. Based on
this criteria, a heap can be of two types –

For Input → 35 33 42 10 14 19 27 44 26 31
Min-Heap − Where the value of the root node is less than or equal to either of its children.

Max-Heap − Where the value of the root node is greater than or equal to either of its children.
Both trees are constructed using the same input and order of arrival.

Max Heap Construction Algorithm


We shall use the same example to demonstrate how a Max Heap is created. The procedure to
create Min Heap is similar but we go for min values instead of max values.
We are going to derive an algorithm for max heap by inserting one element at a time. At any
point of time, heap must maintain its property. While insertion, we also assume that we are
inserting a node in an already heapified tree.

Step 1 − Create a new node at the end of heap.Step 2 − Assign new value to the node.Step
3 − Compare the value of this child node with its parent.Step 4 − If value of parent is less than
child, then swap them.Step 5 − Repeat step 3 & 4 until Heap property holds.

Note − In Min Heap construction algorithm, we expect the value of the parent node to be less
than that of the child node.
Let's understand Max Heap construction by an animated illustration. We consider the same
input sample that we used earlier.

www.BankExamsToday.Com Page 190


IT Officer Professional Knowledge Guide

Max Heap Deletion Algorithm


Let us derive an algorithm to delete from max heap. Deletion in Max (or Min) Heap always
happens at the root to remove the Maximum (or minimum) value.

Step 1 − Remove root node.Step 2 − Move the last element of last level to root.Step 3 −
Compare the value of this child node with its parent.Step 4 − If value of parent is less than child,
then swap them.Step 5 − Repeat step 3 & 4 until Heap property holds.

Hashing, Hash Data Structure and Hash Table

Hashing is the process of mapping large amount of data item to a smaller table with the help
of a hashing function. The essence of hashing is to facilitate the next level searching method
when compared with the linear or binary search. The advantage of this searching method is its
efficiency to hand vast amount of data items in a given collection (i.e. collection size).

Due to this hashing process, the result is a Hash data structure that can store or retrieve data
items in an average time disregard to the collection size.

Hash Table is the result of storing the hash data structure in a smaller table which incorporates
the hash function within itself. The Hash Function primarily is responsible to map between the
original data item and the smaller table itself. Here the mapping takes place with the help of an
output integer in a consistent range produced when a given data item (any data type) is
provided for storage and this output integer range determines the location in the smaller table
for the data item. In terms of implementation, the hash table is constructed with the help of an
array and the indices of this array are associated to the output integer range.

Hash Table Example :


Here, we construct a hash table for storing and retrieving data related to the citizens of a county
and the social-security number of citizens are used as the indices of the array implementation
(i.e. key). Let's assume that the table size is 12, therefore the hash function would be Value
modulus of 12.

Hence, the Hash Function would equate to:


(sum of numeric values of the characters in the data item) %12
Note! % is the modulus operator

Let us consider the following social-security numbers and produce a hashcode:


120388113D => 1+2+0+3+8+8+1+1+3+13=40
Hence, (40)%12 => Hashcode=4

310181312E => 3+1+0+1+8+1+3+1+2+14=34


Hence, (34)%12 => Hashcode=10

041176438A => 0+4+1+1+7+6+4+3+8+10=44

www.BankExamsToday.Com Page 191


IT Officer Professional Knowledge Guide

Hence, (44)%12 => Hashcode=8

Therefore, the Hashtable content would be as follows:


-----------------------------------------------------
0:empty
1:empty
2:empty
3:empty
4:occupied Name:Drew Smith SSN:120388113D
5:empty
6:empty
7:empty
8:occupied Name:Andy Conn SSN:041176438A
9:empty
10:occupied Name:Igor Barton SSN:310181312E
11:empty

Data Structure - Graph Data Structure


A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed as vertices,
and the links that connect the vertices are callededges.

Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of edges,
connecting the pairs of vertices. Take a look at the following graph −
In the above graph,
V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}

Graph Data Structure


Mathematical graphs can be represented in data structure. We can represent a graph using an
array of vertices and a two-dimensional array of edges. Before we proceed further, let's
familiarize ourselves with some important terms –

 Vertex− Each node of the graph is represented as a vertex. In the following example, the
labeled circle represents vertices. Thus, A to G are vertices. We can represent them using an
array as shown in the following image. Here A can be identified by index 0. B can be identified
using index 1 and so on.

 Edge− Edge represents a path between two vertices or a line between two vertices. In the
following example, the lines from A to B, B to C, and so on represents edges. We can use a
two-dimensional array to represent an array as shown in the following image. Here AB can be
represented as 1 at row 0, column 1, BC as 1 at row 1, column 2 and so on, keeping other
combinations as 0.

www.BankExamsToday.Com Page 192


IT Officer Professional Knowledge Guide

 Adjacency− Two node or vertices are adjacent if they are connected to each other through an
edge. In the following example, B is adjacent to A, C is adjacent to B, and so on.
 Path− Path represents a sequence of edges between the two vertices. In the following example,
ABCD represents a path from A to D.

Basic Operations
Following are basic primary operations of a Graph –
 Add Vertex− Adds a vertex to the graph.
 Add Edge− Adds an edge between the two vertices of the graph.
 Display Vertex− Displays a vertex of the graph.

www.BankExamsToday.Com Page 193


IT Officer Professional Knowledge Guide

Chapter : Data Structures

Data Structure and Algorithms Tutorial


Data Structures are the programmatic way of storing data so that data can be used efficiently.
Almost every enterprise application uses various types of data structures in one or the other
way. This tutorial will give you a great understanding on Data Structures needed to understand
the complexity of enterprise level applications and need of algorithms, and data structures.

Audience
This tutorial is designed for Computer Science graduates as well as Software Professionals who
are willing to learn data structures and algorithm programming in simple and easy steps.
After completing this tutorial you will be at intermediate level of expertise from where you can
take yourself to higher level of expertise.

Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of C programming
language, text editor, and execution of programs, etc.

Compile and Execute C Online


For most of the examples given in this tutorial you will find Try it option, so just make use of this
option to execute your programs on the spot and enjoy your learning.
Try the following example using the Try it option available at the top right corner of the following
sample code box −
#include <stdio.h>
int main(){
/* My first program in C */
printf("Hello, World! \n");
return 0;
}

Array Matrix :
In general, array is a built-in data structure that holds a set of elements of the same type.
Arrays are useful and indispensable in programming.

Here are the characteristics of arrays in Java:


 Fixed length: Once an array is created, we cannot change its size. So consider using arrays
when the numbers of elements are known and fixed. Otherwise, you should consider using
another dynamic container such as ArrayList.
 Fast access: It‟s very fast to access any elements in an array (by index of the elements) in
constant time: accessing the 1st element takes same time as accessing the last element. So
performance is another factor when choosing arrays.
 An array can hold primitives or objects.

www.BankExamsToday.Com Page 194


IT Officer Professional Knowledge Guide

 An array of primitives stores values of the primitives.


 An array of objects stores only the references to the objects.
 In Java, the position of an element is specified by index which is zero-based. That means the
first element is at index 0, the second element at index 1, and so on.
 An array itself is actually an object.

1. Arrays declarations and initialization


Declare first and initialize later:
1 int [] numbers = new int[10];

This declares an array object to hold 10 integer numbers (primitive array).


When declaring an array of primitive type, remember these rules:

 All numbers are initialized to zeroes by default. That means the above array numbers contain 10
numbers which are all zeroes, even we haven‟t initialized the array yet.
 Boolean elements are initialized to false by default.
Then we initialize values for each element of the array like this:
1 numbers[0] = 10;

2 numbers[1] = 500;

3 numbers[2] = 1000;

4 ...

The following statement declares an array of String objects:


1 String[] names = new String[5];

This array holds 5 String objects. And by default, all elements of Object type are initialized to
null.

NOTE: In Java, you can place the brackets [] either after the type or after the variable name.
Hence these declarations are both correct:
1 String[] names = new String[5];

2 String titles[] = new String[10];

However, it‟s recommended to use the [] after the type for readability: You can easily realize this
is an array of Strings, or that is an array of integer numbers.
You can also declare and initialize elements of an array in one statement. For example:
1 int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

This creates an array with 10 integer numbers which are initialized up declaration. This is a
handy shortcut for declaring arrays whose elements are already known at compile time.
This statement declares and initializes an array of Strings:

www.BankExamsToday.Com Page 195


IT Officer Professional Knowledge Guide

1 String[] columnNames = {“No”, “Name”, “Email”, “Address”};

2. Multi-dimensional arrays
We can create an array of arrays (2-dimension array). For instance:
1 float[][] matrix = new float[5][3];

This creates a 2D array with is equivalent to a matrix of 5 rows and 3 columns.


Another example:
1 String[][] sampleData = {

2 {"a", "b", "c", "d"},

3 {"e", "f", "g", "h"},

4 {"i", "j", "k", "l"},

5 {"m", "n", "o", "p"},

6 };

This creates a 4x4 array and initializes all the elements.


We can also create a 3D array, 4D array, etc using the same technique.

3. Arrays Manipulation
We access elements in the array by index (remember 0-based):
1 String firstColumn = columnNames[0];

This statement takes value of the first element in the String array columnNamesand assigns it to
the variable firstColumn.

The following statement illustrates accessing an element in a 2D array:


1 String[] firstRow = sampleData[0];

This gets the first element in the sampleData array, which returns an array.

The following statement takes the element at 3rd row and 2nd column in the above 2D array:
1 String letter = sampleData[4][3];

And these examples show how to assign values to elements in arrays:


1 columnNames[2] = “Phone;

2 columnNames[4] = new String(“City”);

3 numbers[4] = 1024;

4 sampleData[4][2] = “xyz”;

www.BankExamsToday.Com Page 196


IT Officer Professional Knowledge Guide

A common operation is iterating an array using a loop statement like the for statement. The
following example uses the forloop to iterate over all elements in an array of integer numbers,
and prints value of each element:

1 int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

3 for (int i = 0; i < numbers.length; i++) {

4 System.out.println(numbers[i]);

5 }

For arrays of objects you can use the for each syntax to iterate. For example:
1 String[] nameList = {"Tom", "Mary", "Peter", "John", "Adam", "Justin"};

3 for (String aName : nameList) {

4 System.out.println(aName);

5 }

Besides the fundamental operations like getting and setting, Java provides various functions to
manipulate arrays in theArrays class.
The Arrays is a utility class which can be found in the java.util package. Here are some
noteworthy methods it provides:
 asList(): returns a fixed-size list backed by an array.
 binarySearch(): searches for a specific value in an array. Returns the index of the element if
found, or -1 if not found. Note that the array must be sorted first.
 copyOf(): copies a portion of the specified array to a new one.
 copyOfRange(): copies a specified range of an array to a new one.
 equals(): compares two arrays to determine if they are equal or not.
 fill(): fills same values to all or some elements in an array.
 sort(): sorts an array into ascending order.
 And other methods you can find in the Arrays class Javadoc.
In addition, the System.arraycopy() is an efficient method for copying elements from one array
to another. Remember using this method instead of writing your own procedure because this
method is very efficient.
So far I have walked you through a tour of arrays in Java. Here‟s the summary for today:
 An array is an object.
 Elements in an array are accessed by index (0-based).
 Advantage of array: very fast access to elements.
 Disadvantage of array: fixed length, not appropriate if a dynamic container is required.

www.BankExamsToday.Com Page 197


IT Officer Professional Knowledge Guide

 The java.util.Arrays class provides useful utility methods for working with arrays such as filling,
searching and sorting.
 The System.arraycopy() method provides an efficient mechanism for copying elements from
one array to another.

Algorithms Basics
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a
certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language.
From the data structure point of view, following are some important categories of algorithms –

 Search− Algorithm to search an item in a data structure.


 Sort− Algorithm to sort items in a certain order.
 Insert− Algorithm to insert item in a data structure.
 Update− Algorithm to update an existing item in a data structure.
 Delete− Algorithm to delete an existing item from a data structure.

Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have the following
characteristics −
 Unambiguous− Algorithm should be clear and unambiguous. Each of its steps (or phases), and
their inputs/outputs should be clear and must lead to only one meaning.
 Input− An algorithm should have 0 or more well-defined inputs.
 Output− An algorithm should have 1 or more well-defined outputs, and should match the
desired output.
 Finiteness− Algorithms must terminate after a finite number of steps.
 Feasibility− Should be feasible with the available resources.
 Independent− An algorithm should have step-by-step directions, which should be independent
of any programming code.

How to Write an Algorithm?


There are no well-defined standards for writing algorithms. Rather, it is problem and resource
dependent. Algorithms are never written to support a particular programming code.
As we know that all programming languages share basic code constructs like loops (do, for,
while), flow-control (if-else), etc. These common constructs can be used to write an algorithm.
We write algorithms in a step-by-step manner, but it is not always the case. Algorithm writing is
a process and is executed after the problem domain is well-defined. That is, we should know the
problem domain, for which we are designing a solution.

Example

www.BankExamsToday.Com Page 198


IT Officer Professional Knowledge Guide

Let's try to learn algorithm-writing by using an example.

Problem − Design an algorithm to add two numbers and display the result.

step 1 − STARTstep 2 − declare three integers a, b & cstep 3 − define values of a & bstep 4 −
add values of a & bstep 5 − store output of step 4 to cstep 6 − print cstep 7 − STOP
Algorithms tell the programmers how to code the program. Alternatively, the algorithm can be
written as –

step 1 − START ADDstep 2 − get values of a & bstep 3 − c ← a + bstep 4 − display cstep 5 −
STOP
In design and analysis of algorithms, usually the second method is used to describe an
algorithm. It makes it easy for the analyst to analyze the algorithm ignoring all unwanted
definitions. He can observe what operations are being used and how the process is flowing.

Writing step numbers, is optional.


We design an algorithm to get a solution of a given problem. A problem can be solved in more
than one ways.
Hence, many solution algorithms can be derived for a given problem. The next step is to
analyze those proposed solution algorithms and implement the best suitable solution.

Algorithm Analysis
Efficiency of an algorithm can be analyzed at two different stages, before implementation and
after implementation. They are the following –

 A Priori Analysis− This is a theoretical analysis of an algorithm. Efficiency of an algorithm is


measured by assuming that all other factors, for example, processor speed, are constant and
have no effect on the implementation.
 A Posterior Analysis− This is an empirical analysis of an algorithm. The selected algorithm is
implemented using programming language. This is then executed on target computer machine.
In this analysis, actual statistics like running time and space required, are collected.
We shall learn about a priori algorithm analysis. Algorithm analysis deals with the execution or
running time of various operations involved. The running time of an operation can be defined as
the number of computer instructions executed per operation.
Algorithm Complexity
Suppose X is an algorithm and n is the size of input data, the time and space used by the
algorithm X are the two main factors, which decide the efficiency of X.
 Time Factor− Time is measured by counting the number of key operations such as
comparisons in the sorting algorithm.
 Space Factor− Space is measured by counting the maximum memory space required by the
algorithm.
The complexity of an algorithm f(n) gives the running time and/or the storage space required by
the algorithm in terms of n as the size of input data.

www.BankExamsToday.Com Page 199


IT Officer Professional Knowledge Guide

Space Complexity
Space complexity of an algorithm represents the amount of memory space required by the
algorithm in its life cycle. The space required by an algorithm is equal to the sum of the following
two components –
 A fixed part that is a space required to store certain data and variables, that are independent of
the size of the problem. For example, simple variables and constants used, program size, etc.
 A variable part is a space required by variables, whose size depends on the size of the problem.
For example, dynamic memory allocation, recursion stack space, etc.

Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I)
is the variable part of the algorithm, which depends on instance characteristic I. Following is a
simple example that tries to explain the concept –

Algorithm: SUM(A, B)Step 1 - STARTStep 2 - C ← A + B + 10Step 3 - Stop


Here we have three variables A, B, and C and one constant. Hence S(P) = 1 + 3. Now, space
depends on data types of given variables and constant types and it will be multiplied
accordingly.

Time Complexity
Time complexity of an algorithm represents the amount of time required by the algorithm to run
to completion. Time requirements can be defined as a numerical function T(n), where T(n) can
be measured as the number of steps, provided each step consumes constant time.

Data Structure - Sorting Techniques


Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to
arrange data in a particular order. Most common orders are in numerical or lexicographical
order.
The importance of sorting lies in the fact that data searching can be optimized to a very high
level, if data is stored in a sorted manner. Sorting is also used to represent data in more
readable formats. Following are some of the examples of sorting in real-life scenarios –

 Telephone Directory− The telephone directory stores the telephone numbers of people sorted
by their names, so that the names can be searched easily.
 Dictionary− The dictionary stores words in an alphabetical order so that searching of any word
becomes easy.

In-place Sorting and Not-in-place Sorting


Sorting algorithms may require some extra space for comparison and temporary storage of few
data elements. These algorithms do not require any extra space and sorting is said to happen
in-place, or for example, within the array itself. This is called in-place sorting. Bubble sort is an
example of in-place sorting.

www.BankExamsToday.Com Page 200


IT Officer Professional Knowledge Guide

However, in some sorting algorithms, the program requires space which is more than or equal
to the elements being sorted. Sorting which uses equal or more space is called not-in-place
sorting. Merge-sort is an example of not-in-place sorting.

Stable and Not Stable Sorting


If a sorting algorithm, after sorting the contents, does not change the sequence of similar
content in which they appear, it is called stable sorting.

If a sorting algorithm, after sorting the contents, changes the sequence of similar content in
which they appear, it is called unstable sorting.

Stability of an algorithm matters when we wish to maintain the sequence of original elements,
like in a tuple for example.

Adaptive and Non-Adaptive Sorting Algorithm


A sorting algorithm is said to be adaptive, if it takes advantage of already 'sorted' elements in
the list that is to be sorted. That is, while sorting if the source list has some element already
sorted, adaptive algorithms will take this into account and will try not to re-order them.
A non-adaptive algorithm is one which does not take into account the elements which are
already sorted. They try to force every single element to be re-ordered to confirm their
sortedness.

Important Terms
Some terms are generally coined while discussing sorting techniques, here is a brief
introduction to them –

Increasing Order

A sequence of values is said to be in increasing order, if the successive element is greater


than the previous one. For example, 1, 3, 4, 6, 8, 9 are in increasing order, as every next
element is greater than the previous element.

Decreasing Order

A sequence of values is said to be in decreasing order, if the successive element is less than
the current one. For example, 9, 8, 6, 4, 3, 1 are in decreasing order, as every next element is
less than the previous element.

Non-Increasing Order

A sequence of values is said to be in non-increasing order, if the successive element is less


than or equal to its previous element in the sequence. This order occurs when the sequence
contains duplicate values. For example, 9, 8, 6, 3, 3, 1 are in non-increasing order, as every
next element is less than or equal to (in case of 3) but not greater than any previous element.

www.BankExamsToday.Com Page 201


IT Officer Professional Knowledge Guide

Non-Decreasing Order

A sequence of values is said to be in non-decreasing order, if the successive element is


greater than or equal to its previous element in the sequence. This order occurs when the
sequence contains duplicate values. For example, 1, 3, 3, 6, 8, 9 are in non-decreasing order,
as every next element is greater than or equal to (in case of 3) but not less than the previous
one.

www.BankExamsToday.Com Page 202

You might also like