0% found this document useful (0 votes)
23 views46 pages

C++16 (Unit 1 and 2) - Final

C++ is an object-oriented programming language developed by Bjarne Stroustrup in the early 1980s, combining features from Simula67 and C. The document outlines fundamental OOP concepts such as objects, classes, methods, inheritance, polymorphism, and encapsulation, along with input/output operations in C++. It also covers stream classes and manipulators for controlling output format.

Uploaded by

Dhana Sekaran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views46 pages

C++16 (Unit 1 and 2) - Final

C++ is an object-oriented programming language developed by Bjarne Stroustrup in the early 1980s, combining features from Simula67 and C. The document outlines fundamental OOP concepts such as objects, classes, methods, inheritance, polymorphism, and encapsulation, along with input/output operations in C++. It also covers stream classes and manipulators for controlling output format.

Uploaded by

Dhana Sekaran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 46

C++

UNIT-I

Evolution of C++

 C++ is an object oriented programming(OOP) language


 Bjarne Stroustrup at AT & T Bell Laboratories, Murry Hill, New Jersey (USA)
developed it in the early eighties of twentieth (20th) century.
 Stroustrup, a master of Simula67 and C, wanted to combine the features of both the
languages into more powerful languages that could support OOP with features of C.

SIMULA67
C
Simulation programming language

ALGOL 68
Algorithmic Language C WITH CLASSES

Figure: Evolution of C++


C++

 Various ideas were derived from SIMULA 67 and ALGOL68.


 Stroustrup called the new language ‘C with Classes’.
 In 1983, the name was changed to C++.
 C++ is an extended version of C
 C++ is a superset of C
 All concepts of C are applicable to C++ also
 For developing complicated applications object-oriented language are most convenient
and easy.

Key (or) Basic (or) fundamental concepts of OOP

1
There are several fundamental concepts in object- oriented programming is shown below
figure.

Objects Polymorphism

Classes Dynamic Binding

Method Message Passing

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

Figure: Two ways of representing an object


 Programming problem analyzed in terms of objects and the nature of communication
between them.
 Objects occupy space in memory.
 The state of the object varies according to procedure used it is known as the action
(depends upon the member function) of the object.
 When a program is executed, the objects interact by sending message to one another.

2
Messages send (requesting bank balance)

Customer (Object_1) Account (Object_2)


Messages send (response returned by the object)
Figure: Example of object

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;

Will create an object mango belonging to the class fruit

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

(a) Computer as a single unit (b) Different components of a computer


Figure: Computer and its parts

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.

Red Yellow Blue

Orange Green Violet

Reddish brown Yellowish brown Bluish brown

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 ( )

Circle object Box object Triangle object

Draw (circle) Draw (box) Draw (triangle)

Figure: Polymorphism

8) Dynamic Binding (or) Late binding


Binding means connecting one program to another program that is to be executed in reply
to the call. The code present in the specific program is unknown till executed.

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.

Object . Display (argument);


Object

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 X // Base class

CLASS Y // Base class

(a) Kind of relationship

CLASS A { }; CLASS B { };

CLASS C
{
A a; / / Object of class A as data member
B b; / / Object of class B as data member
};

(b) Has a relationship (delegation)


Figure: Relationship between two classes

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.

Input and Output in C++


 Application generally involve reading a large amount of data from input devices and
sending them to the output devices
 To control such operations every language provides a set of in-built functions
 C++ supports all I/O functions of C
 C++ also has library or iostream library functions.

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

Input Devices Output Devices

Input Stream Output Stream

Extraction of Entry into


Input Data Output Stream

PROGRAM

Figure: C++ Input and output stream

Unformatted console I/O operations


Input stream:
 The cin statement is used to read data through the input device
 It uses cin as object
 The cin statement uses >> (extraction operator) before variable name
 The cin are pre-defined stream
 The operator >> is overloaded in istream class

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 ;

Where, v1,v2…vn are variables


Example
int i;
float f;
char c;
cin>>i>>f>>c;
cout<<i<<f<<c;

>> Variables MEMORY Variables <<

>> Extraction Operator


cin cout
<< Insertion Operator

Input Device Output Device


Figure: Working of cin and cout statement

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( )

Figure: Frequently used unformatted input functions with cin object

a. get( )
 Reads a single character from the stream

Syntax cin.get (variable); (or) variable=cin.get( )

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.

Syntax cin.getline (variable, size);

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.

Syntax cin.read (variable, size);

Example
char c[15];
c = cin.read (c, 15);
9
cout<<c;

d. putback( )
 The putback( ) replaces the given character into the stream

Syntax cin.putback ( ‘ single character ‘ );

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.

Syntax cout.put ( ‘ single character ‘ ); (or) cout.put( variable );


Example
cout.put(‘C’);
cout.put(‘C’). cout.put(‘+’). cout.put(‘+’);
Output: C
C++
b. write( )
 The write( ) function is used to display the string on the screen.
 Displays only specified number of characters given in the second argument or size.

Syntax cout.write (variable, size);

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

istream ostream Streambuf

iostream file buffer


11
Figure: Stream classes

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

istream iostream ostream

istream_withassign iostream_withassign ostream_withassign

Figure: Hierarchy of stream classes

 The classes istream_withassign, ostream_withassign and iostream_withassign append


appropriate assignment operators as shown above figure.

Member functions of istream class


The istream contains following functions that can be called using cin object
1. peek( )
2. ignore( )
1. peek ( )
It returns the succeeding characters without extraction
Syntax
cin.peek = = ‘ single character ‘;

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

8. hex, oct, dec


Displays the number in hexadecimal, octal and decimal format
Example
int x=153;

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( );

10. setiosflags and resetiosflags


Setiosflags:- Format flag set to 1;
resetiosflags:- Removes the flags indicates by 1
Example
int i=100;
cout<<setiosflags(ios::oct);
cout<<i<<endl;
cout<<resetiosflags(ios::oct);
cout<<i<<endl;
Output
144
100

Manipulator with parameters


User-defined manipulators
The programmer can also define his/her own manipulator according to the requirements
of the program.
Syntax
ostream & mname(ostream & ostr)
{
Statement 1;
Statement 2;
return ostr;
}

Here mname is the name of the manipulator


Example
ostream & tab(ostream & ostr)
{
cout<<"welcome";
16
return ostr;
}

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

Manipulator with one parameters


In these types of manipulator, one argument is passed on to the manipulator.

Example
ostream & tab(ostream & ostr, int iw)
{
for (int k=0;k<=iw;k++)
cout<<”\t ”;
return ostr;
}

Manipulators with multiple parameters


In these types of manipulator, multiple arguments are passed on to the manipulator.

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

 C++ is an object oriented programming(OOP) language


 Bjarne Stroustrup at AT & T Bell Laboratories, Murry Hill, New Jersey (USA)
developed it in the early eighties of twentieth (20th) century.
 C++; its first name ‘C with Classes’
 In 1983, the name was changed to C++.
 C++ is an extended version of C
 C++ is a superset of C
 All concepts of C are applicable to C++ also
 For developing complicated applications object-oriented language are most convenient
and easy
 C++ was not released commercially until the late part of 1985
 C++ is a high level language (because object oriented allowed)
 Classes help programmer with the organization of their code and to avoid mistakes C++
programming language.
 C++ complication is considered efficient and fast

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.

Serial Keywords Description


19
Number

1 asm Insert an assembly instruction

2 auto Declare a local variable

3 bool Declare a boolean variable

4 break Break out of a loop

5 case Part of a switch statement

6 catch Handles thrown exceptions

7 char Declare a character variable

8 class Declare a class

9 const Declare immutable data

10 const_cast Cast from const variables

11 continue Bypass iterations of a loop

12 default Default handler in a case statement

13 delete Free memory

14 do Looping construct

15 double Declare a double precision floating-point Variable

16 dynamic_cast Perform runtime casts

17 else Alternate case for an if statement

18 enum Create enumeration types

19 explicit Only use constructors when they exactly match

Tell the compiler about variables defined


20 extern
elsewhere

21 false The Boolean value of false

22 float Declare a floating-point variable

23 for Looping construct

24 friend Grant non-member function access to private data

20
25 goto Jump to a different part of the program

26 if execute code based off of the result of a test

Expand a call to a function rather than calling that


27 inline
function

28 int Declare a integer variable

29 long Declare a long integer variable

30 mutable Override a const variable

31 namespace Partition the global namespace by defining a scope

32 new Allocate dynamic memory for a new variable

33 operator Create overloaded operator functions

34 private Declare private members of a class

35 protected Declare protected members of a class

36 public Declare public members of a class

37 register Request that a variable be optimized for speed

38 reinterpret_cast Change the type of a variable

39 return Return from a function

40 short Declare a short integer variable

41 signed Modify variable type declarations

42 sizeof Return the size of a variable or type

43 static Create permanent storage for a variable

44 static_cast Perform a non-polymorphic cast

45 struct Create a new structure

Execute code based off of different possible values


46 switch
for a variable

47 template Create generic functions

48 this A pointer to the current object

49 throw Throws an exception

21
50 true The Boolean value of true

51 try Execute code that can throw an exception

52 typedef Create a new type name from an existing type

53 typeid Describes an object

54 typename Declare a class or undefined type

A structure that assigns multiple variables to the


55 union
same memory location

56 unsigned Declare an unsigned integer variable

57 using Used to import a namespace

Create a function that can be overridden by a


58 virtual
derived class

Declare functions or data with no associated data


59 void
type

Warn the compiler about variables that can be


60 volatile
modified unexpectedly

61 wchar_t Declare a wide-character variable

62 while Looping mechanism

Eliminate the need to include a template definition


63 export (either by providing the definition in the header
file or by including the implementation file)

Table: C++ Keywords

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;

The identifiers v, v1, v2….v n is a variable


Example
int a;
float c, d, e;

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

Sno Operator Symbol Description


i >> Extraction operator
ii << Insertion operator
iii :: Scope resolution operator
iv delete Memory release operator
v endl Line feed operator
vi new Memory allocation operator
vii setw Field width operator

Example:
a+b
Where ‘+’ is operator and ‘a’, ’b’ are the operands
a) Arithmetic operators
It carryout basic arithmetic operations

Operator Meaning Example


+ Addition 2+9=11
- Subtraction 9-2=7
* Multiplication 2*9=18
/ Division 9/3=3
% Modulo division 9%2=1

b) Relational operators
Relational operators are used to compare two or more operands

Operator Meaning Example Result


< is less than 2<9 True
<= is less than or equal to 2<=2 True
> is greater than 2>9 False
>= is greater than or equal to 3>=2 True
== is equal to 2==3 False
!= is not equal to 2! = 2 False

c) Logical operators
Logical operators are used to combine the result of two or more conditions

Operator Meaning Example Result


&& Logical AND (9>2) && (17>2) True
|| Logical OR (9>2) | | (17= =2) True
! Logical NOT 29!=29 False

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;

e) Increment and decrement operators (or) Unary operators


The increment (++) adds one to the variables and decrement (--) subtracts one from the
variable
Operator Meaning Example
x++ Post increment (first do the operation int a=10;
and then increment) a++=10
++x Pre increment (first increment and ++a=12
then do the operation)
--x Pre decrement (first decrement and --a=11
then do the operation)
x-- Post decrement (first do the operation a--=11
and then decrement)

f) Conditional (or) Ternary operator (?)


Conditional operator itself checks the condition and executes the statement depending on
the condition
Syntax
condition? exp1:exp2;

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

a b a|b a&b a^b ~a


0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
1 1 1 1 0 0

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

Comma operator (,):-


The comma operator is used to separate the statement element such as variables,
constants or expression etc.
Example
int i,j,k;

Size of operator (sizeof( ))


The sizeof( ) is a unary operator, that returns the length in bytes of the specified variable.

Syntax sizeof(variable);

Example int a;
cout<<sizeof(a);
Output 2

Pointer operator (& and *)


&:- This symbol specifies the address of the variable
*:- This symbol specifies the value of the variable
Example
int *a;
*a=10;
cout<<&a<<endl;
cout<<*a;
Output
27
0x8fd7fff4
10

Member selection operators (. and)


These symbols used to access the elements from a structure
Example program (.)
#include<iostream.h>
#include<conio.h>
struct stu
{
int no;
}s;
void main()
{
clrscr();
cin>>s.no;
cout<<s.no;
getch();
}
Output
56
56

Example program (. and)


#include<iostream.h>
#include<conio.h>
struct stu
{
int no;
}s;
void main()
{
struct stu *t;
clrscr();
cin>>s.no;
t=&s;
cout<<t->no;
getch();
}
Output
44
44

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;

ii. Insertion operator (<<)


 The cout statement uses << (insertion operator) before variable name
 The operator << is overloaded in the ostream class

Example
int i;
float f;
char c;
cin>>i>>f>>c;
cout<<i<<f<<c;

iii. Scope resolution operator (::)


 C++ allows flexibility of accessing both (local and global) the variables with same name.
 The global variable are accessing using scope resolution operator (::)

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

iv. Memory allocation operator (new)

29
The new operator is used to create objects of any data-type.

Syntax pointer-variable = new data-type[size];

Here, pointer-variable is a pointer of data-type. The new operator allocates sufficient


memory.

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 program (new and delete)


#include<iostream.h>
#include<conio.h>
void main()
{ char *c;
c=new char[10];
cin>>c;
cout<<c<<endl;
delete[ ] c;
getch( );
}
Output
Welcome
Welcome

vi. Line feed operator (endl)


Inserts or splits a new-line character
Syntax
endl;
Example
cout <<”welcome”<<endl;
cout <<”hai”;
Output
welcome
hai

vii. Field width operator (setw)


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

Integer Real (or) Single String


Constants Float Character Constants
Constants Constants

Figure: literal constant


a) Integer constants
An integer constant formed with the sequence of digits
Syntax
const data-type variable_name = values;

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

ii. Symbolic constants


A symbolic constant is defined in the same way as variable. However, after initialization
of constants the assigned value cannot be altered.
The constant can be defined in the following three ways:
a) # define
b) The const keyword
c) The enum keyword

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;

c) The enum keyword


 Constants can be defined using enum (enumeration) keyword
 An enum is a user-defined type consisting of a set of named constants called
enumerators.

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

Sno Special Sno Special


Meaning Meaning
characters characters
1 + Plus 17 Blank
2 * Asterisk 18 - Minus
3 , Comma 19 / Slash
4 ; Semicolon 20 . Period
5 ‘ Apostrophe 21 : Colon
6 ? Question mark 22 “ Quotation
7 $ Dollar 23 \ Black slash
8 ~ Title 24 % Percent
9 ! Exclamation 25 | Vertical bar
10 < Less than 26 & Ampersand
11 ( Left parenthesis 27 > Greater than
33
12 [ Left bracket 28 ) Right parenthesis
13 { Left brace 29 ] Right bracket
14 # Number sign 30 } Right brace
15 _ Underscore 31 @ At symbol
16 = Equal to 32 ^ Caret

Table: 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;

The identifiers v, v1, v2….v n is a variable


Example
int a;
float c, d, e;

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

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

5. Relational expression (or) Boolean expression


Relational expressions yield results of type bool which takes a value true or false
Example
x<=y
a+b= =c+d
m+n>100

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;
}

Figure: The simple if statements


 If the condition is true, then the true statements are executed.
 If the condition is false, the program skip pass it
Example
38
int age=18; Output
if(age>=18) You are eligible for voting
{ cout<<” You are eligible for voting”; }
2. The if else statement
 It basically two way decision making statements.
 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

Syntax True False


if (condition) Conditio
{ n
True statements;
} True statements False statements
else
{
False statements;
}

void main( )
{
TRUE FALSE

if ( condition or expression)
{
Statement1;
Statement1;

}
else
{
Statement3;
Statement3;
}
}

Figure: The simple if else statements


 If the condition is true, then the true statements are executed.
 If the condition is false, then the false statements are executed.
 The else keyword is optional.

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;

case constant 2: True


statements; case statements break;
break; constant 1
…………………
………………… False
case constant n:
statements; True
break; case break;
statements
default: constant 2
statements;
break;
} False

default statements break;


Example
int a=2;
switch(a)
{
case 1: End switch
cout<<” I am in case 1”; break;
case 2:
cout<<” I am in case 2”; break;
default:
cout<<” I am in case default”; break;
}
Output
I am in case 2

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

1. The while loop


 It is a repetitive control structure, used to execute the statements within the body until the
condition becomes false
 This is the top tested loop (or) The while loop is an entry controlled loop statement,
means the condition is tested first and it is true, body of the loop is executed.
 The condition is first tested, if the condition is true then the body of the loop is executed
until the condition becomes false and the control is transferred out of the loop.
 Loop will not be executed if the condition is false

Syntax
while(condition) False
{ Conditio
………………. n
body of the loop; True
……………….
} Body of the loop

Example (addition of numbers)


int i, sum=0;
while(i<=10)
{
sum = sum + i;
i++;
}
cout<<” The sum of numbers up to 10 is ” <<sum;

Output
The sum of numbers up to 10 is 55

2. The do while loop


 It is a repetitive control structure, used to execute the statements within the body until the
condition becomes false
 This is the bottom tested loop (or) the do-while loop is first executed the body of the loop
then check the condition.
 It executes the body once, after it checks the condition, if it is true the body is executed
until the condition becomes false
 Loop is executed at least once even if the condition is false
Syntax
Body of the loop 41

Conditio
n
do
{
……………….
body of the loop;
………………. True
}while(condition);

Example (addition of numbers)


int i, sum=0; False
do
{
sum = sum + i;
i++;
} while(i<=10);
cout<<” The sum of numbers up to 10 is ” <<sum;

Output
The sum of numbers up to 10 is 55

3. The for loop


 The for loop is another repetitive control structure, and it is used to execute set of
instructions repeatedly until the condition becomes false
 The initialization, increment or decrement and condition checking is done in for
statement only.

Syntax
for( initialization; condition; increment or decrement)
{
……………….
body of the loop;
……………….
}

 The for loop has three parts


i. Initialization:
ii. Condition
iii. Increment or Decrement

i. Initialization:
It is used to initialize (value) variable

ii. Condition
It is used to test the condition

iii. Increment or Decrement


It is used to increment or decrement counter variable

42
Initialization

False
Conditio
n
True

Body of the loop

Increment or decrement

Example (addition of numbers)


int i, sum=0;
for(i=0;i<=10;i++)
{
sum = sum + i;
}
cout<<” The sum of numbers up to 10 is ” <<sum;

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;

Initializing pointer variable


 The process of assigning the address of a variable to a pointer variable is known as
initialization. This can be achieved in C++ through an ampersand (&) sign.
 The ampersand is an address operator, which is used to access the address of a variable
Example
int n, *p;
n = 15;
p = &n;
Where ‘p’ contains the address of variable ‘n’

Variable Value Address


n 15 2001
p 2001 2005
Example Program
#include<iostream.h>
#include<conio.h>
void main()
{
int n,*p;
n=15;
p=&n;
cout<<"\n value of n="<<*p;
cout<<"\n Address of n="<<&p;
}
Output
Value of n=15
Address of n=0x8fcafff2

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];

Initializing a one dimensional array


The values can be initialized to an array, when they are declared like ordinary variables.
Syntax
data_type array_variable[size or subscript] = {values};
Example
int n[5]={1,5,2,3,7};

ii. Two-Dimensional arrays


The collection of data items can be stored under a one common variable name used two
subscripts; such a variable is called the two-dimensional array

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

Column 0 Column 1 Column 2


Row 0
Row 1
Row 2
Initializing a two dimensional array
The values can be initialized to an array, when they are declared like ordinary variables.

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];

Initializing a three dimensional array


The values can be initialized to an array, when they are declared like ordinary variables.

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

You might also like