C++16 (Unit 1 and 2) - Final
C++16 (Unit 1 and 2) - Final
UNIT-I
Evolution of C++
SIMULA67
C
Simulation programming language
ALGOL 68
Algorithmic Language C WITH CLASSES
1
There are several fundamental concepts in object- oriented programming is shown below
figure.
Objects Polymorphism
C++
Reusability
Data abstraction
Delegation
Encapsulation
Genericty
Inheritance
Figure: Features of
object- oriented programming
1) Objects:
Objects are the primary run-time entities in an object-oriented programming
They may represent a person, a place, any data item related to program, including user-
defined data types.
Object: STUDENT STUDENT
DATA Total
Name
DOB
Marks
Average
…………
FUNCTIONS
Total
Average Display
Display
…………
2
Messages send (requesting bank balance)
2) Classes
A class is a collection of objects of similar types.
Once a class has been defined, we can create any number of objects belonging to that
class
Classes are user-defined data types and behave like the built-in type of a programming
language.
For example Fruit mango;
3) Method
An operation (or) action required for an object or entity when coded in a class is called a
method.
The operations that are required for an object are to be defined in a class.
The data member of any class uses its member functions or methods to perform
operations.
class A
{
private:
data member 1;
data member 2; Members
…………………
data member n;
public
method 1 () { }
method 2 () { } Methods (or)
……………………… Member functions
method n () { }
}
Figure: Representation of methods
4) Data Abstraction
Abstraction refers to the act of representing essential features without including the
background details or explanations.
3
Classes use the concept of abstraction and are defined as a list of abstract attributes or
data members such as size, weight and cost, and function to operate on these attributes.
Since the classes use the concept of data abstraction, they are known as Abstract Data
Types (ADT).
5) Encapsulation
The packing of data and functions into a single components is known as encapsulation
(Using classes)
The data is not accessible to the outside world or function, and only those functions
which are wrapped (or packed) in the class can access it.
Data hiding can be accomplished
Each member in the class may be private or public.
6) Inheritance
Inheritance is the method by which objects of one class get the properties of objects of
another class.
It provides the idea of reusability.
Deriving a new class from existing one without changing it.
Figure: Inheritance
7) Polymorphism
Polymorphism allows the same function to act differently in different classes (or)
Polymorphism means that some code or operations or objects behave differently in
different contexts
4
Polymorphism, a Greek term means the ability to take more than one form.
The behavior depends upon the type of data used in the operation.
For example, the + (plus) operator in C++:
4+5 integer addition
3.14 + 2.0 floating point addition
Str1 + Str2 string concatenation!
The process of making an operator to exhibit different behaviors in different instances is
knows as operator overloading
Using a single function name to perform different types of tasks is known as function
overloading
Shape
Draw ( )
Figure: Polymorphism
9) Message Passing
An object-oriented program consists of a set of objects that communicate with each other
(sending and receiving information).
The following basic steps:
Declaring classes that define objects and behavior
Declaring objects from classes.
Implementing relation between objects.
Communication operator
Message Data
Figure: Message passing
For example, employee . salary(name);
10) Reusability
Object-oriented technology allows reusability of the classes by extending them to other
classes using inheritance. Thus, reusability saves times.
CLASS A
CLASS B 5
CLASS C
Figure: Reusability
11) Delegation
In OOP, two classes can be joined either by- inheritance or delegation, which provide
reusability of the class
One class can be derived from other class and relationship between them is known as
kind of relationship, for example figure(a)
One class is used as data member in other class, such composition is known as
delegation( has a relationship) as shown figure(b)
CLASS A { }; CLASS B { };
CLASS C
{
A a; / / Object of class A as data member
B b; / / Object of class B as data member
};
12) Genericity
The declaration of variables without specifying exact data type.
The complier identifies the data type in run-time.
The template features in C++ allows generic programming.
6
A library is a set of .obj files, which is linked to the program
Streams in C++
C++ supports a number of Input/Output operations to read and write operations
The stream is an inter-mediator between I/O devices and the user
The stream is flow of data in bytes in sequence
If data is received from input devices in sequence then it is called as source stream.
The data is passed to output devices then it is called as destination stream
Keyboard Monitor
Stre
am
Disk Disk
Figure: Streams and I/O devices
PROGRAM
7
Syntax
cin >> v1>>v2>>v3………...>>vn ;
Where, v1,v2…vn are variables
Example
int i;
float f;
char c;
cin>>i>>f>>c;
Output stream:
The cout statement is used to display data on the screen
It uses cout as object
The cout statement uses << (insertion operator) before variable name
The cout are pre-defined stream
The operator << is overloaded in the ostream class
Syntax cout << v1<<v2<<v3………...<<vn ;
Pre-defined streams (or) Standard I/O objects (or) I/O global objects
The C++ has a number of pre-defined streams.
These streams are automatically activated when the program execution starts.
1. cin
2. cout
3. clog
4. cerr
1. cin
8
It handles input from input devices usually from keyboard.
get( )
getline( )
cin read( )
putback( )
gcount( )
a. get( )
Reads a single character from the stream
Example
char c;
c = cin.get( ); // or cin.get(c)
cout<<c;
b. getline( )
The getline( ) function reads the string including white space.
The getline( ) statement terminates the accepting data when enter is pressed.
Example
char c[15];
c = cin.gelinet(c, 15);
cout<<c;
c. read( )
Read ( ) is used to read text through the keyboard.
The read ( ) continues to read till the number of characters entered are equal to the size
specified.
Example
char c[15];
c = cin.read (c, 15);
9
cout<<c;
d. putback( )
The putback( ) replaces the given character into the stream
Example
char c
while( cin.read (c)
{
if(c= = ’ ‘)
cin.putback(‘*’);
else
cout<<c;
}
Output:
One Two Three
One…Two... Three
2. cout
It passes data to output devices such as monitor and printers. Thus, it controls output.
put( )
cout write( )
flush( )
Figure: Frequently used unformatted output functions with cout object
a. put( )
Writes or Displays a single character at a time on the screen.
10
Example
char c[15];
c = cin.read (c, 15);
cout.write(c, 15);
c. flush( )
It is used to flushing(cleaning) the buffer.
Syntax cout.flush ( );
Example
cout<<”test”;
cout.flush( );
3. clog
It controls error messages that are passed from buffer to the standard error device.
Example
clog<<”\n STREAM”;
4. cerr
It controls the un-buffered output data. It catches the error and passes to standard error
device monitor
Example
cerr<<”\n STREAM”;
Stream classes
C++ streams are based on class and object theory.
C++ has a number of stream classes that are used to work console and file operations.
These classes are known as stream classes.
All these stream classes are declared in the header file iostream.h.
ios
The above figure, classes’ istream and ostream are derived classes of base class ios by
using multiple inheritances.
The streambuf class handles the buffer by provoding the facilities to flush clear and pour
the buffer.
The ios class has an ability to handle formatted and unformatted I/O operations.
Example
cin.peek = =’#’;
Where cin as object and ‘#’ is a symbol to be caught in the stream
2. ignore ( )
12
The member function ignore ( ) has two arguments, maximum number of characters to
avoid, and the termination character.
Syntax
cin.ignore ( maxno, ‘ character ‘);
Example
cin.ignore (1,’#’);
The statement ignore 1 character till ‘#’ character is found
Example program
#include<iostream.h>
#include<conio.h>
int main()
{
char c;
clrscr();
cout<<"\n Enter text (press F6 to end";
while(cin.get(c))
{
cout<<c;
while(cin.peek( )=='#')
cin.ignore(1,'#');
}
return 0;
}
Input
Enter text (press F6 to end
ABCDEFG###HIJK^Z
Output
ABCDEFGHIJK
Manipulator
The output format can be controlled using manipulators.
The header file iomanip.h has a set of functions.
The manipulator can be used with cout( ) statement as given below
cout<<m1<<m2<<v1;
Here m1 and m2 are two manipulators and v1 is any valid C++ variable.
1. endl
2. ends
3. setw
4. setbase
5. setprecision
6. setfill
7. ws
8. hex, oct, dec
13
9. flush
10. setiosflags and resetiosflags
1. endl
Inserts or splits a new-line character
Syntax
endl;
Example
cout <<”welcome”<<endl;
cout <<”hai”;
Output
welcome
hai
2. ends
Add null character ('\0') to close an output string
Syntax
ends;
Example
cout << "a";
cout << "b" << ends;
cout << "c" << endl;
Output
ab c
3. setw( )
setw( ) will set field width
Syntax
setw( num); (or) setw(int variable);
Example
cout<<setw(10)<<”welcome”;
cout<<setw(int n)<<”Hello”; // n=50
Output
Welcome
Hello
4. setbase( )
Sets the base of the number system
dec, if base is 10
hex, if base is 16
oct, if base is 8
Syntax
setbase(base);
Here, base is dec, hex or octal
14
Example
cout<<setbase(8);
cout<<100;
Here, the field width is fixed to n;
Output
144 (100 LCM 8)
5. setprecision( )
The precision determines the maximum number of digits that shall be output on insertion
operations to express floating-point values, counting both the digits before and after the decimal
point.
Syntax
setprecision (num); (or) setprecision (int variable);
Example
cout << setprecision (3) << 3.14159;
cout << setprecision (1) << 3.14159;
Output
3.141
3.1
6. setfill( )
The fill character is used in output insertion operations to fill spaces when results have to
be padded to the field width.
Syntax
setprecision (‘single character’);
Example
cout << setfill ('x') << setw (10);
cout << 77;
Output
xxxxxxxx77
7. ws
Used to omit the leading whitespaces present before the first field
Syntax
cin>>ws;
Example
char s[256];
cin>>ws;
cin.getline(s,256);
cout<<s;
Output
ABC
ABC
15
cout <<hex<<x<<endl;
cout<<oct<<x<<endl;
cout<<dec<<x<<endl;
Output
99
231
153
9. flush
Flushes the buffer stream
Syntax
cout.flush( );
Example
cout<<”test”;
cout.flush( );
Example Program
#include <iostream.h>
#include <iomanip.h>
#include<conio.h>
ostream & tab(ostream & ostr)
{
cout<<" \ t ";
return ostr;
}
void main( )
{
clrscr( );
cout<<1<<tab<<2<<tab<<3;
getch( );
}
Output
1 2 3
Example
ostream & tab(ostream & ostr, int iw)
{
for (int k=0;k<=iw;k++)
cout<<”\t ”;
return ostr;
}
Example
IOMANIPdeclare(w_p);
static ostream & tab(ostream & ostr, w_p w_p)
{
17
ostr.width(w_p.w);
ostr.precision(w_p.p);
return ostr;
}
UNIT-II
Introduction to C++
18
Uses of C++ language
C++ is used by programmers to create computer software.
It is used to create general systems software, drivers for various devices, software for
servers and software for specific applications and also widely used in the creation of
video games.
Tokens
The smallest individual units in a program are known as tokens
Types of tokens
The C++ program contains various components. The compiler identifies them as tokens
Keywords
Variables
Tokens Operators
Constants
Figure: Types of tokens
Special Character
1. Keywords
C++ reserves a set of 63 words for its own use. These words are called keywords.
Each of these keywords has a special or pre-defined meaning in the C++ language.
This cannot be changed and used as names for the variables in a program.
14 do Looping construct
20
25 goto Jump to a different part of the program
21
50 true The Boolean value of true
2. Variables
A variable used to store values
Every variable has own memory location.
The variables can be of any data-type ( int, char, float, float etc.,)
The variable can hold single value at a time of its type
The name of a variable is called an identifier.
The programmer can change contents of a variable. Thus, the identifier that holds varying
values is called variable.
Variable Declaration
C++ permits declaration of variables anywhere in the program
22
(a) data-type v;
Syntax
(b) data-type v1, v2, v3……v n;
Example Program
#include <iostream.h>
#include<conio.h>
void main( )
{
clrscr( );
cout<<"Enter any integer values"<<endl;
int n;
cin>>n;
cout<<n;
cout<<"\n Enter any float values";
float f;
cin>>f;
cout<<f;
getch( );
}
Output
Enter any integer values 12
12
Enter any float values 4.3
4.3
Variable Initialization (or) Initializing variables
Initialization of variables can be done using the assignment operator (=). The variables
can be initialized while declaration itself.
Syntax:
data-type variable_name = values;
Example:
float f=3.2;
int a, b, c, d;
a = b = c = d = 5;
Example program
#include <iostream.h>
23
#include<conio.h>
void main()
{
clrscr();
int a,b,c,d;
a=b=c=d=5;
cout<<"a="<<a<<"b="<<b<<"c="<<c<<"d="<<d;
getch();
}
Output
a =5 b =5 c =5 d=5
Dynamic initialization
The declaration and initialization of variable in a single statement at any place in the
program is called as dynamic initialization
Example
#include <iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"Enter radius";
int r;
cin>>r;
float area=3.14*r*r;
cout<<"\n Area="<<area;
getch(); Note:
} Area of circle= π × r2
Output: Enter radius 3 π =3.14159…
Area = 28.26
3. Operators
An operator is a symbol that specifies an operation to be performed on the operands.
All C operators are valid in C++ also.
a) Arithmetic operators
b) Relational operators
c) Logical operators
d) Assignment operators
e) Increment and decrement operators
f) Conditional (or) Ternary operator
g) Bitwise operators
h) Special operators
24
In addition, C++ introduces some new operators are
Example:
a+b
Where ‘+’ is operator and ‘a’, ’b’ are the operands
a) Arithmetic operators
It carryout basic arithmetic operations
b) Relational operators
Relational operators are used to compare two or more operands
c) Logical operators
Logical operators are used to combine the result of two or more conditions
25
d) Assignment operators
Assignment operator are used to assign a value or an expression or a value of a variable
to another variable
Syntax:
variable = expression (or) value;
Example
k=10;
y=a+b;
n=y;
Example
int a=5,b=3,big;
big= a > b? a : b;
cout<<”Biggest no is...”<<big;
Output
Biggest no is...5
g) Bitwise operators
Bitwise operators are used to manipulate the data at bit level. It operates on integers only
Operators Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
26
<< Shift left
>> Shift right
~ One’s complement
Example
h) Special operators
The C++ language supports some of the special operators given below
Operators Meaning
, Comma operators
sizeof( ) Size of operators
& and * Pointer operators
. and Member selection operators
Syntax sizeof(variable);
Example int a;
cout<<sizeof(a);
Output 2
28
i. Extraction operator (>>)
The cin statement uses >> (extraction operator) before variable name
The operator >> is overloaded in istream class
Example
int i;
float f;
char c;d
cin>>i>>f>>c;
Example
int i;
float f;
char c;
cin>>i>>f>>c;
cout<<i<<f<<c;
Example
#include<iostream.h>
#include<conio.h>
int m=10; //global variable
void main( )
{
int m=15; //local variable
clrscr( );
cout<<::m<<endl; //cin>>::m;
cout<<m;
getch( );
}
Output
10
15
29
The new operator is used to create objects of any data-type.
Example
char *c; // char *c[10]; Error
c= new char [10];
v. Memory release operator (delete)
The delete operator is used to destroy objects of any data-type.
Syntax delete [ ] pointer-variable;
Example
delete[ ] c;
Example
cout<<setw(10)<<”welcome”;
cout<<setw(int n)<<”Hello”; // n=50
Output
Welcome
Hello
4. Constants
The items whose values cannot be changed during the execution of program are called
constants.
C++ supports various types of constants including integers, single characters, float or real
and string constants
C++ has two types of constants:
i. Literal constants and
ii. Symbolic constants
i. Literal constants
A literal constant is directly assigned to a variable.
Example
int n=5;
Where n is a variable of type int and 5 is a literal constant. C++ supports literal constants
are
Types of Constants
Example
const int a=90;
cout<<a; // cin>>a; Error
Output 90
31
b) Real constants
A real constant is made up of a sequence of numeric digits with presence of a decimal
point
Syntax const data-type variable_name = values;
Example
const float f=912.56;
cout<<f; // cin>>f; Error
Output 912.56
c) Single character constants
The character constant contains a single character enclosed in single quotes
Syntax
const data-type variable_name = ‘ values ’;
Example
const char c = ’K’;
cout<<c; // cin>>c; Error
Output K
d) String constant
A string constant is a sequence of characters enclosed in double quotes.
Syntax
const data-type variable_name[size] = “ values “;
Example
const char c[ ] = “welcome” ; // (or) const char c[20] = “welcome” ;
cout<<c; // cin>>c; Error
Output welcome
a) # define
The # define preprocessor directive can be used for defining constants
Example
# define price 152
# define price 63.741
# define price ‘k’
# define price “hai”
32
Here, price symbolic constant contains 152 and it is not mentioned whether the type is
int, char or float.
Example program
#include<iostream.h>
#include<conio.h>
#define price 2.52
void main()
{ cout<<price; }
Output: 2.52
b) The const keyword
We can also define a constant using const keyword
Example
const int price=152;
Example
enum stu {a=5, b=10, c=12 };
Here a,b,c are declared as integer constants with values 5,10 and 12;
Example program
#include<iostream.h>
#include<conio.h>
enum stu{ a=5,b=10,c=12};
void main()
{
cout<<a<<b<<c;
}
Output 5 10 12
5. Special character
Identifiers
Identifiers are names of variables, functions and array etc.
They are user-defined names, consisting of a sequence of letters and digits, with a letter
as a first character.
Lower case letters are preferred.
Upper case letters are also permitted.
The underscore ( _ ) symbol can be used as an identifier.
Underscore is used to link two words in long identifiers.
Rules
The identifier name must begin with a character and should not start with a digit. There
should not be any space between the characters in the variable but underscore is allowed
The identifier name should not be a C++ keyword
The identifier name may be a combination of upper and lower characters. For example
variable suM, sum and Sum are not the same.
Variable Declaration
C++ permits declaration of variables anywhere in the program
(c) data-type v;
Syntax
(d) data-type v1, v2, v3……v n;
Example Program
#include <iostream.h>
#include<conio.h>
void main( )
{
clrscr( );
cout<<"Enter any integer values"<<endl;
int n;
cin>>n;
cout<<n;
getch( );
}
34
Output
Enter any integer values 12
12
Example program
#include <iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c,d;
a=b=c=d=5;
cout<<"a="<<a<<"b="<<b<<"c="<<c<<"d="<<d;
getch();
}
Output
a =5 b =5 c =5 d = 5
Dynamic initialization
The declaration and initialization of variable in a single statement at any place in the
program is called as dynamic initialization
Example
#include <iostream.h>
#include<conio.h>
void main()
{
cout<<"Enter radius";
int r;
cin>>r;
float area=3.14*r*r;
cout<<"\n Area="<<area;
Note:
Area of circle= π × r2 35
π =3.14159…
getch();
}
Output: Enter radius 3
Area = 28.26
Expression
An expression is a combination of operators, constants and variables arranged as per the
rule of the language. It may also include function calls and return values.
An expression may consist of one or more operands, zero or more operators to produce a
value
Types of expression
1. Constant expression
2. Integral expression
3. Float expression
4. Pointer expression
5. Relational expression
6. Logical expression
An expression may also use combinations of the above expressions. Such expressions are
known as compound expression
1. Constant expression
Constant expression consists of only constant value.
Example
15
20+5/2.0
‘x’
2. Integral expression
Integral expressions are those which produce integer results after implementing all the
automatic and explicit type conversion
Example
m
m*n-5
Where m and n are integer variables
3. Float expression
Float expressions are those which, after all conversions, produce floating-point results
Example
x+y
x*y/10
Where x and y are floating-point variables
4. Pointer expression
Pointer expressions produce address values
Example
&m
36
ptr
Where m is a variable and ptr is a pointer
6. Logical expression
Logical expressions combine two or more relational expressions and produces bool type
results
Example
a >b && x= =10
x= =12 | | y= =5
37
Control structure
In a program all the instructions(statements) are executed sequentially by default( no
repetition)
To change the execution order of statements based on condition or to repeat a set of
statements until certain conditions are satisfy. In such situation control structure are very
useful
Control structures are used to alter the flow of execution of the program
Control Structures "Statements used to control the flow of execution in a program"
1. The if statement
2. The if else statement
3. The switch statement
1. The if statement
The if statements is a decision making statement
It is used to control the flow of execution of the statements and also used to test logically
whether the condition is true or false
If the condition is true returns 1 otherwise 0 False
Conditio
Syntax
n
if (condition)
{ True
True statements;
} True statements
void main( )
{
TRUE FALSE
if ( condition or expression)
{
Statement1;
Statement1;
Statement3;
}
void main( )
{
TRUE FALSE
if ( condition or expression)
{
Statement1;
Statement1;
}
else
{
Statement3;
Statement3;
}
}
Example
int age=18;
if(age>=17)
cout<<” You are eligible for voting”;
else
cout<<” You are not eligible for voting”;
Output
You are not eligible for voting
39
4. The switch statement
The switch statement is a multi-way branch statement and an alternative to if-else-if
ladder in many situations.
The switch statement requires only one argument, which then checked with number of
case options.
If the value is matched with a case constant then that case constant is executed until a
break statement is found or end of switch block is reached.
If not then simply default is executed
The default block must not be empty.
Every case statement terminates with colon (:)
The break statement is used to stop execution
Syntax
switch (expression or constant)
switch
{
case constant 1: (expressio
statements; n)
break;
40
Repetitive statement (or) A loop statement
It is used to execute one statement or more than one statements multiple times based
upon some condition
The repetitive statements always having initialize variable and increment values will
appear
There are several types of repetitive statements
1. The while loop
2. The do while loop
3. The for loop
Syntax
while(condition) False
{ Conditio
………………. n
body of the loop; True
……………….
} Body of the loop
Output
The sum of numbers up to 10 is 55
Conditio
n
do
{
……………….
body of the loop;
………………. True
}while(condition);
Output
The sum of numbers up to 10 is 55
Syntax
for( initialization; condition; increment or decrement)
{
……………….
body of the loop;
……………….
}
i. Initialization:
It is used to initialize (value) variable
ii. Condition
It is used to test the condition
42
Initialization
False
Conditio
n
True
Increment or decrement
Output
The sum of numbers up to 10 is 55
Pointers
A pointer is a variable; it may contain the memory address of another variable.
It is declared in the same manner like other variable.
It is always denoted by * operator
Each variable has two attributes: address and value.
Assigning values directly to variable, we can indirectly manipulate a variable by creating
a variable called a pointer, which contains the memory address of another variable
Simply we can define pointers in two ways
First-A pointer is a variable and assign different values to a pointer variable
Second-The value contained by a pointer must be an address which indicates the
location of another variable in the memory
43
So pointer is called as address variable
Syntax
data-type * pointer-variable;
Example
int *a;
char *c;
float *f;
Arrays
An array is a collection of similar data items that are stored under a common name.
A value in an array is identified by index or subscript enclosed in square brackets with
array name
The individual data items can be integers, floating point numbers, characters and soon.
Arrays can be classified into
1. One-Dimensional arrays
2. Two-Dimensional arrays
3. Multi-Dimensional arrays
i. One-Dimensional arrays
44
The collection of data items can be stored under a one common variable name using only
one subscript; such a variable is called the one-dimensional array
Syntax
data_type array_variable[size or subscript];
Example
int n[5];
Where ‘n’ is the array name and it reserved 5 subscripts of memory as shown below
n
n[0];
n[1];
n[2];
n[3];
n[4];
Syntax
data_type array_variable [row size] [column size];
Example
int n[3][3];
Where ‘n’ is the name of the array with 5 subscripts of integer data types
Syntax
data_type array_variable [row size] [column size] = {values};
Example
int n[4][2]={
{66, 80},
{54, 67},
{75, 42},
{35, 12 }
};
45
iii. Multi-Dimensional arrays
The collection of data items can be stored under a one common variable name used three
or more subscripts; such a variable is called the three-dimensional array
Syntax
data_type array_variable [size 1] [size 2] [size 3];
Example
int n[3][3][3];
Syntax
data_type array_variable [size 1] [size 2][size 3] = {values};
Example
int arr[3][3][3]=
{
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
46