Sie sind auf Seite 1von 50

1

material prepared by: MUKESH BOHRA


MAIL UR FEEDBACK AT: mbthebigboss@gmail.com
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
If the result of a boolean expression is
always TRUE or 1, it is called a tautology.

Fallacy
If the result of a boolean expression is
always FALSE or 0, it is called Fallacy.

-----------------------------------------------------------------------------------------------------------------------------

LOGIC GATES
Logic gates are small electronic circuits that work on digital signals. Basically logic gates
are of two types:

Basic Gates
AND gate

Derived Gates
NAND gate

OR gate
NOT gate

NOR gate
X-OR gate
X-NOR gate

BASIC GATES:
1. AND gate
Operation
Symbol
Graphical symbol

:
:
:

logical multiplication
. or ^

Y=A.B

i/p lines

o/p line

Truth Table:
INPUT
A
0
0
1
1

OUTPUT
Y= A.B
0
0
0
1

B
0
1
0
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
Symbol
Graphical symbol

i/p lines

:
:
:

logical addition
+ or v

Y=A+B
o/p line

3
Truth Table:
INPUT
A
0
0
1
1

OUTPUT
Y= A+B
0
1
1
1

B
0
1
0
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
Symbol
Graphical symbol

i/p line

:
:
:

Compliment
or

o/p line

Truth Table:

Input
A
0
1

Y = A (or A )

output
Y = A
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
B

A.B
Y = A.B

4
Graphical symbol:
A
Y=A.B

i/p lines

o/p line

Truth Table:
INPUT
A

A.B

OUTPUT
Y= A.B

0
0
1
1

0
1
0
1

0
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+B
Y=A+B

B
Graphical symbol:
A
i/p lines

Y=A+B
B

o/p line

INPUT
A

A+B

OUTPUT
Y= A+B

0
0
1
1

0
1
0
1

0
1
1
1

1
0
0
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.

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

AB
B

Graphical symbol:

Y = A + B = AB + AB

i/p lines

o/p line

Truth Table:
INPUT
A
B

AB

AB

0
0
1
1

1
1
0
0

1
0
1
0

0
1
0
0

0
0
1
0

0
1
0
1

OUTPUT
Y =A+ B
= AB + AB
0
1
1
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.

4. X-NOR gate:
It is obtained by complementing the output of X-OR gate.

AB

i/p

A+B

Y=A . B

o/p
B

AB

Graphical symbol:

i/p lines

Y = A . B = AB + AB

o/p line

Truth Table:
INPUT
A
B

AB

AB

AB + AB

0
0
1
1

1
1
0
0

1
0
1
0

0
1
0
0

0
0
1
0

0
1
1
0

0
1
0
1

OUTPUT
Y =A . B
= AB + AB
1
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.

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

Y= A

2) AND gate using NAND

A.B

Y = A.B = A.B

3) OR gate using NAND

A
A
Y = A. B = A + B = A + B

B
B

ii. Construction of basic gates using NOR gate:


1) NOT gate using NOR

Y=A
A

2) OR gate using NOR

A+B

Y = A+B = A+B

3) AND gate using NOR

A
A
Y=A+B=A.B=A.B

B
B

------------------------------------------------------------------------------------------------------

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
Gray Code

A single variable or its compliment.


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
AB

CD

00

00

g2
01

10

1
m0

01

11

1
m1

m3

m2
1

m4

m5

m7

m6

m12

m13

m15

m14

11

10

1
m8

m9

m11

m10
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

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

first complete physical


connection is setup & then
the msg is passed.
(mostly used for voice
communication)

Packet Switching

Message Switching

msg segmented into smaller packets


and then transmitted into the n/w.
At receving end, packets are
reassembled to get back the orig. msg.

whole messages are


transmitted through
the n/w.

TRANSMISSION MEDIA
Guided Media
(Wired)
Include Cables

Twisted-Pair Cable (@1mbps upto 100m)


Coaxial Cable (@10mbps upto several-100m)
Fiber-Optic Cables (v. high data transfer rates)

Unguided Media
(Wireless)
Include waves through
air, water or vacuum

Microwaves (upto 50km)


Radio waves (city,states etc)
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
ETHERNET
ETHERNET CARD
HUB

REPEATER
SWITCH
BRIDGE

ROUTER

GATEWAY

Registered jack-45 is an 8-wire connector, which is commonly used to connect


computers on LANs-especially Ethernets.
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.
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.
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.
A repeater is a device that amplifies the signals appearing on them.- for long
distance transmission. Repeaters do not understand packets, or frames.
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.
A bridge is a network device that connects two or more LANs. When a dataframe 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.
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.
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
NSFNET

Advanced Research Projects Agency NETwork


National Science Foundation NETwork

NIU
NIC

Network Interface Unit


Network Interface Card

MAC

Medium Access Control

bps
BPS

bits per second


Byte Per Second

LAN
MAN
WAN

Local Area Network


Metropolitan Area Network
Wide Area Network

MODEM

Modulator/Demodulator

AM
FM
PM

Amplitude Modulation
Frequency Modulation
Phase Modulation

RJ-45

Registered Jack-45

PSTN
PSDN
ISDN

Public Switched Telephone Network


Public Switched Data Network
Integrated Services Digital Network

HTTP
FTP
TCP/IP
SLIP
PPP
POP3
IMAP
SMTP
MIME
VoIP

Hypertext Transfer Protocol


File Transfer Protocol
Transmission Control Protocol/Internet Protocol
Serial Line Internet Protocol
Point To Point Protocol
Post Office Protocol 3
Internet Mail Access Protocol
Simple Mail Transfer Protocol
Multipurpose Internet Mail Extensions
Voice over Internet Protocol

URL
DNS

Uniform Resource Locator


Domain Name Server

GSM
TDMA
CDMA

Global Systems for Mobile communications


Time Division Multiple Access
Code Division Multiple Access

17

SIM
GPRS
WLL
WAP
Wi-Fi
WiMAX
3G
EDGE
SMS
MMS

Time Division Multiple Access


General Packet Radio Service
Wireless in Local Loop
Wireless Application Protocol
Wireless Fidelity
Worldwide Interoperability for Microwave Access
3rd Generation for mobile communications
Enhanced Data rates for Global Evolution
Short Message Service
Multimedia Message Service

e-mail

electronic mail

www

world wide web

HTML
DHTML
XML

HyperText Markup Language


Dynamic HyperText Markup Language
eXtensible Markup Language

JSP
PHP
ASP

Java Server Pages


Preprocessor Hypertext
Active Sever Pages

OSS
FLOSS
GNU
FSF
OSI
W3C

Open Source Software


Free Libre and Open Source Software
GNUs Not Unix
Free Software Foundation
Open Source Initiative
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
Authentication
Firewall

Means permissions or granting access to a service.


Concerned with assuring that a communication is authentic. It is
the process of verifying the identity claimed by a communicating
entity.
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 refers to the unauthorized access of information.
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.
A Malicious Program that attaches itself to a program/file and
propagates copies of itself to other programs IN order to infect
them.
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).
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

Hacking
Cyber law
Virus
Trojan Horse

Worms

Spam

capable of multitasking and are connected by a network.


Spam refers to electronic junk mail or junk newsgroup postings.

19

Comparison between LAN, WAN & MAN


Parameter
Area covered

LAN
Covers small area i.e.
within the building
Lowest
High speed

WAN
Covers large geographical
area (across countries,
continents)
Highest
Low speed

MAN
Covers larger than LAN &
smaller than WAN (within
cities, town)
Moderate
Moderate speed

Error rates
Transmission
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
Short cable length, easy to extend.
Fault diagnosis difficult, nodes must be
BUS
intelligent.
Short cable length, no wiring closet
Fault diagnosis difficult, single node
RING
space required.
failure causes network failure.
Centralized control, fault diagnosis and
Long cable length, difficult to expand,
STAR
isolation easier, simple access protocols. central node dependency.
Hierarchical flow of data, easy to extend. Long cable length, root dependency.
TREE
Terms related to WWW

Web Server
Web Page
Website
Web Portal
URL
Domain

A web server refers to a location on the internet that contains information in


the form of web pages.
A web page refers to a document on the web.
A web site comprises of a collection of web pages on a net server that may
be maintained & updated by an organization or individuals.
A website that hosts other websites.
Each website has a unique web address called URL (Uniform Resource
Locator).
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
Web Hosting
Web Scripting
Script

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.
Means hosting web server application on a computer system.
Process of creating and embedding scripts in a web page.
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

(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;
cptr=&ch;
fptr=&f;

// assuming a is declared as a variable of type int.


// assuming ch is declared as a variable of type char.
// 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;
int *iptr=&a;
iptr++;
iptr+=3;

iptr

1020

// Suppose address of a is 1020


// iptr now points to 1022 instead of 1021
// iptr now points to 1028 instead of 1025

iptr+1

1021

1022

iptr+2

1023

1024

iptr+3

1025

1026

iptr+4

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 <iostream.h>
int main()
{
int n = 6,*iptr;
double PI = 3.14 ,*fptr;
fptr = &PI;
iptr = &n;
char ch = 'M',*cptr;
cptr = &ch; // initializing by &ch
cout<< "Size of the pointer to int n = " <<sizeof(iptr)<<endl;
cout <<"Size of the pointer to double PI = "<<sizeof(fptr)<<endl;
cout<< "Size of the pointer to char ch = "<<sizeof(cptr) <<endl;
cout<<"Variables are "<<*iptr <<", "<<*fptr<<" and "<<*cptr<< endl;
return 0;
}

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 ;
int** pptr = & iptr ;

// iptr is pointer to n
// 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 ;


int* const ptr ;
const int* const ptr ;

// Here ptr is a non-constant pointer to a constant int.


// Here ptr is a constant pointer to a non-constant int.
// 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:
*ptrA

Pointer
arithmetic
12
Array
indexing

*(ptrA+1)

25

A[0]

A[1]

*(ptrA+2)

36
A[2]

*(ptrA+3)

50
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 <iostream.h>
int main()
{
int A [] = {12, 25, 36 ,50};
int *ptrA = A;

// A is an array of integers
//ptrA is pointer to A. Note that & is not used.

cout<<"*ptrA ="<<*ptrA <<"\t ptrA ="<<ptrA<<endl;


cout<<"*(ptrA+1)="<<*(ptrA+1)<<"\t ptrA+1="<<(ptrA+1)<<endl;
cout<<"*(ptrA+2)="<<*(ptrA+2)<<"\t ptrA+2="<<(ptrA+2)<<endl;
cout<<"*(ptrA+3)="<<*(ptrA+3)<<"\t ptrA+3="<< (ptrA+3)<<endl<<endl;
cout<<"A = "<< A<<endl;
cout<<ptrA[0]<<\t<<ptrA[1]<<\t<<ptrA[2]<<\t<<ptrA[3]<<endl;
cout <<*(A+0)<<\t<<*(A+1)<<\t<<*(A+2)<<\t<<*(A+3)<<endl;
// These will display the values of array elements.

return 0;
}

25

The expected OUTPUT is as below:


*ptrA
=12
*(ptrA+1)=25
*(ptrA+2)=36
*(ptrA+3)=50
A = 0x225f2450
12
25
36
50
12
25
36
50

ptrA =0x225f2450
ptrA+1=0x225f2452
ptrA+2=0x225f2454
ptrA+3=0x225f2456

----------------------------------------------------------------------------------------------------------------------------- --

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 <iostream.h>
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<< "THE VALUES ARE:\n";
for(int i=0;i<6;i++)
cout<<*p[i]<<"\t";
cout<<\nThe size of p is: <<sizeof(p);
cout<<\nThe size of (p[0]) is: <<sizeof(p[0]);
cout<<\nThe size of (p[1]) is: <<sizeof(p[1]);

26
cout<<\nThe size of (*p[0]) is: <<sizeof(*p[0]);
cout<<\nThe size of (*p[1]) is: <<sizeof(*p[2]);
return 0;
}

The expected OUTPUT is as below:


THE VALUES ARE:
11 22 33 44 55 66
The size of p is: 24
The size of (p[0]) is: 4
The size of (p[1]) is: 4
The size of (*p[0]) is: 2
The size of (*p[1]) is: 2

POINTERS AND STRINGS: [storing several strings in the memory]


We know that a string is a one-dimensional array of characters, which start with the index
0 and ends with the null character \0. C++ also allows us to handle strings with pointers, simply
called string array. Each entry in the array is a string, but in C++ a string is essentially a pointer to
its first character, so each entry in an array of strings is simply a pointer to the first character
of a string.

e.g. Consider the declaration of string array pstr that might be useful in representing different
subjects:
char *pstr[ 4 ] = { "PHY", "CHEM", "MATHS", "BIO" };

The pstr[4] portion of the declaration indicates an array of four elements. The char * portion
of the declaration indicates that each element of array pstr is of type "pointer to char.
Although it appears that these strings are being placed in the pstr array, only pointers are
actually stored in the array, as shown in figure below. Each pointer points to the first character of
its corresponding string. Thus, even though the pstr array is fixed in size, it provides access to
character strings of any length. This flexibility is one example of C++'s powerful data-structuring
capabilities.

pstr[0]

pstr[1]

pstr[2]

pstr[3]

\0

1020

1021

1022

1023

\0

2020

2021

2022

2023

2024

\0

3020

3021

3022

3023

3024

3025

\0

4020

4021

4022

4023

1020

2020

3020

4020
pstr[ ] array

27

Program to Illustrate string pointer pointing to several strings:


#include <iostream.h>
void main()
{
char *pstr[]={ "PHY", "CHEM", "MATHS", "BIO" };
for(int i=0;i<4;i++)
{
cout<<pstr[i]<<"\t";
cout<<&(pstr[i])<<"\t";
cout<<"size of (pstr[i]): "<<sizeof(pstr[i])<<endl;
cout<<*pstr[i]<<"\t";
cout<<&(*pstr[i])<<"\t\t";
cout<<"size of (*pstr[i]): "<<sizeof(*pstr[i])<<"\n\n";
}

The expected OUTPUT is as below:


PHY
P

0x24cf241c
PHY

size of (pstr[i]) : 4
size of (*pstr[i]): 1

CHEM
C

0x24cf2420
CHEM

size of (pstr[i]) : 4
size of (*pstr[i]): 1

MATHS
M

0x24cf2424
MATHS

size of (pstr[i]) : 4
size of (*pstr[i]): 1

BIO
B

0x24cf2428
BIO

size of (pstr[i]) : 4
size of (*pstr[i]): 1

Note: we cannot perform pointer arithmetic in the above program as array elements (of the
array pstr) are not stored in contiguous memory locations.
----------------------------------------------------------------------------------------------------------------------------- --

POINTERS AND FUNCTIONS:


We know that a function is a user defined operation that can be invoked by passing the values of
arguments (call by value method) or references to arguments (call by reference method).
The call by reference method can itself be used in two ways:

by passing references

by passing the pointers

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 <iostream.h>
void main()
{
void swap(int* , int*);
int a=10,b=20;
cout<<"original values are:"<<endl;
cout<<"a="<<a<<"\t b="<<b;
swap(&a,&b);

// prototype

// function call

cout<<"\nvalues after swapping are:"<<endl;


cout<<"a="<<a<<"\t b="<<b;
}
Here, pointers x and y are
are initialized with &a and &b resp.
i.e. *x=&a , *y=&b
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}

The OUTPUT of the program is as below:


original values are:
a=10
b=20
values after swapping are:
a=20
b=10

// function definition

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 <iostream.h>
void main()
{
int *bigger(int*, int*);
// prototype
int a,b,*big;
cout<<"Enter two integers:"<<endl;
cin>>a>>b;
big= bigger(&a, &b);

// function call

cout<<"\nThe bigger value is:"<<*big;


}
int *bigger(int *x, int *y)
{
if(*x>*y)
return(x);
else
return(y);
}

The OUTPUT of the program is as below:


Enter two integers:
4
9
The bigger value is:9

// note that return(x) is same as return(&x)

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 <iostream.h>
struct stu
{
int rollno;
char name[20];
float marks;
};
void main()
{
stu s1={1, "mohan", 76},*pstu;
// declaration
pstu=&s1;
// initialization
cout<<"The details of S1 are:"<<endl;
cout<<pstu->rollno<<"\t"<<pstu->name<<"\t"<<pstu->marks;
}

The OUTPUT of the above program is:


The details of S1 are:
1
mohan
76

Note that the members of structures are accessed either by using dot operator (.) and
using the arrow operator (->).

Accessing members of structures


using dot operator (.)

using the arrow operator (->) in


case of structure pointers

s1.rollno;
s1.name;
s1.marks;

pstu-> rollno;
pstu->name;
pstu->marks;

31

Self-Referential Structures:
A structure having a member element that refers to the structure itself is known as selfreferential 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 *optr;

// s1 is an object of class student


// optr is the object pointer.

Accessing public members of a class


By using dot operator (.) in case
while accessing the class members
using an object
s1.getdata();
s1.display();

by using the arrow operator (->)


in case while accessing the class
members using an object pointer.
optr-> getdata();
optr -> display();

32

e.g. Consider the program :


#include <iostream.h>
#include<string.h>
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<<rollno<<"\t"<<name<<"\t"<<marks; }
};
void main()
{
stu s1;
stu *optr=&s1;
// object pointer declared & initialized
optr->getdata(1, "rohan", 76);
cout<<"The details of object S1 are:"<<endl;
optr->display();
}

The OUTPUT of the above program is:


The details of object S1 are:
1
rohan
76

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 <iostream.h>
#include<string.h>
class stu
{
char name[20];
public:
stu(char *n)

Note that this can be used only within a member


function and it stores the address of the calling object

{ strcpy(name,n); }
void display()
{ cout<<this->name<<endl; }
// here, cout<<this->name has the same effect as cout<<name
};
void main()
{
stu s1("sohan"), s2("rohan"), s3("mohan");
s1.display();
s2.display();
s3.display();
}

The OUTPUT of the above program is:


sohan
rohan
mohan

The this pointer is useful in returning the object (address) of which the function is a member.

----------------------------------------------------------------------------------------------------------------------------- --

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
Reversing
Merging

Searching
Copying

Sorting
Concatenation

Traversal

Types of Data Structures


Linear Data structures

Non Linear Data Structures

elements form a sequence


relationships

represent hierarchical

Array
Linked List
Stack (LIFO List)
Queue (FIFO List)

Trees
Graphs

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 )

Address of a[i][j] = B + W ( j *row + i )

Or

Or

Address of a[i][j] = B + W [( i Lr)* col + ( j-Lc)]

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

2000

50

2004

2002

70
2004

2006

99

NULL

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;
node *link;
};

// data part
// 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
PUSH
POP

DESCRIPTION
To insert an element at the top of the stack
To remove an existing element from the top of the stack

STACK IMPLEMENTATION
Static implementation (using arrays)

PUSH and POP function definitions


(using arrays)
void stack :: push ( int item )
{

Dynamic implementation (using pointers)

PUSH and POP function definitions


(using pointers)
void stack :: push ( int item )
{

if ( top == MAX - 1 )
{
cout << "Stack is full" ;
return ;
}
top= top+ 1 ;
arr[top] = item ;

node *temp ;
temp = new node ;

// dynamic allocation

temp -> data = item ;


temp -> link = top ;
top = temp ;

//top pointer is set

void stack :: pop( )


{
if ( top == -1 )
{
cout << "Stack is empty" ;
return NULL ;
}

void stack :: pop( )


{
if ( top == NULL )
{
cout<< "Stack is empty" ;
return NULL ;
}
node *temp ;

int d = arr[top] ;
top = top - 1 ;
cout<<Popped item is:<<d;

temp = top ;
int d = temp -> data;
cout<<Popped item is:<<d;
top = top -> link ;
delete temp ;

}
}

//resetting the top pointer


//freeing the popped node

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

Operation
Insertion
Deletion

DESCRIPTION
To add a new element at the rear
To remove an element from the front

QUEUE IMPLEMENTATION
Static implementation (using arrays)

Dynamic implementation (using pointers)

INSERT and DELETE function definitions


(using arrays)
void queue :: insertq ( int item )
{
if ( rear == MAX - 1 )
{
cout << "Queue is full" ;
return ;
}

INSERT and DELETE function definitions


(using pointers)
void queue :: insertq ( int item )
{
node *temp ;
temp = new node ;
// dynamic allocation
temp -> data = item ;
temp -> link = NULL ;

rear = rear + 1 ;
arr[rear] = item ;

if ( front == NULL )
{
rear = front = temp ;
return ;
}

if ( front == -1 )
front = 0 ;
}

rear -> link = temp ;


rear = rear -> link ;
}

void queue :: delq( )


{
if ( front == -1 )
{
cout << "Queue is Empty" ;
return NULL ;
}

void queue :: delq( )


{
if ( front == NULL )
{
cout << "Queue is empty" ;
return NULL ;
}

int d = arr[front] ;
arr[front] = 0 ;
if ( front == rear )
front = rear = -1 ;
else
front = front + 1; ;

node *temp ;
int d = front -> data ;
cout<<deleted item is:<<d;
temp = front ;
front = front -> link ;
delete temp ;

cout<<deleted item is:<<d;


}

//freeing the deleted node

38

Function That Evaluates the Postfix Expression


-----------------------------------------------------------------------------------------------------void postfix :: calculate( )
{
int n1, n2, n3 ;
while ( *s )
{
if ( *s == ' ' || *s == '\t' )
{
s++ ;
continue ;
}

// skip whitespace, if any

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 << "Unknown operator" ;
exit ( 1 ) ;
}
push ( n3 ) ;
}
s++ ;
}
}

---------------------------------------------------------------------------

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
data stored in the form of
characters (ASCII Code)
each line terminated with a special
Character known as end-of-line
(EOL) character

Binary Files
data stored in the form of
sequence of bytes, i.e. 0s & 1s
there is no 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:
Type of stream
input stream (Read mode)
output stream (Write mode)
input/output stream (R/W mode)

Associated Class
ifstream
ofstream
fstream

--------------------------------------------------------------------------------------------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.

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

ios::in
ios::out
ios::ate

Open for reading (default for ifstream)


Open for writing (default for ofstream)
Start reading or writing at the end of file (AT End)

ios::app
ios::trunk
ios::nocreate
ios::noreplace

Start writing at end of file (APPend)


Truncate file to zero length if it exists (TRUNCate)
Error when opening if file does not already exist.
Error when opening for output if file already exist, unless ate
or app is set.
Open file in binary (not text) mode.

ios::binary

Associated
Class

ifstream
ofstream
ofstream
ifstream
ofstream
ofstream
ofstream
ofstream
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 endof-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
(input pointer)

put pointer
(output pointer)

Used for reading the


contents of a file location

Used for writing to a given


file location

NOTE: Each time an input or output operation takes place; the concerned pointer is
automatically advanced.
Open for reading only
I

Open in app mode


I

GET POINTER

Open for writing only

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
seekg()
seekp()
tellg()
tellp()

Description
Moves the get pointer or input pointer to a specified location
Moves the put pointer or the output pointer to a specified
location
Gives the current position of the get pointer
Gives the current position of the put pointer

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<fstream.h>
void main()
{ ofstream outfile(poem.txt);
outfile<<I love my country;
outfile<<\n I love my India;
}

// create file for output


// send text to file

NOTE:

1) In the above program, getfrom operator << is appropriately overloaded; we used it to write text
to the file.
2) When the program terminates, the outfile object goes out of scope. This calls the destructor,
which closes the file. i.e. we dont need to close the file explicitly.

3) When the program is executed, the lines of text specified in the program are written into the

file. There is no output to the screen. To see what the text is in the file poem.txt, goto Dos
shell & type the following: type poem.txt and press enter; it will show the file contents.

TIP: poem.txt is the physical name of the file & outfile is the logical name of the file.
--------------------------------------------------------------------------------------------EXAMPLE 2: READING A FILE:
We can read the above file at a later stage as (first we must create an object of
class ifstream)
#include<fstream.h>
void main()
{ const int max=80;
char str[max];
ifstream infile(poem.txt);
while(infile)
// until end of file
// while(!infile.eof()) can also be written
{ infile.getline(str, max);
//reads a line until \n is encountered
cout<<str;
// displays it
}
}

******************************
The same prog can be written using get( ) member function:
#include<fstream.h>
void main()
{ char ch;
ifstream infile(poem.txt);
while(infile)
// until end of file
// while(!infile.eof()) can also be written
{ infile.get(ch);
//reads a character
cout<<ch;
// displays it
}
}

OUTPUT:

I love my country
I love my India

----------------------------------------------------------------------------------------------------------------

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<fstream.h>
#include<iostream.h>
struct student
{ int roll ;
char name[30];
char address[60];
};
int main()
{ student s;
ofstream fout;
fout.open("student.dat");
cout<<"\n Enter Roll Number :";
cin>>s.roll;
cout<<"\n Enter Name :";
cin>>s.name;
cout<<"\n Enter address :";
cin>>s.address;
fout.write((char *)&s, sizeof(student));
fout.close();
return 0;
}
-----------------------------------------------------------------------------------------------------

Example To Read data from a binary File using read( ) member function

#include<fstream.h>
#include<iostream.h>
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<<"\n Roll Number :"<<s.roll;
cout<<"\n Name :"<<s.name;
cout<<"\n Address :"<<s.address;
fin.close();
return 0;
}
-----------------------------------------------------------------------------------------------------

45

Example To Write Class object in a file


#include<fstream.h>
#include<iostream.h>
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
{ cout<<"\n Enter Roll :";
cin>>roll;
cout<<"\n Student name :";
cin>>name;
cout<<"\n Enter Address :";
cin>>address;
}
void student:: write_data()
{ cout<<"\n Roll :"<<roll;
cout<<"\n Name :"<<name;
cout<<"\n Address :"<<address;
}
int main()
{
student s;
ofstream fout;
fout.open("student.dat");
s.read_data();
// member function call to get data from Keyboard
fout.write((char *)&s, sizeof(student)); // write object in file
fout.close();
return 0;
}
------------------------------------------------------------------------------------------------------

Example To Read Class object from a binary file


#include<fstream.h>
#include<iostream.h>
class student
{
int roll ;
char name[30];
char address[60];
public:
void read_data( );
void write_data( );
};

// member function prototype


// member function prototype

46
void student::read_data( )
// member function definition
{
cout<<"\n Enter Roll :";
cin>>roll;
cout<<"\n Student name :";
cin>>name;
cout<<"\n Enter Address :";
cin>>address;
}
void student:: write_data()
{
cout<<"\n Roll :"<<roll;
cout<<"\n Name :"<<name;
cout<<"\n Address :"<<address;
}
int main()
{
student s;
ifstream fin;
fin.open("student.dat");
fin.read((char *)&s, sizeof(student));
s.write_data();
fin.close();
return 0;
}
------------------------------------------------------------------------------------------------------

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
Physical data model

Network Model (directed graphs)

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
Relation
Tuple
Attribute
Cardinality
Degree or Arity
Domain
Primary key
Foreign Key

Their Meanings
Table
Row (or record)
Column ( or field)
No. of rows
No. of columns
Set of legal values
Unique identifier
Identifier used to reference
another table.

To understand these terms, let us consider an instance of a STU relation.

Attributes

Primary
key

domains

Attribute
names
Stu_id

Tuples

Stu_name

Age

City

Gender

CS01

Aman

17

Vizag

CS02

Raman

18

Chennai

CS03

Simran

21

Hyderabad

CS04

Boman

16

Mumbai

CS05

Anjali

18

New Delhi

CS06

Rahul

20

Chandigarh

c
a
r
d
i
n
a
l
i
t
y

degree

In the above STU Relation, there are 6 tuples (i.e. cardinality = 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).

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.

Das könnte Ihnen auch gefallen