1
material prepared by: MUKESH BOHRA
MAIL UR FEEDBACK AT: [email protected] Follow me on FB : http://www.facebook.com/mukesh.sirji4u
Twitter Handle: http://twitter.com/mbthebigboss
BOOLEAN ALGEBRA Boolean Algebra is a set of rules, laws and theorems by which logical operations can be
mathematically expressed. This algebra was first introduced by George Boole, an English
mathematician.
Boolean algebra deals with boolean variables (characters allowed A-Z, a-z), the operators
. (AND) , + (OR), and (NOT) and the symbols ( ) and =.
Basic Theorems/Properties of Boolean Algebra Theorem/Law/Axioms Over (.) Over (+) 1. Properties of 0 x.0 = 0 x+0 = x 2. Properties of 1 x.1 = x x+1 = 1 3. Indempotence Law (Identity Law) x.x = x x+x = x 4. Complementarity Law x.x = 0 x+x = 1 5. Commutative Law x.y = y.x x+y = y+x 6. Associative Law x.(y.z) = (x.y).z x+(y+z) = (x+y)+z 7. Distributive Law x+(y.z) = (x+y).(x+z) x.(y+z) = xy+xz 8. Absorption Law (Redundance Law) x(x+y) = x x+xy = x 9. De-Morgans Law (x.y)' = x+y (x+y) = x.y 10. Involution Law (Negation Law) (x) = x
Principle of Duality: It states that starting with a boolean relation; another boolean relation can be derived by:
1) Changing each OR (+) sign to an AND (.) sign. 2) Changing each AND (.) to an OR (+) sign. 3) Replacing each 0 by1 & vice-versa.
e.g. The Dual of an expression x+xy = x is x.(x+y) = x
Tautology Fallacy If the result of a boolean expression is
always TRUE or 1, it is called a tautology.
If the result of a boolean expression is
always FALSE or 0, it is called Fallacy.
-----------------------------------------------------------------------------------------------------------------------------
2
LOGIC GATES
Logic gates are small electronic circuits that work on digital signals. Basically logic gates
are of two types:
Basic Gates Derived Gates AND gate NAND gate OR gate NOR gate
NOT gate X-OR gate
X-NOR gate
BASIC GATES:
1. AND gate
Operation : logical multiplication
Symbol : . or ^
Graphical symbol :
A
i/p lines Y=A.B
B o/p line
Truth Table:
INPUT OUTPUT
A B Y= A.B
0 0 0
0 1 0
1 0 0
1 1 1
It is concluded from the above truth table that; the output of an AND gate is TRUE
(i.e. 1) only when both the inputs are TRUE, and in all other cases it is always FALSE.
2. OR gate
Operation : logical addition
Symbol : + or v
Graphical symbol :
A i/p lines Y = A + B
B o/p line
3
Truth Table:
INPUT OUTPUT
A B Y= A+B
0 0 0
0 1 1
1 0 1
1 1 1
It is concluded from the above truth table that; the output of an OR gate is FALSE
(i.e. 0) only when both the inputs are FALSE, and in all other cases it is always TRUE.
3. NOT gate ( Inverter)
Operation : Compliment
Symbol : or
Graphical symbol :
i/p line A Y = A (or A ) o/p line
Truth Table:
Input output
A Y = A
0 1
1 0
It is concluded from the above truth table that; the NOT gate simply inverts the input.
DERIVED GATES: ( obtained by combining two or more basic gates)
1. NAND gate: [compliment of AND gate]
It is obtained by complimenting the output of AND gate.
A A.B
Y = A.B
B
4
Graphical symbol:
A
i/p lines Y=A.B
B o/p line
Truth Table:
INPUT
A.B
OUTPUT
A B Y= A.B
0 0 0 1
0 1 0 1
1 0 0 1
1 1 1 0
It is concluded from the above truth table that; the output of an NAND gate is FALSE
(i.e. 0) only when both the inputs are TRUE, and in all other cases it is always TRUE.
2. NOR gate: [compliment of OR gate]
It is obtained by complimenting the output of OR gate.
A A+B
Y = A + B
B
Graphical symbol:
A
i/p lines Y = A + B
B o/p line
INPUT
A+B
OUTPUT
A B Y= A+B
0 0 0 1
0 1 1 0
1 0 1 0
1 1 1 0
It is concluded from the above truth table that; the output of an NOR gate is TRUE
(i.e. 1) only when both the inputs are FALSE, and in all other cases it is always FALSE.
5
3. X-OR gate:
It is a special case in OR gate. It is obtained as:
A
A AB
i/p
Y=A + B
o/p
B AB
B
Graphical symbol:
A
i/p lines Y = A + B = AB + AB
B o/p line
Truth Table:
INPUT
A
B
AB
AB
OUTPUT
A B Y = A + B
= AB + AB
0 0 1 1 0 0 0
0 1 1 0 1 0 1
1 0 0 1 0 1 1
1 1 0 0 0 0 0
It is concluded from the above truth table that; the output of an X-OR gate is FALSE
(i.e. 0) when both the inputs are SAME, and in all other cases it is always TRUE.
6
4. X-NOR gate:
It is obtained by complementing the output of X-OR gate.
A
A AB
i/p A + B Y=A . B
o/p
B AB
B
Graphical symbol:
A i/p lines Y = A . B = AB + AB
B o/p line
Truth Table:
INPUT
A
B
AB
AB
AB + AB
OUTPUT
A B Y = A . B
= AB + AB
0 0 1 1 0 0 0 1
0 1 1 0 1 0 1 0
1 0 0 1 0 1 1 0
1 1 0 0 0 0 0 1
It is concluded from the above truth table that; the output of an X-NOR gate is TRUE
(i.e. 1) when both the inputs are SAME, and in all other cases it is always FALSE.
7
Universal gates: [ NAND & NOR ] NAND and NOR gates are known as universal gates because any other gate / any logic
circuit can be constructed using only NAND as well as only NOR.
i. Construction of basic gates using NAND gate:
1) NOT gate using NAND
A Y = A
2) AND gate using NAND
A A.B Y = A.B = A.B
B
3) OR gate using NAND
A
A
Y = A. B = A + B = A + B
B
B
8
ii. Construction of basic gates using NOR gate:
1) NOT gate using NOR
Y = A
A
2) OR gate using NOR
A A+B Y = A+B = A+B
B
3) AND gate using NOR
A
A
Y = A + B = A . B = A . B
B
B
------------------------------------------------------------------------------------------------------
9
Minimizing A Boolean Expression A given boolean expression can be minimized or reduced to a simpler form before
implementing it into a circuit. By doing so, we can remove complexities of a circuit to a
larger extent.
There are two methods of minimizing a boolean expression:
Algebraic method [using laws of boolean algebra]
Map method [using K-map]
K- MAP ( Karnaugh Map) K-map is a graphical arrangement of a truth-table in the form of a grid, which provides a
simplest & systematic way of minimizing a boolean expression.
Key Terms: Literal A single variable or its compliment. Gray Code A binary code in which each successive number differs only in one
place. Canonical Form Standard SOP or Standard POS expressions where all variables/literals
are present in each term of the expression.
Maxterm SUM term containing sum of all the literals, with or without bar Minterm PRODUCT term containing product of all the literals, with or without
bar Points to remember while drawing a K-map:
1) In SOP; each minterm is marked as binary 1 in the corresponding cell of the map. In POS; each maxterm is marked as binary 0 in the corresponding cell of the map.
2) While grouping the cells, check firstly for large groups. i.e. check first for a group of 16cells, then 8cells, then 4cells, then 2cells and lastly for 1cell. At each step
dont forget to roll/fold the map. 3) Redundant groups should not be taken. 4) For each group, take the common row-variables and the column-variables and
multiply them to get the simplified minterm (or add them to get the simplified
maxterm).
[In SOP: 0-complemented; 1-uncomplemeted]
[In POS: 0-uncomplemented; 1-complemeted]
Repeat the procedure for all the groups.
5) Finally, add all the minterms obtained (or multiply all the maxterms obtained) to get the final minimized expression.
10
EXAMPLE: Reduce the following Boolean Expression using K-map:
F(A, B, C, D) = (0, 1, 2, 4, 5, 6, 8, 10) [CBSE 2011]
SOL:
No. of variables = 4
Therefore, no of cells in the map= 24 = 16
So lets draw the K-map with 16 cells
g1 g2
CD
AB 00 01 11 10
00
01
11
10
g3
For group g1: its a quad containing cells (m0, m1, m4, m5)
A=0 i.e A
C=0 i.e. C
Combining both the literals, well get the minterm
AC
1
m0
1
m1
m3
1
m2
1
m4
1
m5
m7
1
m6
m12
m13
m15
m14
1
m8
m9
m11
1
m10
11
For group g2: its a quad containing cells (m0, m2, m4, m6)
A=0 i.e A
AD
D=0 i.e D
For group g3: its a quad (obtained on map folding) containing cells (m0, m2, m8, m10)
B=0 i.e B
BD
D=0 i.e D
Now, Combining the minterms obtained above; well get the reduced boolean exp. as:
F(A, B, C, D) = AC + AD + BD
-------------------------------------------------------------------------------------------------------------
Other Activities: Practice the following:
1) Minimization Problems using K-maps & algebraically also. 2) Realization of a given Boolean expression using:
Any Logic NAND NOR
gate(s) gate only gate only
3) To draw out the output from a logic circuit and vice-versa. 4) Writing SOP or POS forms from truth tables. 5) SOP to POS conversion and vice-versa. 6) Proving the laws or a given expression
Algebraically
Using truthtables.
-------------------------------------------------------------------------------------------------------------
12
COMMUNICATIONS
Transmission
SWITCHING TECHNIQUES
Circuit Switching Packet Switching Message Switching
first complete physical msg segmented into smaller packets whole messages are
connection is setup & then and then transmitted into the n/w. transmitted through
the msg is passed. At receving end, packets are the n/w.
(mostly used for voice reassembled to get back the orig. msg. communication)
TRANSMISSION MEDIA Guided Media Unguided Media
(Wired) (Wireless)
Include Cables Include waves through
air, water or vacuum
Twisted-Pair Cable (@1mbps upto 100m) Microwaves (upto 50km)
Coaxial Cable (@10mbps upto several-100m) Radio waves (city,states etc)
Fiber-Optic Cables (v. high data transfer rates) Infrared (v. short distance)
---------------------------------------------------------------------------------------
1. Twisted pair cable: It consists of two identical 1 mm thick copper wires insulated and twisted together. The twisted pair cables are twisted in order to reduce crosstalk and electromagnetic induction. Advantages:
(i) It is easy to install and maintain.
(ii) It is very inexpensive
13
Disadvantages: (i) It is incapable to carry a signal over long distances without the use of repeaters.
(ii) Due to low bandwidth, these are unsuitable for broadband applications.
2. Co-axial Cables: It consists of a solid wire core surrounded by one or more foil or braided wire shields, each separated from the other by some kind of plastic insulator. It is mostly used in the TV-cable wires.
Advantages: (i) Data transmission rate is better than twisted pair cables.
(ii) It provides a cheap means of transporting multi-channel television signals around metropolitan areas. Disadvantages: (i) Expensive than twisted pair cables.
(ii) Difficult to manage and reconfigure.
3. Optical fiber: An optical fiber consists of thin glass fibers that can carry information in the form of visible light.
Advantages:
(i) Transmit data over long distance with high security.
(ii) Data transmission speed is high
(iii) Provide better noise immunity (iv) Bandwidth is up to 10 Gbps. Disadvantages: (i) Expensive as compared to other guided media.
(ii) Needs special care while installation.
4. Infrared: The infrared light transmits data through the air and can propagate throughout a room, but will not penetrate walls. It is a secure medium of signal
transmission. The infrared transmission has become common in TV remotes, automotive garage doors, wireless speakers etc.
5. Radio Wave: Radio Wave an electromagnetic wave with a wavelength between 0.5 cm and 30,000 m. The transmission making use of radio frequencies is termed as radio-wave transmission
Advantages: (i) Radio wave transmission offers mobility.
(ii) It is cheaper than laying cables and fibers. (iii) It offers ease of communication over difficult terrain. Disadvantages:
(i) Radio wave communication is insecure communication.
(ii) Radio wave propagation is susceptible to weather effects like rains, thunder storms etc.
14
6. Microwave Wave: The Microwave transmission is a line of sight transmission. Microwave signals travel at a higher frequency than radio waves and are popularly used for transmitting data over long distances.
Advantages:
(i) It is cheaper than laying cable or fiber.
(ii) It has the ability to communicate over oceans. Disadvantages: (i) Microwave communication is an insecure communication.
(ii) Signals from antenna may split up and transmitted in different way to different antenna which leads to reduce to signal strength.
(iii) Microwave propagation is susceptible to weather effects like rains, thunder storms etc.
(iv) Bandwidth allocation is extremely limited in case of microwaves.
7. Satellite link: The satellite transmission is also a kind of line of sight transmission that is used to transmit signals throughout the world.
Advantages:
(i) Area covered is quite large.
(ii) No line of sight restrictions such as natural mountains, tall building, towers etc.
(iii) Earth station which receives the signals can be fixed position or relatively mobile. Disadvantages:
(i) Very expensive as compared to other transmission mediums.
(ii) Installation is extremely complex.
(iii) Signals sent to the stations can be tampered by external interference.
PROTOCOLS
A protocol is a set of rules that govern data communications. It represents an agreement
between the communicating devices. Without a protocol, two devices may be connected but not
communicating.
Key elements of a protocol:
Syntax: concerns the format or structure of data blocks.
Semantics: refers to the meaning of each section of bits.
Timing: refers to two characteristics: when data should be sent and how fast they can be sent.
15
NETWORK DEVICES MODEM (MOdulator-DEModulator) a device that encodes data for transmission over a
particular medium, such as telephone lines, coaxial cables, fiber optics, or
microwaves. A modem converts digital data to analog signals and vice versa. The modem is inserted between the (digital) computer and the (analog) telephone system. Modem comes in two varieties: Internal & External.
RJ-45 CONNECTOR Registered jack-45 is an 8-wire connector, which is commonly used to connect computers on LANs-especially Ethernets.
ETHERNET Ethernet is a LAN architecture developed by Xerox Corp in association with DEC and Intel. It either uses bus or star topology and support data transfer
rates up to 10Mbps.
ETHERNET CARD The computers that are a part of Ethernet, have to install a special card called Ethernet Card. It contains connections for either coaxial or twisted pair cables
or both.
HUB A hub is a network device used to connect several computers. Hubs share bandwidth among all attached devices. A hub has a number of input lines that
it joins electrically. Data-frames arriving on any of the input lines are sent out
on all the others. Hubs cant filter network traffic (i.e. If two packets arrive at the same time, they will collide). Hubs can be either active or passive.
Hubs are only suitable for use with very lightly loaded networks.
REPEATER A repeater is a device that amplifies the signals appearing on them.- for long distance transmission. Repeaters do not understand packets, or frames.
SWITCH A switch is a network device that is used to segment networks into smaller subnets or LAN segments. Segmenting the n/w into small subnets, prevent
traffic overloading.
BRIDGE A bridge is a network device that connects two or more LANs. When a data-frame arrives, software in the bridge extracts the destination address (MAC)
and looks it up in a table to see where to send the frame. Bridges can filter
network traffic.
ROUTER A Router is a network component that joins several networks together intelligently. It works like a bridge, but it can handle different protocols.
A router is more powerful than a bridge because it can look up the best route
to a distant site. The router filters network traffic based on IP addresses. The
Internet relies heavily on routers. GATEWAY A gateway is network device that connects dissimilar networks. It establishes
an intelligent connection b/w a local network and external networks with
completely different structures.
Good Network Design: The 80-20 Rule
[80% of the traffic on a given network segment should be local]
TIP Place the SERVER at a place (or building) where the total number of computers
connected is maximum and the sum of distances for others places (or buildings) is
minimum.
16
ABBREVIATIONS
Abbreviation Expanded Form
ARPANET Advanced Research Projects Agency NETwork
NSFNET National Science Foundation NETwork
NIU Network Interface Unit
NIC Network Interface Card
MAC Medium Access Control
bps bits per second
BPS Byte Per Second
LAN Local Area Network
MAN Metropolitan Area Network
WAN Wide Area Network
MODEM Modulator/Demodulator
AM Amplitude Modulation
FM Frequency Modulation
PM Phase Modulation
RJ-45 Registered Jack-45
PSTN Public Switched Telephone Network
PSDN Public Switched Data Network
ISDN Integrated Services Digital Network
HTTP Hypertext Transfer Protocol
FTP File Transfer Protocol
TCP/IP Transmission Control Protocol/Internet Protocol
SLIP Serial Line Internet Protocol
PPP Point To Point Protocol
POP3 Post Office Protocol 3
IMAP Internet Mail Access Protocol
SMTP Simple Mail Transfer Protocol
MIME Multipurpose Internet Mail Extensions
VoIP Voice over Internet Protocol
URL Uniform Resource Locator
DNS Domain Name Server
GSM Global Systems for Mobile communications
TDMA Time Division Multiple Access
CDMA Code Division Multiple Access
17
SIM Time Division Multiple Access
GPRS General Packet Radio Service
WLL Wireless in Local Loop
WAP Wireless Application Protocol
Wi-Fi Wireless Fidelity
WiMAX Worldwide Interoperability for Microwave Access
3G 3rd
Generation for mobile communications
EDGE Enhanced Data rates for Global Evolution
SMS Short Message Service
MMS Multimedia Message Service
e-mail electronic mail
www world wide web
HTML HyperText Markup Language
DHTML Dynamic HyperText Markup Language
XML eXtensible Markup Language
JSP Java Server Pages
PHP Preprocessor Hypertext
ASP Active Sever Pages
OSS Open Source Software
FLOSS Free Libre and Open Source Software
GNU GNUs Not Unix
FSF Free Software Foundation
OSI Open Source Initiative
W3C World Wide Web Consortium
KEY TERMS
Internet: The Internet is a world-wide computer network, i.e., a network that interconnects millions of computing devices throughout the world.
Intranet: An internet used by a single organization for internal purposes along with the key internet applications, especially the WWW. e.g. banks use intranet.
Interspace: Interspace allows multiple users to communicate online with real-time audio, video and text chat in 3D environments.
Telnet: Telnet is an Internet utility that lets you logon to a remote computer and function as if directly connected to that computer.
18
FTP (File Transfer Protocol): is used to send files from one system to another under user command. Both text & binary files are accommodated, and the protocol provides features for
controlling user access.
HTTP (Hyper Text Transfer Protocol): is the foundation protocol of the World Wide Web (WWW) and can be used in any client/server application involving hypertext. The most typical
use of HTTP is b/w a web-browser and a web-server. When a browser wants a Web page, it sends
the name of the page it wants to the server using HTTP; the server then sends the page back.
Network Security Concepts:
Authorization Means permissions or granting access to a service.
Authentication Concerned with assuring that a communication is authentic. It is the process of verifying the identity claimed by a communicating entity.
Firewall The system designed to prevent unauthorized access to or from a private network is called firewall. A firewall is considered as a first
line of defense in protecting private information. All traffic from inside to outside, and vice versa, is made to pass through the firewall. The firewall forms a barrier which acts as a filter and only authorized traffic as defined by the local security policy, will be allowed to pass.
A firewall can be implemented in both hardware or software or both.
Cookies Cookies are messages that web sites use to recognize users who have previously visited them. The browser stores the message in a
text file (with a few parameters like name, value, expiration date etc.) The next time the user accesses that site, the information in the cookie is sent back to the site and the customized web page is opened.
Hackers An exceptionally enthusiastic and skilled person who breaks into computers without authorization;
Crackers The crackers are the malicious programmers who break the security of a computer system, software program, algorithm, encrypted data, and so on. (u might heard of password cracking, software cracking)
Hacking Hacking refers to the unauthorized access of information.
Cyber law Cyber law is a generic term, which refers to all the legal and regulatory aspects of internet and the World Wide Web. Applications: track activities on internet, handling issues related to digital transactions, etc.
Virus A Malicious Program that attaches itself to a program/file and propagates copies of itself to other programs IN order to infect
them.
Trojan Horse A Trojan Horse is useful, or apparently useful, computer program containing a hidden code that, when invoked, performs some
unwanted or harmful function (such as erasing the hard-disk on a
specified date).
Worms A worm is a computer program that can replicate itself and send copies from computer to computer across network connections. Upon arrival, the worm may be activated to replicate and
propagate again. Worms are found primarily on computers that are capable of multitasking and are connected by a network.
Spam Spam refers to electronic junk mail or junk newsgroup postings.
19
Comparison between LAN, WAN & MAN
Parameter LAN WAN MAN
Area covered Covers small area i.e.
within the building
Covers large geographical
area (across countries,
continents)
Covers larger than LAN &
smaller than WAN (within
cities, town)
Error rates Lowest Highest Moderate
Transmission
speed
High speed Low speed Moderate speed
Equipment
cost
Uses inexpensive
equipment
Uses most expensive
equipment
Uses moderately expensive
equipment.
NETWORK TOPOLOGY: means the way systems are connected in a network. TOPOLOGY ADVANTAGES DISADVANTAGES
BUS Short cable length, easy to extend. Fault diagnosis difficult, nodes must be intelligent.
RING Short cable length, no wiring closet space required.
Fault diagnosis difficult, single node
failure causes network failure.
STAR Centralized control, fault diagnosis and isolation easier, simple access protocols.
Long cable length, difficult to expand,
central node dependency.
TREE Hierarchical flow of data, easy to extend. Long cable length, root dependency.
Terms related to WWW
Web Server A web server refers to a location on the internet that contains information in the form of web pages.
Web Page A web page refers to a document on the web.
Website A web site comprises of a collection of web pages on a net server that may be maintained & updated by an organization or individuals.
Web Portal A website that hosts other websites.
URL Each website has a unique web address called URL (Uniform Resource Locator).
Domain A portion of the Internet distinguished by a particular final part of the name. For instance, www.google.com, is a server in the commercial (.com) domain. Some most common domains are: com, edu, gov, org, net, co, mil, etc. In addition,
some domain names are location based also; which includes two letter
abbreviations for country names, like .in for India, .au for Australia, .uk for United
Kingdom, .jp for Japan. e.g. www.cbse.nic.in
Web Browser A software program that is used to view web pages. Browser helps you to connect to the web sites.
Ex. Internet Explorer, Mozilla Firefox, Opera, Google Chrome, etc.
Web Hosting Means hosting web server application on a computer system.
Web Scripting Process of creating and embedding scripts in a web page.
Script A script is a list of commands embedded in a web page.
20
POINTERS
INTRODUCTION:
A pointer is a variable that holds (or whose value is) the memory address of
another variable and provides an indirect way of accessing data in memory. The main memory (RAM) of computer consists of bytes which are numbered
sequentially. Each byte is numbered [i.e. from 0 to (n-1)] and this number is its address.
When we declare a variable, we mention its type and its name, and the compiler
along with operating system allocates a block of memory for storing the value of the
variable.
Generally, the address of a variable is the address (byte number) of the very first byte of
the memory block allocated to the variable. This address is known as base address.
While programming, a programmer doesnt knows what address is to be allocated by the compiler to a variable. However, C++ provides address-of operator (&), also called
reference operator to retrieve the address of a variable.
For instance, if n is an integer variable, its address (i.e. address of the first byte, also called base address) is given by &n. We may declare another variable for storing
&n, which is the address of n. That variable is called pointer to n.
1020
p is a pointer to n 1020
p n (pointer variable)
---------------------------------------------------------------------------------------------
POINTERS : DECLARATION AND INITIALIZATION
A pointer variable can be declared as follows:
type *ptrvarname;
The operator (*) tells the compiler that the variable name on its right is a pointer and is
going to store a memory address. e.g.
int *iptr; // pointer to an integer
char *cptr; // pointer to a character
float *fptr; // pointer to a floating point number.
21
Initializing a pointer (Creating a Link):
Like any other variable, a pointer variable must also be initialized before using it. Pointers
may be initialized to an address or otherwise to 0 or NULL, which is a symbolic constant. NULL is defined in header file iostream.h and other C++ header files like stddef.h. It is
equivalent to 0. A NULL pointer does not point to any valid data.
A pointer variable can be initialized as follows:
ptrvarname=&variable;
e.g.
iptr=&a; // assuming a is declared as a variable of type int.
cptr=&ch; // assuming ch is declared as a variable of type char. fptr=&f; // assuming f is declared as a variable of type float.
The pointer variable can be declared as well as initialized in a single line as follows:
type *ptrvarname=&variable;
e.g.
int *iptr = &a;
char *cptr = &ch;
float *fptr = &f;
---------------------------------------------------------------------------------------------
Indirection or Dereference Operator:
The value of a variable may be obtained from its pointer by using indirection
operator also called dereference operator (*). It is called indirection because it obtains
the value indirectly. e.g.
int n = 5, *iptr ;
iptr = &n ; *iptr = 60; // read as value at address iptr is 60; this expression makes the value of n as 60.
In this way pointers may be used in place of the variables they point to.
---------------------------------------------------------------------------------------------
NOTE:
i) The pointer variables must always point to the correct type of data. Making a pointer point to
incorrect type of data may lead to loss of information. e.g.
float f;
int *ptr; cin>>f; ptr=&f; // NOTE pointer ptr is of type int and is initializing it with the address of a float point value.
ii) A pointer variable must not remain uninitialized since uninitialized pointers cause the system
crash. To avoid this problem, initialize such pointers with NULL.
22
iii) NULL Pointer: A NULL Pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid memory address.
e.g.
int *p=NULL; (OR) int *p=0;
iv) In pointer arithmetic, all pointers increase or decrease by the length of the data-type they
point to. e.g.
int a; // Suppose address of a is 1020
int *iptr=&a; iptr++; // iptr now points to 1022 instead of 1021
iptr+=3; // iptr now points to 1028 instead of 1025
iptr iptr+1 iptr+2 iptr+3 iptr+4
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
Fig: To illustrate all pointer arithmetic is relative to its base type.
v) The pointers to two or more variables of same type may be declared in the same line. e.g.
int m, n, *m, *n; m=&m;
n=&n;
vi) A pointer variable itself is allocated 4-bytes of memory space (on 32-bit systems) to store
the memory address irrespective of the fact whether the variable to which it points to is
integer, double or character.
The following program illustrates this:
#include int main()
{ int n = 6,*iptr;
double PI = 3.14 ,*fptr;
fptr = Π iptr = &n;
char ch = 'M',*cptr;
cptr = &ch; // initializing by &ch
cout
23
OUTPUT:
Size of the pointer to int n = 4
Size of the pointer to double PI = 4
Size of the pointer to char ch = 4
Variables are 6, 3.14 and M
vii) POINTER TO POINTER: Just like we have a pointer to a variable, we can also define a
pointer to a pointer which keeps the address of the pointer to the variable.
e.g.
int*iptr = &n ; // iptr is pointer to n
int** pptr = & iptr ; // pptr is pointer to iptr
Note that both for pointer and pointer to pointer, the type is int because n is integer. Also note
that for getting the value of variable, we use one dereference operator (*) to pointer while for
getting the value of variable from pointer to pointer, we have to use two dereference operators
(**). This situation is called multiple indirection. But there is no change in the application of
address-of operator (&).
viii) CONSTANT POINTERS: The attribute modifier const may be used with pointers as well.
However, the declaration should be done carefully keeping in view the following:
const int* ptr ; // Here ptr is a non-constant pointer to a constant int.
int* const ptr ; // Here ptr is a constant pointer to a non-constant int.
const int* const ptr ; // Here ptr is a constant pointer to a constant int.
-------------------------------------------------------------------------------------------------------------------------------
POINTER TO ARRAY: [1-D array] Arrays and Pointers are very closely linked in C++ and may be used almost interchangeably.
C++ treats the name of an array as a constant pointer that always point to the first element of
the array; and the pointer to array also carries the address of the first element of the array. Thus
the pointer to an array has same value as the name of the array. The declaration of a pointer to an array is illustrated below:
int A[] = {12, 25, 36 ,50}; // A is the name of array
int *ptrA ; // pointer ptrA of type int declared
ptrA = A ; // assigns address of array A to ptrA; Notice there is no & operator before A.
The above definition may also be written as below: int *ptrA = A;
This is equivalent to taking the address of the first element of the array as follows: int *ptrA = A[0]; // It is so because the address of A[0] is same as of A.
24
C++ provides two methods of accessing array elements: array indexing and pointer
arithmetic. e.g.
The elements of the above array A[0], A[1], A[2], and A[3] have respective values as 12, 25, 36 and 50 which may also be obtained from pointers as illustrated below:
Pointer *ptrA *(ptrA+1) *(ptrA+2) *(ptrA+3) arithmetic
12 25 36 50
Array
indexing A[0] A[1] A[2] A[3]
The above discussion shows that array subscript and pointer offset are equal. If we call array A
without a subscript, it will give the address of first element of array. A +1 gives the address of second
element, A+2 gives address of third elements and so on. Therefore, we can also get the values stored at
these addresses by using dereference operator (*). Thus for the above declared array we may get the
values of array elements as given below:
*A = A[0] = 12
*(A+1) = A[1]= 25
*(A+2 )= A[2]= 36
*(A+3) = A[3]= 50
Note that expression *A++ is not legal because A is a constant pointer to array and a
constant cannot be incremented/decremented.
Program to Illustrate declaration of pointer to an array:
#include int main()
{
int A [] = {12, 25, 36 ,50}; // A is an array of integers
int *ptrA = A; //ptrA is pointer to A. Note that & is not used.
cout
25
The expected OUTPUT is as below:
*ptrA =12 ptrA =0x225f2450
*(ptrA+1)=25 ptrA+1=0x225f2452
*(ptrA+2)=36 ptrA+2=0x225f2454
*(ptrA+3)=50 ptrA+3=0x225f2456
A = 0x225f2450
12 25 36 50
12 25 36 50
----------------------------------------------------------------------------------------------------------------------------- --
ARRAY OF POINTERS:
Similar to other variables, we can create an array of pointers in C++. The pointers may be
arrayed by declaring a pointer array of specific type and then assigning each element of the pointer array by the addresses.
type *pointerArrayName[size];
Ex. An array holding 6 integer pointers can be declared as:
int *p[6]; // declares an array P that can hold 6 int pointers
After this declaration, contiguous memory would be allocated for 6 pointers that
can point to integers.
To assign the address of an integer variable called var to the third element of the
pointer array, we may write: p[2] = &var;
To get the value of that var, we can write : *p[2]
The following program illustrates this:
#include
int main()
{ int *p[6];
int a=11,b=22,c=33,d=44,e=55,f=66;
p[0]=&a; p[1]=&b; p[2]=&c; p[3]=&d; p[4]=&e; p[5]=&f;
cout
26
cout
27
Program to Illustrate string pointer pointing to several strings:
#include
void main()
{ char *pstr[]={ "PHY", "CHEM", "MATHS", "BIO" };
for(int i=0;i
28
Invoking functions by passing the pointers:
When the pointers are passed to the function, the addresses of actual arguments in the calling function are
copied into the formal arguments of the called function. i.e. in the function-call statement, we have to
pass addresses of actual arguments. Thus, the called function doesnt create its own copy of original values, rather, it refers to the original values by the addresses it receives in corresponding pointers.
The declaration of a function (Function Prototype) that is invoked by passing pointer looks like:
return-type functionname( type*, type*, . . . );
Ex: Program to swap values of two variables by passing pointers
#include void main()
{
void swap(int* , int*); // prototype
int a=10,b=20; cout
29
Functions returning pointers:
Like any other data-type, a function may also return a pointer.
The general form of prototype of a function returning a pointer would be
type *functionname(argument-list);
where type specifies the pointer type being returned by the function specified by functionname
Program to illustrate a function returning a pointer:
#include
void main()
{ int *bigger(int*, int*); // prototype
int a,b,*big;
coutb;
big= bigger(&a, &b); // function call
cout
30
POINTERS TO STRUCTURES:
Just like pointers to any other data-type, C++ also allows pointers to structures. The pointers to structures
are also known as structure pointers.
The general form of declaration of a structure pointer is as follows:
structname *structpointer;
where structname is the name of an already defined structure and structpointer is the pointer to this structure.
e.g.
#include
struct stu
{ int rollno;
char name[20];
float marks;
}; void main()
{ stu s1={1, "mohan", 76},*pstu; // declaration
pstu=&s1; // initialization
cout
31
Self-Referential Structures:
A structure having a member element that refers to the structure itself is known as self-
referential structure.
For Example:
struct stu
{
int rollno;
char name[20]; float marks; stu *next; // *next is referring to the structure stu itself
};
In the above example, * next is referring to the structure stu itself. It is useful in
defining linked lists wherein each element points to the next element of same type.
-------------------------------------------------------------------------------------------------------------------------------
POINTERS AND OBJECTS:
C++ also allows us to have pointers to objects. The pointers pointing to objects are
referred to as object pointers.
The general form of declaration of an object pointer is as follows:
classname *objectptr;
where classname is the name of an already defined class and objectptr is the pointer to an object of this class type.
e.g. student s1; // s1 is an object of class student
s1 *optr; // optr is the object pointer.
Accessing public members of a class
By using dot operator (.) in case by using the arrow operator (->) while accessing the class members in case while accessing the class using an object members using an object pointer.
s1.getdata(); optr-> getdata();
s1.display(); optr -> display();
32
e.g. Consider the program :
#include
#include
class stu
{ int rollno;
char name[20];
float marks;
public: void getdata(int r, char n[], float m)
{ rollno=r; strcpy(name,n); marks=m;}
void display()
{ cout
33
this POINTER
The this pointer is an object pointer which points to the currently calling object. It stores the address of
the object that is invoking a member-function. The this pointer is, by default, available to each called member-function. Following example illustrates this:
Consider the program :
#include
#include class stu {
char name[20];
public: Note that this can be used only within a member stu(char *n) function and it stores the address of the calling object { strcpy(name,n); }
void display()
{ cout
34
DATA STRUCTURES
The logical or mathematical model of data is called a data structure. Data
structures are the building blocks of a program. The selection of a particular data structure will help the programmer to design more efficient programs.
A data structure has a well-defined operations, behaviour & properties.
Operations on a Data Structure: Insertion Deletion Searching Sorting Traversal
Reversing Merging Copying Concatenation
Types of Data Structures
Linear Data structures Non Linear Data Structures
elements form a sequence represent hierarchical
relationships
Array
Linked List Trees
Stack (LIFO List) Graphs
Queue (FIFO List)
ARRAYS An array is a finite collection of similar elements stored in contiguous memory locations.
Array size = U- L + 1 In C++, the lower bound (L) is always 0.
The address of first element of an array is called the Base Address (B).
-------------------------------------------------------------------------------------------------------------------------------
2-D arrays: A 2-D array is an array in which each element is itself an array. Its sometimes also called a matrix.
Formula for address calculation in 2-D arrays
In Row Major Arrangement (row wise) In Column Major Arrangement (column wise)
Address of a[i][j] = B + W ( i *col + j )
Or
Address of a[i][j] = B + W [( i Lr)* col + ( j-Lc)]
Address of a[i][j] = B + W ( j *row + i )
Or
Address of a[i][j] = B + W [( j Lc)* row + (i -Lr)]
Here, Lr = Lower Bound of Row (i.e. first row number)
and Lc = Lower Bound of Column (i.e. first column number)
35
SEARCHING AND SORTING: (Once Go Through the Searching and Sorting Algorithms)
SEARCHING
SORTING
LINEARS SEARCH
BINARY SEARCH
INSERTION SORT
SELECTION SORT BUBBLE SORT
LINKED LIST
A linked list is a linear collection of specially designed elements called nodes; each of which stores two items of information- an element of the list (data part)
and a link (pointer).
25 2002 50 2004 70 2006 99 NULL
2000 2002 2004 2006
A linked list can grow as well as shrink in size during its lifetime. Linked lists are used preferably when the quantity of data is not known prior to execution.
Defining each node of a linked list: In linked lists, data is stored in the form of nodes (self-referential structure) and at run-time, memory is allocated for creating
nodes (using new operator). The data can be accessed using the START pointer of
the list.
struct node
{
int data; // data part node *link; // link part
};
36
STACK A stack is a linear data structure in which addition of new element or deletion of an existing element takes
place at the same end. This end is often known as the top of the stack.
The stack is sometimes also called as LIFO List (Last-In-First-Out), because the last element
pushed into the stack is the first one to be popped out.
Operations on a stack
Operation DESCRIPTION
PUSH To insert an element at the top of the stack
POP To remove an existing element from the top of the stack
STACK IMPLEMENTATION
Static implementation (using arrays) Dynamic implementation (using pointers)
PUSH and POP function definitions
(using arrays)
PUSH and POP function definitions
(using pointers)
void stack :: push ( int item ) {
if ( top == MAX - 1 )
{
cout data = item ;
temp -> link = top ; top = temp ; //top pointer is set
}
void stack :: pop( ) {
if ( top == -1 )
{ cout
37
QUEUE Queue is linear data structure that permits insertion of new element at one end (called rear of the queue)
and deletion of an existing element at the other end (called front of the queue). Queues are sometimes
also called FIFO List (First-In-First-Out).
Operations on a stack
QUEUE IMPLEMENTATION
Static implementation (using arrays) Dynamic implementation (using pointers)
INSERT and DELETE function definitions (using arrays)
INSERT and DELETE function definitions (using pointers)
void queue :: insertq ( int item ) {
if ( rear == MAX - 1 ) {
cout data = item ;
temp -> link = NULL ;
if ( front == NULL )
{
rear = front = temp ; return ;
}
rear -> link = temp ;
rear = rear -> link ;
}
void queue :: delq( ) {
if ( front == -1 )
{ cout
38
Function That Evaluates the Postfix Expression
------------------------------------------------------------------------------------------------------ void postfix :: calculate( ) {
int n1, n2, n3 ;
while ( *s ) {
if ( *s == ' ' || *s == '\t' ) // skip whitespace, if any
{
s++ ; continue ;
}
if ( isdigit ( *s ) ) // if digit is encountered
{
nn = *s - '0' ;
push ( nn ) ; }
else
{ // if operator is encountered
n1 = pop( ) ; n2 = pop( ) ;
switch ( *s )
{ case '+' :
n3 = n2 + n1 ;
break ;
case '-' : n3 = n2 - n1 ;
break ;
case '/' : n3 = n2 / n1 ;
break ;
case '*' : n3 = n2 * n1 ;
break ;
case '%' :
n3 = n2 % n1 ; break ;
case '$' :
n3 = pow ( n2 , n1 ) ; break ;
default :
cout
39
DATA FILE HANDLING
The Language like C/C++ treat everything as a file, these languages treat
keyboard, mouse, printer, Hard disk, Floppy disk and all other hardware as a file. In C++, a file, at its lowest level, is interpreted simply as a sequence of (or stream of)
bytes.
Files in computers are of two types. One that stores instruction for the computer,
i.e. a program file and the second that stores data, i.e. data file.
FILES
Program Files Date Files
Text Files Binary Files
data stored in the form of data stored in the form of characters (ASCII Code) sequence of bytes, i.e. 0s & 1s
each line terminated with a special Character known as end-of-line there is no EOL character (EOL) character
---------------------------------------------------------------------------------------------
What is a Stream?
A stream is a general name given to the flow of data. Different streams are used to
represent different kind of data flow. Each stream is associated with a particular
class of fstream.h header file of the standard library.
The streams are of the following types:
---------------------------------------------------------------------------------------------
Basic Operations On A Text File
Creating or writing in file.
Reading a text file and displaying contents.
Manipulating the contents read from a text file.
Type of stream Associated Class input stream (Read mode) ifstream
output stream (Write mode) ofstream
input/output stream (R/W mode) fstream
40
To be able to carry out the above basic operations on a file, the following sequence has to
be followed:
Open the file.
Perform operation on the file.
Close the file. ---------------------------------------------------------------------------------------------
Opening A File
Before opening a file, we shall create a file stream object of a particular class (ifstream,
ofstream or fstream) depending upon the type of operation.
e.g. In order to open a file as an input file i.e. data will be read from it and no other operation
would take place, we shall create a file stream object of ifstream type.
Similarly, in order to open an output file (on which no operation can take place except writing
only), we shall create a file stream object of ofstream type.
A file can be opened in two ways:
Using the constructor function of the class (useful when we use only one file in the stream)
e.g. ofstream outfile(marks.dat);
Using member function open() of the class (useful in case of multiple files)
e.g. ofstream outfile; outfile.open(marks.dat);
--------------------------------------------------------------------------------------------- Concept of File Modes
The file mode describes how a file is to be used - to read from it, to write to it, to append
it, and so on.
File Mode Constants
Meaning Associated Class
ios::in Open for reading (default for ifstream) ifstream
ios::out Open for writing (default for ofstream) ofstream
ios::ate Start reading or writing at the end of file (AT End) ofstream ifstream
ios::app Start writing at end of file (APPend) ofstream
ios::trunk Truncate file to zero length if it exists (TRUNCate) ofstream
ios::nocreate Error when opening if file does not already exist. ofstream
ios::noreplace Error when opening for output if file already exist, unless ate
or app is set.
ofstream
ios::binary Open file in binary (not text) mode. ofstream
ifstream
Note:
1) We can combine two or more file mode constants using the C++ bitwise OR (|) operator.
2) The fstream class does not a mode by default and, therefore, one must specify the
mode explicitly when using an object of the fstream class. ----------------------------------------------------------------------------------------------------------------
41
How is end-of-file detected in a file?
The end of any file is checked with eof() function which is predefined in class
ios of ifstream, ofstream and fstream classes. If the file pointer points to the end-
of-file then condition is TRUE and the object returns zero otherwise it returns a
non-zero value. ----------------------------------------------------------------------------------------------------------------
File Pointers
Each file has two pointers associated with it which are called file pointers. One of
them is the input pointer, known as get pointer; and the other one is called output
pointer or the put pointer.
File Pointers
get pointer put pointer
(input pointer) (output pointer)
Used for reading the Used for writing to a given contents of a file location file location
NOTE: Each time an input or output operation takes place; the concerned pointer is
automatically advanced.
Open for reading only Open in app mode Open for writing only
I N D I A
GET POINTER PUT POINTER PUT POINTER ----------------------------------------------------------------------------------------------------------------
How can the file pointers be moved in a file?
The file stream classes support some predefined functions that navigate the position of the file-pointers. The relevant functions are: seekg(), seekp(), tellg(),
and tellp().
Function
name
Description
seekg() Moves the get pointer or input pointer to a specified location
seekp() Moves the put pointer or the output pointer to a specified
location
tellg() Gives the current position of the get pointer
tellp() Gives the current position of the put pointer
I N D I A
42
seekg() and seekp() are the functions used for manipulation of file pointers.
e.g. ifile.seekg(30);
This statement moves the get pointer to the byte number 30 in the file linked
with ifile. Remember the counting of bytes in a file begins from zero.
Another form of seek() function
seekg( offset, reposition);
seekp( offset, reposition);
e.g. ifile.seekg(10, ios::beg); //goto byte number 10 from the beginning ifile.seekg(10, ios::cur); //goto byte number 10 from the current position
ifile.seekg(0, ios::end); //goto end of the file.
ifile.seekg(-10, ios::end) // goto 10 bytes before the end of file.
----------------------------------------------------------------------------------------------------------------
Closing A File A file is closed by disconnecting it with the stream it is associated with. A file can be
closed in two ways:
If the file has been opened using constructor, it gets closed automatically as
soon as the stream objects go out of scope. This calls the destructor, which
closes the file.
Using close function of the class
e.g. infile.close();
(or) outfile.close();
----------------------------------------------------------------------------------------------------------------
43
EXAMPLE 1: CREATING/WRITING A FILE: #include
void main() { ofstream outfile(poem.txt); // create file for output outfile
44
Writing/Reading Data in Binary Format
To write and read data in binary format two member functions are available
in C++. They are read( ) and write( ).
The syntax of read() and write() function is given below:
fileobject.write((char *)&object, sizeof(object));
fileobject.read((char *)&object, sizeof(object)); Example of write ( ) member function
#include
#include struct student
{ int roll ;
char name[30];
char address[60]; };
int main()
{ student s; ofstream fout;
fout.open("student.dat");
couts.roll;
couts.name;
couts.address;
fout.write((char *)&s, sizeof(student));
fout.close(); return 0;
}
-----------------------------------------------------------------------------------------------------
Example To Read data from a binary File using read( ) member function #include
#include
struct student { int roll ;
char name[30];
char address[60]; };
int main()
{ student s;
ifstream fin; fin.open("student.dat");
fin.read((char *)&s, sizeof(student));
cout
45
Example To Write Class object in a file #include
#include
class student
{ int roll ; char name[30];
char address[60];
public:
void read_data( ); // member function prototype void write_data( ); // member function prototype
};
void student::read_data( ) // member function defintion
{ coutroll;
coutname;
coutaddress; }
void student:: write_data()
{ cout
46
void student::read_data( ) // member function definition {
coutroll;
coutname;
coutaddress;
} void student:: write_data()
{
cout
47
DATABASES AND SQL
What is a database? A database is a collection of interrelated data stored together to serve multiple
applications.
Database Management System (DBMS)
48
DATA MODELS
A data model is a collection of conceptual tools that can be used to describe the
structure of the database including data types, relationships and constraints that
should apply on the data.
A data model should possess the following characteristics so that the best
possible data-representation can be obtained:
Should be represented diagrammatically.
No duplication in the representation of data. It could be shared by different applications
Consistency and structure validity is maintained.
Detailed enough to be used by a database designer to build the database.
Different types of data models The various data models that have been proposed fall into three different categories:
Hierarchical Model (tree structure)
Object-based data model Record-based data model Network Model (directed graphs)
Physical data model
Relational Model (tables or relations)
RELATIONAL MODEL
The relational model is considered as one of the most popular developments in the database technology because it can be used for representing most of the real world
objects and the relationships between them.
The relational model uses a collection of tables to represent both data and the
relationships among those data. Each table consists of rows and columns. A row in a table
represents a relationship among a set of values. Since a table is a collection of such
relationships, there is a close correspondence between the concept of table and the
mathematical concept of relation, from which the relational model got its name.
49
Relational Model Terminology
The following is the list of relational terms and their corresponding meanings:
Formal Relational Term Their Meanings
Relation Table
Tuple Row (or record)
Attribute Column ( or field)
Cardinality No. of rows
Degree or Arity No. of columns
Domain Set of legal values
Primary key Unique identifier
Foreign Key Identifier used to reference
another table.
To understand these terms, let us consider an instance of a STU relation.
Primary Attributes domains key
Attribute names
Tuples
degree
cardinality = In the above STU Relation, there are 6 tuples (i.e. 6) and 5 attributes (i.e.
degree = 5).
Stu_id, Stu_name, Age, City, and Gender are the attribute names.
The first tuple contains ( CS01, Aman ,17, vizag , M ) as its values.
The domain of the of the gender attribute is (M,F).
Stu_id Stu_name Age City Gender
CS01 Aman 17 Vizag M
CS02 Raman 18 Chennai M
CS03 Simran 21 Hyderabad F
CS04 Boman 16 Mumbai M
CS05 Anjali 18 New Delhi F
CS06 Rahul 20 Chandigarh M
ca
r
di
n
a
li
ty
50
KEYS
The central concept in the relational model is concept of KEY.
A key is an attribute or a collection of attributes that may uniquely identify a particular tuple within a relation.
Different types of keys
KEY DESCRIPTION
Primary Key A primary key is an attribute or a group of attributes that can
uniquely identify tuples within the relation.
Candidate Key A candidate key is one that is capable of becoming the primary
key. (i.e. candidate for primary key position).
Alternate Key A candidate key that is not the primary key is called an
alternate key.
Foreign Key A non-key attribute, whose value(s) are derived from the
primary key of some other table, is known as foreign key in its
current table.