Object Oriented Programming using C plus plus

suleman05cs32 9 views 204 slides Sep 21, 2024
Slide 1
Slide 1 of 204
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204

About This Presentation

Object Oriented Programming using C plus plus


Slide Content

Object Oriented Programming with
C++

Class : MCA - Il Semester

Overview of C++
Sample C++ program
Data types
Operators
Expressions
Statements

Arrays

Strings

Pointers

User defined types
Function components
Argument passing
Inline functions
Function overloading
Recursive functions

Overview of C++

Object oriented programming is a
programming paradigm.
Tool which is used to build more reliable and
reusable system.
Two types of programming paradigms

1. Procedure oriented programming

2. Object oriented programming

Structured programming

Gives importance to the logic rather than data.
Emphasis on algorithm rather than data.

Programs are divided in to modules.

Independent functions (procedure) to discrete
tasks.

Do not support inheritance and polymorphism.

In procedural languages like FORTRON, PASCAL,
COBOL, C etc. a program is a list of instructions.
Each statement in the program tells the computer
to do something.

Procedural approach has its own limitations.

o Division into functions

o Complex

o Data undervalued

o Division into functions:
* loosely defined discipline
* Program divided into number of functions.
* Grouping number of functions into larger
entity called module.
o Complex:
* Large programs become complex to debug
and maintain.
o Data undervalued:
* Importance to actions and not for the data
« Data is not secure.
« Any function can access the global variable
and changes its values.

Object oriented programming

To overcome the limitation of the procedural
language the OOP concept was developed.

New way of solving problems with computers.

OOP languages provide the programmer, the
ability to create class hierarchies.

Programmer can create modular and reusable
code.

Can modify the existing modules.

The fundamental idea behind object oriented
languages is to combine into a single unit, both
data and functions. Such a unit is called as object.

Functions inside the objects are called as member
functions and these member function provide the
way to access data.

If you want to read a data item in an object then
you call the member function in the object.

It will read that data item in an object and returns
the value. You cant access the data directly. Data
is hidden.

Data and its functions are said to be encapsulated
into single entity called object.

* OOPS definition: OOPS can be defined as technique
by which a computer program is designed and
written around the objects.

* The fundamental features of OOPs are
— Encapsulation
— Data Abstraction
— Inheritance

— Polymorphism

— Message passing

— Extensibility

— Persistence

— Delegation

— Genericity

— Multiple inheritance

Class

Class is a template (format).

The C++ class mechanism allows users to define their
own data types.

For this reason, classes are called user-defined types.
A class definition has two parts:

— class head - composed of the keyword class followed by
the class name

— class body - enclosed by a pair of curly braces.

A class definition must be followed either by a
semicolon or a list of declarations.

For example:
€ E
class Screen { .............. } myScreen, yourScreen;

Objects

+ aclass is a logical
abstraction.

+ An object has physical
existence.

« An object is an instance of a
class.

+ An object is a combination or
collection of data and code
designed to emulate a physical
or abstract entity.

EX: class Screen { .............. }

myScreen, yourScreen;

+ Screen-class name

+ myScreen and yourScreen
are objetcs.

* The general form of class and
its object lists looks as below:

class class-name {
private data and functions
access-specifier:
data and functions
access-specifier:
data and functions
N...
access-specifier:
data and functions
} object-list;

Example for representation of class

Class account
{

private:
char name[20]; // data members
int acc_type;
int acc_no;
float balance;

public:
deposite(); // member functions
withdrow();
enquire();

Objects serve the following purposes:
Understanding the real world and a practical base
for designers.

Decomposition of a problems into objects
depends on judgment and nature of the problem.
Every object has attributes and behavior called
operations.

The attributes are the data structures
representing the properties of the objects.

Encapsulation:

¢ It is a mechanism that associates the code and data,
it manipulates into a single unit. It is supported by
class.

» Encapsulation is the mechanism that binds together
methods and the data, and keeps both safe from
outside interference and misuse.

* In an object-oriented language, functions and data
may be combined in such a way that a "black box" is
created.

+ The wrapping of data and functions into a single unit
is known as encapsulation.

» Data Abstraction:

° The technique of creating new datatype that
are well suited to an application to be
programmed is known as data abstraction.

« The data types created by the process of data
abstraction are called Abstract Datatype.

Inheritance:

Inheritance is the process by which an object of one
class acquires the properties of objects of another
class.

The class which inherits the properties from another
class and the relation is called parent — child relation.
The parent class which gives its properties to another
class is known as Base class.

The child class which inherits properties from parent
class is known as derived class.

It allows the extension and reuse of existing code
without having to rewrite the code from scratch.

The new derived class inherits the members of the
base class and also adds its own.

Ex: when the class B inherits the class A, the
class B is called the derived class or sub class.

The class A is called the base or super class.
The class B has two parts.

Derived part: which is inherited from the base
class A

Incremental part: which is the new code
included in the class B.

For example, Maruthi, sports cars and Benz are
all types of cars.

In the object oriented language, sports cars,
Maruthi and Benz are subclasses of the class car.
The class car is a "super class" (parent class or
base class) of Maruthi, Benz, and sports cars.
Every subclass will inherit data (state) and
functions (properties) from the super class.

The various types of cars such as Maruthi and
Benz will share certain properties such as break,
escalator, steering etc.

+ The attribute once declared in the super class which
are inherited by its subclasses, need not repeated.
They can be accessed form any subclass unless they
are private.

+ Only the methods of a class can access its private
attributes.

+ The attributes which are declared as protected are
accessible to subclasses.

Single Inheritance:

» refers to deriving a class from a single base
class .

Multiple Inheritance:

+ In this, the class is derived from more than
one base class is known as multiple
inheritance.

Polymorphism:

Poly means many and morph means forms. So
Polymorphism means many forms.

It allows a single name/operator to be associated with
different operations depending on data passed on it.
The ability to use an operator or function in different
ways or giving different meaning to the operators or
functions is called polymorphism.

Poly refers many. That is a single function or an
operator functioning or behaving in many ways
depending upon the usage is called polymorphism.
Operator overloading and function overloading are the
two kinds of polymorphism.

* EX: depending on the type of the arguments
passed then it’s known as function overloading.

* when an object/class has several methods with
the same name that take different parameters:
Calculate(int a, float b), Calculate(int a, int b),
Calculate(float a, float b)

* Here one of the three Calculate function is
executed depending upon the arguments passed
to it.

Message Passing:

In an object oriented language, a message is sent to an object.

It is the process of invoking an operation on an object in
response to a message, the corresponding method is executed
in the object.

A message for an object is interpreted as a request for the
execution of a function.

When message is received, the suitable function is invoked and
result is generated in the object.

Ex: student.marks(rollNo)

It contains the name of the object, name of the function,
information sent to the object.

In the above example : marks() is a message with the parameter
rollNo as the information, student is an object.

Object have life time, created and destroyed, whenever
necessary communication between objects can occur as long as
they are alive.

Extensibility:

* it allows the extension of the functionality of
the existing software components.

Persistence :

° The phenomenon where the object outlives
the program execution time and exists
between execution of program is known as
persistence.

Genericity :
* It allows the declaration of data items without
specifying their exact datatype.

Delegation:

Two most common techniques for reusing functionality in
object oriented system are class inheritance and object
composition.

In class inheritance we know that if the class B is derived
from class A, then B is a kind of A.

The new approach to object composition says that an
object can be a collection of many other objects and the
relationship is called a has a relationship or containership.
Delegation is a way of making object composition as
powerful as inheritance for reuse.

Here two objects are involved in handling the request: a
receiving object delegates operations to its delegate. (just
similar to subclasses sending requests to parent classes).
In some cases, inheritance and containership relations are
serve the same purpose.

A C++ program consists of a number of objects
which communicate each other by calling one
another’s member functions.

The member functions in C++ are called as
methods.

Calling an object’s member function is referred to
as sending a message to the object.

The object’s internal structure is totally hidden
from the user and this property is called “ Data /
information hiding ” or “ data encapsulation ”.

In C++, both attribute (data) and methods (functions) are

members of a class. The members are declared either as

private or public.

Public members can be accessed by any function, private

members can be accessed methods of the same class.

C++ has a special constructor function to initialize new

instances and a destructor function to perform necessary

clean up when an object is to be destroyed.

C++ provides 3 types of memory allocations for objects:

— Static — pre allocated by the compiler — variable outside a
function using static keyword.

— Automatic- allocated on the stack — locals variables with in
function.

— Dynamic — allocated from a heap - explicit request from
programmer.

Differences

structured programming
approach

Gives importance to logic
rather than data.

Data is not at all protected
and can be modified by any
anyone.

we cannot create reusable
components
Large programs are divided
to smaller programs known
as functions.

object oriented programming
approach

Gives importance to data.

Only the preferred set of
methods can modify the
data. Here data is not
accessible to everyone.

we can create a reusable
component.

they
objects.

are divided into

Differences

structured programming
approach

functions cannot be
mapped to a real world
object.

object oriented programming
approach

objects can be mapped to a
real world.

For e.g. a program on Car
can be written by creating a
class called Car and having
functions and data variables
associated with it.

Differences

C++ programming language

C++ is an object oriented
programming language,
programs are written using
the classes and objects.

Stream objects for 1/0 i.e.
iostream.h is used. C++ has
stream-type objects like cin
and cout

Inlining and overloading of
functions.

C Programming language

C is an structured or
procedural oriented
programming language

where the programs are
written using several
functions.

Stdio.h files is included in
the program for 1/0.

C doesn't support inline and
overloading of functions.

Differences

C++ programming language

Storage operators new and
delete.

Support for object-oriented
programming through
inheritance, polymorphism
and encapsulation.

In C++ comments are
enclosed in /* and */ and //
In C++, declaration
statements can occur just
anywhere in the code.

C Programming language

Only memory allocation
functions like malloc, calloc
are used.

Do not support object-
oriented programming.

In C comments are enclosed
in /* and */. Like C++ //
cannot be used for
comments.

In C declaration statements
must be the first statements
in a block.

Differences
C Programming language

C++ programming language

Function and operator
overloading is possible in
C++. Functions with
different type of arguments
can have same names.
Operators can be redefined
to perform different tasks.

Function and operator
overloading is not possible
in C. Functions with
different type of arguments
have to have different
names. Operators cannot be
redefined as in C++.

¢ C++ was developed by Bjarne Stroustrup
starting in 1979 at Bell Labs as an
enhancement to the C programming
language and originally named C with
Classes. It was renamed as C++ in 1983.

The C++ program

In C++, an action is referred to as an expression.

An expression terminated by a semicolon is referred to
as a statement.

A smallest independent unit in a C++ program is a
statement.

int book_count = 0;

This is a declaration statement. book_count is called as
identifier or variable or symbolic variable or an object.
In C++, every program must contain a function called
main ().

A C++ program begins execution with the first
statement of main ().

A function consists of four parts:

— a return type

— the function name

— a parameter list

— the function body (function definition)

The first three parts are collectively referred to as
the function prototype.

The parameter list, enclosed within parenthesis,
consists a comma separated list of zero or more
parameters.

The function body is enclosed within a pair of
curly braces. It consists of a sequence of program
statements.

A program source file’s name generally consists of
two parts: a file name and extension.

.CPP is the file extension.

Part of the compiler’s job is to analyze the
program for correctness.

Compiler cannot detect whether the meaning or
the logic of the program is correct, but it can
detect error in the program.

Two common forms of program errors are as
follows:

— Syntax error

— Type error

+ Syntax error
— The programmer has made a grammatical error in
the C++ program
° Type error:
— Each item of data in C++ has an associated type.

— For e.g. the value of 10 is an integer. The word
“hello” is string. If a function is expecting an
integer argument but given a string then type
error is signaled by the compiler.

Comment:

+ The main purpose of the comment is the help the human
readers of our program.

+ They help the person writing a program and anyone else who
must read the source file or code, to understand what’s going
on.

+ The compiler ignores the comments. Comments are helpful to
describe apart of the code.

There are two comment delimiters in C++:

1. Comments start with a double slash symbol (//) - Comments
start with a double slash symbol (//) and terminate at the
end of the line. This is mainly used for single line comments.

Ex: // this is a program to add two numbers

2. The comment pair (/*, */) - The compiler treats everything
falls

between /* and matching */ as part of the comment.
This is mainly used for multiple line comments.

Ex: /* this is a program to add two numbers * /

Input / Output

In C++ input and output is provided by the standard library
known as iostream library.

Input from our terminal (standard input) is tied to a
predefined iostream object cin.

Output to our terminal (standard output) is tied to a
predefined iostream object cout.

Any program which uses cin and cout statements must
include following statement. #include <iostream.h>

C++ uses the bit-wise left shift operator to perform output.
For e.g. cout <<”Hello world”;
The symbol << is called the insertion or put-to-operator.
More than one item can be displayed using a single cout
object

For e.g. cout<< “age =



<<age;

C++ uses the bit-wise right shift operator to
perform input operation.

Syntax:

cin >> variable;

For e.g. cin>>age;

The symbol >> is called the extraction operator.

More than one item can be displayed using a
single cout object

For e.g. cin>>name >>age;

Basic structure of C++ program

| Preprocessor directives |

( Global declaration |

| Class definition |

main()
{

Local declaration;
Statements;

}

User defined functions

A sample C++ program

« // program to display hello world // comment
+ #include<iostream.h> //pre processor directive
* Void main()

.L // function declaration
* Cout<<“Hello world, SIT, Valachil, Mangalore”;

° }

« // end of the program

The program (source code) is written in any
available text editor. Then it is compiled to
convert the machine code.

C++ program make use of libraries which contain
the object code of standard functions. This code
of all functions used in the program have to be
combined with the program written by the
programmer.

Some startup code is needed to produce an
executable version of the program.

This process of combining all the needed object
codes and startup code is called linking — which
produces executable code.

Scope resolution operator

+ C++ supports a mechanism to access a global variable from a
function in which a local variable is defined with the same name
as global variable. This is done using the scope resolution
operator.

+ Syntax : global variable name

« Ex: #include<iostream.h>

* Intnum=20; // global variable

* void main()

+ { int num=30; // \ocal variable
* cout<< “local = "<<num;

* cout<< “global = "<< ::num; //using scope resolution operator
* cout<< “sum =”<<::num+num;

° }

Output:

Local = 30 global = 20 sum = 50

manipulators

+ Manipulators are operators used to format the
data display.

* endl and setw are common used manipulators.

* endl — indicates the end of line. Further content
will be displayed in the next line.

* setw used to specify a field width to the data so
that it is right justified leaving enough spaces to
its right if number of characters are less.

« Ex: cout<<sum<<endl; 2] 4]5

* Cout<<setw(5)<<sum; 2 [als

DATA TYPES

Data types
Data is the smallest unit of information that
the computer manipulates.
The type of data being manipulated in the
computer defined the data type.
Basic data types are integer, floating point
character.
C++ supports both basic and derived data
types.
Two more data types bool and wchar_t are
added by ANSI C++.

C++ Data Types

User-defined type

AH

Built-in Type Derived Type
Structure Array
Union Function
Class Pointer
Enumeration Reference

Integral Type

Void Floating Type
\

Data es

+ It describes the characteristics of the data.
« There are different types-

Primary/ Fundamental Data type:

* integer (int)

« character (char)

* floating point (float)

+ double-precision floating point (double)

—There are five basic data types:
¢ char
e int
* float
° double
* void
—ANSI C++ adds two more:
* bool Boolean value
ewchar_t wide character

The wchar_t Type Specifier

° The wchar_t type specifier is an integral
type that has enough storage to
represent a wide character literal.

+ A wide character literal is a character
literal that is prefixed with the letter L,
for example L'x'

Integer Data Type:

¢ It contains whole numbers.

+ If we use a 16 bit word length then the size of integer ranges
between -32768 to 32768. (2:15 & 2+15)

Signed Integer Unsigned Integer
* int Unsigned int
* short int Unsigned short int

+ long int Unsigned long int

Floating Data Type:

* Occupy 4 bytes. (32 bits) where last 6 bits are for precision
+ The decimal point occupies 1 bit.

¢ Float

+ Double

+ Long double

Character Data Type:

It may be signed or unsigned character
+ Itis defined as char.
+ It occupies one byte

Bool e:

A bool object can be assigned literal values true or false.
For Ex: bool found = false;

« Bool cannot be declared to be either signed, unsigned, short or
long.

. bool found = false;
int occ_count = 0;
while( )
{ found = look_for();
occ_count += found;

}

« Bool objects and Bool literals are implicitly promoted to type
int when an arithmetic value is necessary. False becomes 0 and
true 1.

+ Arithmetic and pointer values are implicitly converted to a
value of type bool.

« A zero or null pointer value is converted to false, all other
values are converted to true

Derived Data types

Array Types:

An array is a collection of variables of the same type that are
referred to through a common name.

For Ex: int a[10]; // declares an array of 10 ints

» The dimension must be a const expression. A non constant
variable cannot be used to specify the dimension of an array.

* It must be possible to evaluate the value of the dimension at
compile time. But the access to non-const object is accomplished
only at run time and so it cannot be used as a dimension.

* const int size = 5;

* int a[size] = {0, I, 2};

int b[ ] = {1, 2, 3}

An array can be explicitly initialized and such an array need not specify a
dimension value.

If the dimension is greater than the number of elements, the non initialized
elements are set to zero

int a[5] = {0, 1, 2}; // a= {0, 1,2, 0, 0}

A character array can be initialized as either a list of
comma-separated characters or a string literal

const char calf ] = {‘c’, ‘+’, +};

const char ca2[ ] = “C++”; const char ch3[3] =
“C++” ;

The string const contains an additional terminating null
character.

Pointer type:

A Pointer is a variable which holds the address of another
variable.

« A pointer is defined by prefixing the identifier with the
dereference operator (*)

. int *p = 0; //comment

« A pointer can hold a value of zero, indicating that it points to
no object. A pointer cannot hold a non address value.

. void *gp;

+ Void pointer is called a generic pointer, which can hold the
address value of any data type. But may not be dereferenced.

For Ex: void *gp;
int *ip;
gp = ip; // assign int pointer to void pointer
But *ip=*gp; /lillegal
Pointer arithmetic:
A number can be added to a pointer.
A number can be subtracted from a pointer

A pointer when incremented always points to an immediate
next location of its type.

String type:
C++ provides two string representations:
i) C-style character string

ii) String Class type

+ The C-style originated within C language and is
supported within C++

+ The string is stored within a character array and is
manipulated by a char* pointer.

+ The C-style character string can be of zero length.

+ String Class type : String class supports the following
operations

a) Initialize a string object both with a sequence of characters and
with a second string object.

b) Copy one string to another.

c) Compare two strings for equality.

d) To append two strings.

e) Finding String length

f) Support to know whether a string is empty

g) Defining an empty string.

Reference Types:

A reference provides an alias for a previously defined object. The
general form is:

Data-type & reference-name = variable-name
For Ex: float total = 100;
float &sum = total;

Both the variables refer to the same data object in the memory.

Cout<<total<<“\n”<<sum; //Both print 100
total = total +10; // changes the value of both to 110
int &rerefval = &ival //illegal

Although a reference serves as a pointer, it is not correct to initialize
it to the address of an object

Once defined a reference cannot be made to refer to another
object that is why it must be initialized.

The difference between a reference and a pointer is that a
reference is internally treated as a constant pointer.

The major application of reference variables is in passing
arguments to functions
void fun(int &x)
{ x=x+10; }
main()
{ intm = 10;
fun(m); //function call
return 1;

}

When the function call is executed , the following initialization
occurs.

int &x = m;

User-defined Data types

> Structures

> Union

> Classes

> Enumerated data type:

User-defined Data types

Enumerated Data type:

* Itis a user-defined data type.
« The syntax of enum statement is similar to that of struct
» For Ex: enum shapef circle, square, triangle};

« The tag name becomes new type name and new variables can
be declared using these tag names.

« For Ex: shape ellipse;

C++ does not permit an int value to be automatically converted
to an enum value but an enum value can be used in place of an
int value.

By default enumerators are assigned integer values starting
with 0, 1, .....

Integer values can be assigned to enumerators explicitly.
For Ex: enum colorfred, blue = 4, green}

Anonymous enums are enums without tagnames. For Ex:
enum {off, on}; int switchl = off;

Enumeration is used to define symbolic constants for a switch
statement.

Literals- constant Qualifier

Literals are constants to which symbolic
names are associated for the purpose of
readability and ease of handling standard
constant values.

There are 3 ways of defining constants in C++

#define preprocessor directive
Enumerated data types

Const keyword

Ex: float PI=3.1452;

The above statement declares a variable Pl which
is assigned a value 3.1452, which is a constant.

But any changes to the variable Pl is not
restricted here.

This problem is overcome in C++ by using the
keyword const while declaring a variable.

The value is never changing later in that case.

We cannot modify a constant object.

Using this qualifier accidental modification of a
value can be prevented in programs with or
without functions

Tokens, expressions and control structures

+ As C++ isa super set of C, most constructs of C are legal
in C++.

+ Tokens: smallest individual units in a program.

+ In C++ there are — keywords, identifiers, constants,
strings and operators.

+ There are 48 keywords including 32 C keywords. 15
more are added by ANCI C++.

¢ Identifiers are names of variables, functions, arrays,
classes etc. — rules similar to C.

+ A major deference is in the length of a name. ANCI C
only recognizes the first 32 characters in a name.

* In C++, no limit on its length and so all the characters
are significant.

Like C, C++ supports several kinds of literal
constants.

Ex: 123 decimal constant
Floating point constant
Octal integer
Hexadecimal integer
String constant
Character constant

C++ also recognizes all the backslash characters
of C.

Character constants

Single character constants: contains a single
character enclosed within a pair of single
quote marks.

Eg: ‘p’, u:
String constants: A string constant is a
sequence of characters enclosed in double
quotes.

Eg: “class”, “123”

Operators and Expressions

OPERATORS

> C++ is rich in built-in operators(rich set of
operators).

> There are four main classes of operators:
arithmetic, relational, logical, and bitwise

The Assignment Operator

> The assignment operator within any valid expression.
> The general form of the assignment operator is

Variable_name =expression;
Where, expression may be as simple as a single constant or as
complex as you require.

Here, target or left part, of the assignment must be a variable or a
pointer not a function or a constant.

In compiler error messages you will see these two terms: {value and
rvalue.

“value” means “variable” and “rvalue” means “value of an
expression”

Type Conversion in Assignments

> When variables of one type are mixed with variables of another
type , a type conversion will occur.

> The value of the right side(expression side) of the assignment is
converted to the type of the left side( target variable)

For eg:- int x;

char ch;

float f;

void func(void)

{
ch=x;
x=f;
f=ch;
f=x;

Multiple Assignments

* C++ allows you to assign many variables
the same value by using multiple
assignments in a single statement

For eg: this program fragment assigns x,y,
and z the value O

x=y=z=0;

Arithmetic Operators
> The arithmetic operators can be almost

any built-in data.
For eg: int x,y;

x=5;
y=2;

printf(“%d”,x/y); /*will display 2*/

printf(“%d”,x%y); /*will display 1,the remainder of the

integer division*/

x=1;

2

printf(“%d%d”,x/y,x%y); /*will display O 1 */

Arithmetic operators

- Subtraction , also unary minus

+ Addition

hos Multiplication
N} Division

% Modulus
we Decrement

++ Increment

Increment and Decrement

> The operator ++(increment) adds 1 to its operand, and —
(decrement) subtracts 1.

> In other words,
x=x+1; is same as +4+x;
x=x-1; is same as X--}
Both increment and decrement operators may either precede (prefix)
or follow (postfix) the operand.
For eg:-
x=x+1; can be written as ++x; or x++;
Precedence of the arithmetic operators:

- (unary minus)
1%

Lowest +-

Diff b/w prefix and postfix forms

> Diff b/w prefix and postfix forms when you use these operators in an
expression. When an increment or decrement operator precedes its
operand, the increment or decrement operation is performed before
obtaining the value of the operand is obtained before incrementing
or decrementing it

> for eg:

x=10;

y=t+x;

Sets y to 11. However , if you write the code as

x=10;

y=xt+;

y is set to 10. Either way, x is set as 11; the difference is in when it
happens

Note:-Parentheses force an operation, or set of operations, to have a
higher level of precedence

Relational and Logical operators

Relational operator, relational refers to the relationships that value
can have with one another.

Logical operator, logical refers to the ways these relationships can
be connected.

Expression that use relational or logical operators returns 0 for false
and 1 to true.

The truth table for logical operators

0 0 0 0 il
0 al 0 il al

1 1 À 1 0

Relational and Logical operators

Relational operators

Operator Action
> Greater than
= Greater than or equal
< Lesser than
<= Lesser than or equal
ES Equal
I= Not equal
Operator Action
&& AND
Il OR

! NOT

Precedence for relational and logical

Both relational and logical operators are lower in precedence than
the arithmetic operators.

The following table shows the relative precedence of the relational
and logical operators:

Highest !

Lowest 11

Bitwise operator

> Bitwise operation refers to testing , setting or shifting the actual bits
in a byte or word, which correspond to the char and int data types
and variants.

> The operations are applied to the individual bits of the operands.

> Table for Bitwise operators

Operator Action

& AND
| OR
N Exclusive OR(XOR)
~ One’s complement(NOT)
>> Shift right
<< Shift left

Bitwise operator

> The bit shift operators , >> and <<, move all
bits in a value to the right or left as specified.

> The general forms of the shift-right statements
is:

value>> number of bit positions

> The general forms of the shift-left statements
is:

value<<number of bits positions

As bits are shifted off one end , 0's are brought in
the other end , shift is not a rotate. That is the
bits shifted off one end do not come back

around to the other. The bits shifted off are
lost.

The ? Operator

> The ternary operator ? takes the general form:
Exp1 ? Exp2 : Exp3;

where, exp1, exp2, exp3 are the expressions.

> The ? Operator words like this :Exp1 is
evaluated. If its is true Exp2 is evaluated and
becomes the value of the expression . If Exp1
is false, exp3 is evaluated and its value
becomes the value of the expression.

For eg:

X=10;

Y=X>9?100:200;

Output: Y=100

The & and * pointer operators

> Apointer is the memory address of some object .

> A pointer variable is a variable that is specifically declared to hold a
pointer to an object of its specified type.

> The first pointer operator is €, a unary operator that returns the
memory address of its operand.(unary operator requires only one
operand)

For eg: m=&count;
Places into m the memory address of the variable count. This address
is the computer’s internal location of the variable. It has nothing to do
with the value of count.
& as meaning “the address of”

The above statement means: “m receives the address of count”

> In the above eg assume that the variable count is at memory location
2000. Also assume that count has the value 100, m will have the value
2000.

The & and * pointer operators

The second pointer operator is *, which is the complement of &.

Vv

v

The * is a unary operator that returns the value of the variable
located at the address that follow it

Y

For eg:- if m contains the memory address of the variable count
q=*m;
> Places the value of count into q. now q has the value 100 because

100 is stored at location 2000, the memory address that was
stored in m.

* as meaning “at address”

The above statement means:”q receives the value at address m”

Eg for * and & operator:

Program uses * and & operators to put the value 10 into a variable
called target

ttinclude<stdio.h>
int main(void)

{

int target, source;
int *m;

source=10;
m=&source;
target=*m;
printf(“%d”,target);
return 0;

}

The Compile-time Operator sizeof

N

> Size of is a unary compile time operator that returns the length in bytes,
of the variable or parenthesized type- specifier that it precedes.

> For eg :assuming that integers are 4 bytes and doubles are 8 bytes,
double f;
printf(“%d”,sizeof(f));
printf(“%d”,sizeof(int));

Will display 8, 4

> Size of primarily helps to generate portable code that depends upon the
size of the built-in datatypes.

Vv

The comma operator

The comma operator strings together several expressions.

The left side of the comma operator is always evaluated as void.
This means the expression on the right side becomes the value of
the total comma-separated expression.

> For eg: x = (y=3,y+1);

first assigns y the value 3 and then assigns x the value 4. the
parentheses are necessary becoz the comma operator has a lower
precedence than the assignment operator.

Comma causes a sequence of operations. When you use it on the
right hand side of an assignment statement the value assigned is
the value of the last expression of the comma-separated list.

Vv

Vv

Vv

Vv

wv

The dot(.) and arrow(->) operator

In C, the . (dot) and the -> (arrow)operators access individual
elements of structures and unions. Structure and unions are
compound (also called aggregate) data types that may be referenced
under a single name.

In C++, the . (dot) and the -> (arrow)operators are also used to
access the member of a class.

The dot operator is used when working with the structure or union
directly.

The arrow operator is used when a pointer to a structure or union is
used

Eg for dot operator:
emp.wage=123.34

Eg for arrow operator:
emp->wage=123.34

The [ ] and ( ) operators

> Parentheses ( )are operators that increase
the precedence of the operation inside
them.

> Square brackets perform array indexing.
Given an array, the expression within
square brackets provides an index into
the array.

for eg : char s[80]
All arrays begin at index value O

Expressions

> Operators , constants and variables are the
constituents of expressions.

>An Expression is any valid combination of these
elements.

Vv

Vv

Vv

Type conversion in expressions

When constants and variables of different types are mixed in an
expression, they are all converted to the same type.

The compiler converts all operands up to the type of the largest
operand which is called the type promotion.

First all char and short int values are automatically elevated to int
(process is called as integral promotion).

If the above step has been completed then all other conversions are
done operation by operation as described in the following type
conversion algorithm:

Conversion algorithm
IF an operand is a long double
THEN the second is converted to long double
ELSEIF an operand is a double
THEN the second is converted to double
ELSEIF an operand is a float
THEN the second is converted to float
ELSEIF an operand is a unsigned long
THEN the second is converted to unsigned long
ELSEIF an operand is a Jong
THEN the second is converted to long
ELSEIF an operand is a unsigned int
THEN the second is converted to unsigned int

Special case :lf one operand is long and the other is unsigned int, and if the
value of the unsigned int cannot be represented by a long both operands
are converted to unsigned long

Casts

> You can force an expression to be of a specific type by using a cast.
> The general form of cast is :
(type) expression
where type is a valid data type.
for eg:- to make sure that the expression x/2 evaluates to type float,
write
(float ) x/2
+ Casts are technically operators. As an operator, a cast is unary and
has the same precedence as any other unary operator.

> Inthe above eg, only an integer division would have been performed
. The cast ensures that the fractional part of the answer is displayed.

Spacing and parentheses

> This allows us to add tabs and spaces to expressions to make them
easier to read.

for eg:- the following 2 expressions are the same :

Q x=10/y-(127/x);

a x = 10 / y - (127/x);

> Using of additional parentheses do not causes errors or slow down
the execution of an expression.

Instead parentheses helps to clarify the exact order of evaluation,
both for yourself and others.

for eg:-
O x= y/3-34*temp+127;
Q x= (y/3) — (34*temp) + 127;

Compound assignments

> Variation on the assignment statement, called compound
assignment, that simplifies the coding of a certain type of
assignment operation.

For eg:- x= x+10; can be written as x += 10;

The operator += tells that the compiler to assign to x the value of x
plus 10.

> compound assignment operators exists for all the binary
operators(those that require two operands).in general the
statement like:

var = var operator expression
can be rewritten as,
var operator = expression

STATEMENTS

Statement

« Astatement is a part of the program that can
be executed.

+ Statement specifies an action.

Selection statements

» General form:

If(expression)

{

Statements;

}

Else

{

Statements;

}

If statement

Cont...

« |f expression evaluates to true, the statement
or block that forms the target of if is executed.
Otherwise the statement or block that is the
target of else will be executed.

Example

main()

{

int a=10, b=15;
if(a>b)

cout<<“A is greater”
else

cout<<“B is greater”

}

Nested if

+ Anested if is an if that is the target of another if or else.

* General form
if(expression1)

{
if(expression2)
statement;
else
statement;

}

else

statement;

Example

Int a=10,b=15,c=20;
If(a>b)
{
if(a>c)
cout<<“A is largest”;
else
cout<<“c is largest”;
}
Else
{
If(b>c)
Cout<<“B is largest”;
Else
Cout<<“c is largest”;

}

Else if ladder

* The conditions are evaluated from the top
downward. As soon as a true condition is
found, the statement associated with it is
executed and rest of the ladder is bypassed,

General form

if(expression1)
statementl;
else if(expression2)
statement2;
else if(expression3)
statement3;

else
Statement;

Example

main()
{
int magic=rand();
int guess;
cout<<“Guess a number”;
Cin>>guess;
if(guess==magic);
cout<<“Right”;
else if(guess>magic)
cout<<“Wrong too low”;
else if(guess<magic)
cout<<“Wrong too high”;

? Operator(Ternary)

+ ? Operator is used to replace simple if_else
statement.

° General form
expression?statement1:statement2;

Ex:
x=10;
y=x>9?100:200;

Switch statement

* It is a built-in multiple-branch selection
statement.

* It tests the value of an expression against a list
of integer or character constants. When a
match is found, the statement associated with
that constant are executed.

General form

switch(expression)

{

case constant1: statement1
break;

case constant2: statement2
break;

default: statement

}

Example

main()

{

int ch,a=250,b=150,c;
cout<<“1.Add\n”;
cout<<2.Sub\n”;
cout<<“Enter your choice:”
cin>>ch;

switch(ch)

{

case 1: c=add(a,b);
break;

Cont...

case 2: c=sub(a,b);

break;
default: cout<<“Error”
cout<<c;

}

Iteration statements

+ In c++ iteration statements allow a set of
instructions to be executed repeatedly until a
certain condition is reached.

For loop

General form

for(initialization;condition;increment/decrement)

The initialization is an assignment statement that is used to set
the loop control variable.

The condition is a relational expression that determines when
the loop exits.

The increment or decrement defines how the loop control
variable changes each time the loop is repeated.

We can use for(;;) to create infinite loop.

Example

Main()

{

For(int i=0;i<10;i++)
{

Cout<<i<<“\t”;

}

}

Output:
0123456789

While loop

General form

while(condition)

{

statement;

}

The condition may be any expression.
The loop iterates while the condition is true.

When the condition becomes false, program
control passes to the line of the code
immediately following the loop.

main()

{

Int i=0;
While(i<10)

{
Cout<<c<<“\t”;
i++;
}

Output:
0123456789

Example

Do while

It is a exit controlled loop.

It tests the loop condition at the bottom of
the loop.

The loop body is executed at least once.
General form:

do

{

statements;

}while(condition);

Example

main()

{

int a=25;

do

{
cout<<a<<“\t”;
a--;
}while(a==50);
}

Jump statements

« C++ has four statements that perform an
unconditional branch: return, goto, break and
continue.

« Return and goto we can use anywhere in the
program.

+ We may use the break and continue
statements in conjunction with any of the
loop statements.

return statement

return is used to return from a function.

It is recognized as a jump statement because
it causes execution to return to the point at
which the call to the function was made.
return may or may not have a value
associated with it.

Syntax:
Return expression

The goto statement

¢ The goto statement requires a label for
operation.

¢ The label must be in the same function.
« General form
goto label;

label:satements;

break statement

« It has two uses: It is used to terminate a case
in the switch statement.

¢ It can also be used to force immediate
termination of a loop.

+ When a break statement is encountered
inside a loop, the loop is immediately
terminated and program control resumes at
the next statement following the loop.

main()

{

int t;
for(t=0;t<100;t++)
{

cout<<t;

if(t==10)

break;

}

return 0;

}

Example

The continue statement

* continue statement forces the next iteration
of the loop to take place, skipping any code in
between.

Example

main()

{

int t;
for(t=0;t<=20;t++)
{

if(t<=10)
continue;
cout<<t;

}

}

The exit() function

* User can break out of a program by using the
standard library function exit().

* This function causes immediate terminaton of
the entire program, forcing a return to the
operating system.

* General form is
void exit(int return_code)

The value of the return_code is returned to the
calling process, which is usually the operating
system.

Arrays and null terminated Strings

Arrays

An array is a collection of variables of the same
type that are referred to through a common
name.

A specific element in an array is accessed by an
index.

All arrays consist of contiguous memory
locations.

The lowest address corresponds to the first
element and the highest address to the last
element.

Arrays can have from one to several
dimensions.

Single-Dimension Arrays

A list of items that is given one variable name using
only one subscript sharing same data-type.

The general form of declaring single dimension array is
type var_namelsize];

+ Type = data type.

+ var_name = user defined.

Like ater varlables, arrays must be declared
explicitly.

Ex: int list[10];

char str[20];

Single-Dimension Array initialization

+ Array initialization can be either of the following stages:
1. At compile time
2. At Run time
« Syntax for compile time initialization is:
type arr_namelsize]={ list of items };
Ex: intno[3]={1,2,3}
char str [5]=Ug",%o" "ol, d'A E
intlist{]={1,2,3}; //size omitted
char str [] = “SIT”;
int list [5]={9,18}; // remaining elements to zeros
int list [3] ={10,11,12,13}; // illegal

« Runtime initialization is easy using loop statements.
Ex: initializing '5' numbers to the array called ‘list’.
for (int i=0; i<5; i++) scanf(“%d”, &list[i]);

Generating pointer to an array

It is possible by simply specifying the array
name, without any index.

For example:
int simple[10];
int *ptr;
ptr = simple;
It is same as,.

ptr= &simple[0]; //address of first item in
array

‘simple’ and 'Esimple[0]' both produce the same
result,. simple==&simple[0];

Null terminated strings

String is a sequence of characters that is treated as a single data
item.

Any group of characters (except double quote sign) defined
between double quotation marks is a string constant.

Eg.
It is a null (‘\0’) terminated character array.

Some times, NULL terminated strings are also called as C-Strings.
Ex: char str[12];

Here str will have a room to store NULL character at the end of
the string.

While storing “hello there” in str, the compiler automatically sets
the null.

String manipulation functions are included in 'string.h' header
file.

e Most common string functions are:
1. strcpy(s1,s2); // Copies s2 into s1
2. strcat(s1,s2); // Concatenates s2 onto the end of si.
3. strlen(s1); // Returns the length of s1
4. stremp(s1,s2) // Compares two strings (+1,-1 or 0).

5. strchr(s1,ch); //returns a ptr to the 1st occurrence of ch
in s1.

6. strstr(s1,s2); // returns a pointer to the Ist occurrence of
s2 in sl.

Passing single-dimension array
to the functions
. Syntax of passing array is:
function_name(array_name[, size]); //size is optional
Ex: sum(a, 5);

+ Passed array will be received by the formal parameter in

three ways:

| — As a sized array
As a pointer
int sum( int a[5] )

oe m
J

— As a unsized array
int sum( int a[5] ){.. ..

J

int sum( int *a, int n )

Two-Dimensional array

Arrays which have elements of two subscripts are known as
2-D arrays.

A 2-D array consists of rows and columns.

Each element is accessed by 2 subscripts.

The general form of declaring single dimension array is
type var_name[row_size][col_size];

Here, it reserves 72 bytes of storage locations and
3*6=18 elements can be stored.

Eg: - float X[3][6];

i.e.., the individual elements are : -
X [O][0] X[01 1... X[0][5]

X [AO] XL mn. X[1][5]

X [AIO] XA Tecnos x[2115]

Array Initialization

+ A2-D array can be initialized by listing the values enclosed in curly
braces.

« Different methods of forms of initializing the elements to the array.

% int mat[2][2] = {1,2,3,4};
Where,

mat[0][0] = 1
mat[0][1] = 2
mat[1][0] = 3
mat[1][1] = 4

2, int mat[2][2] = { (1,2),

{3,4} },
3 int mat [ ][2] = { {1,2},

{3,4} },

Here, the elements are specified explicitly. So there is no need of mentioning the
size (row size in the above Example).

If the values are missing in an initialize, they are
automatically set to zero.

int mat[3][5] = € {1}, {1}, (133;
here, 1% element of all the rows will be 1 and rest
all will be zeroes. i.e..,
Run time initialization can be done using loop,.
Example for loop.
for (int i=0;i<5;i++)
for( int j=0;j<5;j++)
Scanf(“%d”,mat[i][5]);
Here ‘i’ represents row and ‘j’ represents column.

Multi-Dimensional array
« More than 2-dimensions are also possible in C.
General Format:
type array-name[s1 ][s2][s3]........[sm];
Eg: - intlamps[3][3][4];
i.e.., 3* 3 * 4 = 36 integer elements.
« Here, intlamps[3][3][4];

[3] represents lamp type.
[3] represents wattage type.
[4] represents year.

i.e.., the above declaration, represents the sales of 3 types
of lamps with 3 types of wattage for 4 years.

Functions

+ General form of a function

« Scope rules of Functions

¢ Function Arguments

+ Call by Value, Call by Reference

« Calling function with Arrays

* argc and argv - Arguments to main()

What is a function?

A function is a self-contained block of code that
performs a particular task.

We can also say it is a set of instructions to
carryout a particular task.

General form of a Function
ret-type function-name(parameter list)

{
body of the function

* ret-type specifies the type of data that the function
returns, it can return any type of data except an array.
By default it is assumed to be int.

« Function name is the name of the function which
follows the rules of the identifier/variable

« Parameter list takes the following form:
f(type varnamel, type varname2...., type varnameN)

The list of arguments/parameters should be separated
with comma and to be enclosed within parenthesis.

Ex: — f(int i, int k, int j) /* correct */
f(int i, k, float j) /* incorrect */

Scope rules of Functions

The scope rules of a language are the rules that govern
whether a piece of code knows or has access to another

piece of code or data.

Variables that are defined within the functions are
called local variable.

A local variable come into existence when the function
is entered and is destroyed upon exit.

The exception to this rule is when the variable is

declared with the static storage class specifier

Function Arguments

¢ Ifa function is to use argument, it must declare
variables that accept the values of the arguments.
These variables are called Formal parameter

e EX:
int is_in(char *s, char c)
{
while(*s)
if(*s==c)
return 1;
else
St+;

return 0;

» The function is_in has two parameters: s and c.
This function returns 1 if the character c is part of
the string s; otherwise, it returns 0.

Call by Value, Call by Reference

* In a computer language, there are two ways that
arguments can be passed to a subroutine i,e by

1. Call by Value.
2. Call by Reference.

Call by Value

» The calling function(i,e main()) sends the data to
the called function through actual arguments
and the called function receives the data through
formal parameters.

¢ In this method, the calling function sends copies
of its data which are stored in temporary storage
locations. These values are used by the function
as local variables(formal parameters)

« Further, the results are processed, temporary
variables are destroyed and result is returned to
the main program through return statements

« The formal parameters may change within the
called function. However, this does not affect the
actual parameters, since only copies of data have
been sent to the called functions.

e Ex:

#include<stdio.h>

swap(int,int);

main()

{
int x=10, y=20;
printf(“Before calling swap:x=%d, y=%d”,x,y);
swap(x,y)
printf(“After calling swap : x=%d, y=%d”,x,y);
return;

}

swap(int x, int y)

{
int temp;
temp=x;
y;
y=temp;

printf(“with swap function x=%d, y=%d”,x,y);
return;

Output:

« Before calling swap : x=10, y=20
« With swap function : x=20, y=10
« After calling swap : x=10, y=20

Call by Reference
« In the call by reference method the address of
arguments are passed as actual parameters to
the called function, the function can change the
contents stored at those addresses and these
changes will be visible in the calling function.

« As a result of this a function with the pointer
variables as parameters can return several values
to the calling function.

¢ It is important that the formal arguments of the
called function receiving the address of the
actual argument must be of pointer type

#include<stdio.h>
swap(int *,int *)
main()
{
int x=40, y=20;
printf(“Before calling swap:x=%d, y=%d”,x,y);
swap(&x, &y)
printf(“After calling swap : x=%d, y=%d”,x,y);
return;
}
swap(int *x, int *y)
{
int temp;
temp=*x;
ut
*y=temp;
printf(“with swap function x=%d, y=%d”,x,y);
return;

Output :-

« Before calling swap : x=40 y=20
« Within swap function :x=20 y=40
« After calling swap :x=20 y=40

Calling functions with Arrays
+ Generally, constants and variables are passed to
the functions as arguments

« Sometimes it is required to pass an entire array
to the function, in this case a reference(address)
of the first element of the array is passed to the
function. This is an exception to the call by value
parameter passing convention

+ Any change made to the array in the function, is
reflected in the actual argument in the calling
function

Ex:

int array_sum(int a[],int n)
{
int i,sum=0
printf(“Array Elements are:”)
for(i=0;i<n;i++)
{
scanf(”%d”,&alil);
sum=sum+alil;
}

return sum;

}

Argc and argv-Arguments to main()

* argc and argv, are two special built in arguments
which are used to receive command line
arguments.

« The argc parameter hold the number of
arguments on the command line and is an integer

+ It is always at least 1 because the name of the
program qualifies as the first argument.

* The argv parameter is a pointer to an array of
character pointers each element in this array
points to a command line argument.

Ex:
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
if(argc!=2)
{
printf(“You forgot to type your name\n”);
exit(1);
}
printf(“Hello %s”,argv[1]);
return 0;

}

THE RETURN STATEMENT
RECURSION

The Return Statement

«The return statement is used to return from a function.
*It has two important uses, they are
1. It causes an immediate exit from the function that it is in.

2. It may be used to return a value.

Returning from a Function
«There are two ways that a function terminates execution and returns
to the caller.

*The first occurs when the last statement in the function has executed
and conceptually the function’s ending curly brace (}) is
encountered.

*For eg:

The pr_reverse() function in this program simply prints the string “I
like C++” backwards on the screen and then returns. Once the string
has been displayed, there is nothing left for pr_reverse() to do, so

It returns to the place from which is called.

#include<string.h>
#include<stdio.h>

void pr_reverse(char *s)

int main(void)

{

pr_reverse(“I like C++)
return 0;

}

void pr_reverse(char *s)
{

register int t;
for(t=strlen(s)-1;t>=0;t--)
putchar(s[t]);

}

*Functions rely on return statement to stop execution either because a
value must be returned or to make a function’s code simpler and

efficient.

Returning Values
Void function doesnot return any value

If a non-void function doesnot explicity return a value via return
statement, then garbage value must be returned.
The valid expressions are

Y x=power(y)

Y If(max(x,y)>100) printf(“greater”)

Y For(ch=getchar(); isdigit(ch) ; ) ....;

*swap(x,y) =100; /* incorrect statement */

When we write programs, functions generally will be of three types
1) The first type is simply computational.
> They are designed to perform operations on their
arguments and return a value based on that operation.
> Computational function is a “pure” function.
> Eg: sqrt() and sin()

2) The second function manipulates information and returns
a value that indicates the success and failure of that
manipulation.
> Eg: felose()

> If close operation is successful, the function returns 0; if
the operation is unsuccessful, it returns EOF.

3) The last function has no explicit return value.
> The function is strictly procedural and produces no value
> Eg: exit()- terminates the program
> Itcan be declared as void.

Eg:

#include<stdio.h>
int mul (int a, int b);
int main (void)

{

int X,y,Z;

x=10; y=20;

z=mul(x,y) /* the return value of mul() is assigned to z */

printf(“%d”, mul(x,y) ); /* the return value is not assigned

‚but it is used by the printf() */

mul(x,y); /* the return value is lost because it is neither
assigned to another variable nor used as part of an
expression */

return 0;

}

int mul ( int a, int b)
{
return a * b;

}

Returning Pointers

=Pointers to variables are neither integers nor unsigned integers.
“They are the memory addresses to certain type of data.

"Eg

"This function returns a pointer to the first occurrence of the
character c in string s

Char *match(char c, char *s)

{
while (c!=*s && *s) s++;
return(s);

}

If no match is found, a pointer to the null terminator is returned.
Here is the pgm that uses match()

#include<stdio.h>

Char *match(char c , char *s) ; /*prototype */

int main(void)

{

char s[80], *p ,ch;
gets(s);
ch=getchar():
p=match(ch,s);

if(*p) /* there is a match */
printf(“%s”,p);

else

Printf(“no match found”);
Return 0;

Y

Functions of Type void

The functions donot return the values
Eg:

void print_vertical( char *str)

{

while ( *str )

printf( “ %c \n “, *str++);

}

Since it returns no value , it is declared as void.

What does main() Return?

oThe main function returns an integer to the calling process,
which is generally the operating system.

oReturning a value from main() is equivalent of calling exit() with
the same value.

Recursion

% A function is said to be recursive if a statement in the body of the
function calls itself.

< Recursion is the process of defining something in terms of itself,

and is sometimes called circular definition.
+ Eg:

«e /% Recursive */
int fact (int n)
{
int ans;
if(n==1)
return(1);
ans=fact(n-1)*n;
return(ans);

}

v When the function calls itself, a new set of local variables and
parameters are allocated storage on the stack, and function code is

executed from the top with these new variables.

Ÿ A recursive function doesnot make a new copy of the function.

Only the values being operated upon are new.

Y The old local variables and parameters are removed from the
stack and execution resumes at the point of the function call inside

the function.

Disadvantages

"Recursive routines do not reduce code size or improve memory

utilization over their iterative counterparts.
"It is bit slower than iterative counterparts.
"Recursive calls to a function would cause stack overrun.
"Because storage for function parameters and local variables is on
the stack and each new call creates a new copy of these

variables, the stack could be exhausted.

Advantages

*Recursive functions can be used to create clearer and simpler
versions of several algorithms.
For eg:- Quicksort

»Some problems one related to artificial intelligence, lend
themselves to recursive solutions.

*Use conditional statement, like if , somewhere to force the
function to return without the recursive call being executed.

Inline functions

* Instead of writing same code many times
we can create a function and can be called
when ever necessary.

* Main use of function in program is to save
memory space.

Demerit:

« Every time when a function is called lots of
extra time is required to execute the series of
instructions, like jumping to the function,
saving registers, pushing arguments into the
stack, returning control to the calling function.

Solution:

* Use macro definitions.

Drawback:

« But macros are not really functions

* Error checking does not occur during
compilation

+ C++ has a different solution to this problem.

+ C++ introduces a new feature called inline
function

It is a good practice to declare the class specification
first and then implement member functions out side
the class.

These functions can be made inline by prefixing the
keyword inline to its definition.

An inline function decreases the over head involved
in accessing member functions and make the use of
functions more efficient.

Any call to this function in a program is replaced by
the function itself. This is called inline expansion.

These functions are also called open subroutines.

An inline function is a function that is
expanded in line when it is invoked.

The compiler replaces the function call with
the corresponding function code, which is
similar to macros expansion.

Syntax:
Inline <return type> <function name> (parameters) \

There is no explicit function call. The function body is
substituted at the point of inline function, there by
the runtime overhead for function linkage
mechanism is reduced.

Example:
# include<iostream.h>

inline float square(float x)

{

KK * :
return x;

}

void main()
{

float num;

cout<<“ Enter a number =“;
cin >>num;
cout<< “Its square is ”<<square(num);

}

When to use inline functions ?

+ In general inline functions should not be used.

+ Needed when a fully developed and tested program
runs too slowly.

+ Inline functions can be used when member functions
have one very simple statement like return
statement.

* It is only useful to implement an inline function if the
time spent during a function call is more compared
to the function body execution time.

Default function Arguments

+ C++ allows to call a function without specifying all its
arguments.

+ Default values are specified when the function is declared.

+ The compiler looks at the prototype to see how many
arguments a function uses and alerts the program for possible
default values.

« Ex: // function declaration

float amount(float p, int t, float r=9.5);

+ The default value is specified just similar to a variable
initialization.

+ The above prototype declares a default value of 9.5 to the
argument r.

Value = amount(5000, 7);
* Here one argument is missing.

* This statement passes the value of 5000 to p and 7 to
t, then it takes the default value for the variable r.

Value = amount(5000, 7,10);
+ Here no arguments are missing.

* This statement passes the value of 5000 to p and 7 to
t, then it will not take the default value for the
variable r. It considers 10 to the variable r.

example

Int multiplication(int i, int j=5, int k=10);
//legal

Int multiplication(int i=5, int j, int k);

// illegal

Int multiplication(int i=0, int j, int k=10);
// illegal

Int multiplication(int i=5, int j=3, int k=10);
// legal

Program

void print_data(char=“-”, int =10);

// declaration

void main()

{

print_data();

// uses bothe default arguments
print_data(‘!’);

// assumes the 2™ argument as
default

}

print_data(‘*’, 8);
// ignores both default arguments
print_data(‘s’, 5);
// ignores both default arguments

void print_data(char ch, int count)
{

int i;

cout<<endl;

for (i=0;i<count; i++)

cout<<ch;

}

Function overloading

Overload refers to - use of the same thing for different
purposes.

C++ permits overloading of functions.

The Function overloading is one of the defining aspects
of the C++ programming language.

It provides support for compile-time polymorphism
and it also adds flexibility and convenience.

We can use the same function name to create
functions that perform a variety of different tasks. This
is known as function polymorphism.

Function overloading is the process of using the
same name for two or more functions.
Once a function is overloaded then each redefinition
of the function must use either different types of
parameters or a different number of parameters.
Using these differences that the compiler knows
which function to call in any given situation.
Ex: swap(int, int); // prototype

swap(float, float);

swap(int, int, int);

void show(int val) int main()

{

ss “<<val; show(25);

void show(double val) show(3.14);

{ show(“SIT Valachil”);
cout<<“double: “<<val; return(0);

} }

void show(char * val)

{ Here the parameters are
cout<<“character: “<<val; of different types.

}

program overloads myfun() using a different
number of parameters

#include <iostream> return 0;

int myfun(int i); }

// these differ in number of int myfun(int i)
parameters {

int myfun(int i, int j); return i:

int main() }

{ int myfun(int i, int j)
cout << myfun(10) <<" "; {

// calls myfunc(int i) return i*j;

cout << myfun(4, 5); }

// calls myfun(int i, int j)

Two functions differing only in their return
types cannot be overloaded.

For example, this is an invalid attempt to
overload myfun():

int myfun(int i);

float myfun(int i);

// Error: differing return types are insufficient
when overloading.

Two function declarations will appear to differ,
actually they do not differ.

For example, consider the following
declarations.

void f(int *p);

void f(int p[]); // error, *p is same as pl]

To the compiler *p is the same as p[ ],
although the two prototypes appear to differ
in the types of their parameter.

When a function name is declared more than once in a
particular scope, the compiler interprets the second
declaration as follows.

a) If the parameter lists of the functions differ either in
number or type, the functions are considered to be
overloaded.

int max(int, int);
float max(float, float, float);

b) If both the return type and the parameter list of the
function declarations match exactly, the second is treated as
re-declaration.

int max(int, int);
int max(int, int);

c) If the parameter lists of the function declarations match
exactly, but the return types differ, the 2nd is treated as
erroneous re-declaration.

int max(int, int);
float max(int, int);
d) If the parameter lists of the functions differ only in default
arguments, the second is treated as re-declaration.

int max(int, int);
int max(int, int =10);

Steps of Overload Resolution

* Function overload resolution is the process by which a function
call is associated with one function in a set of overloaded
functions.

* In the presence of many functions with the same name, one
function is selected for the arguments specified in the function
call.

* There are three steps in the process of function overload
resolution. We will use the following example to illustrate these
three steps:

Ex: void f();

void f( int );
void f( double, double = 3.4 );
void f( char*, char* );
int main(){ f(5.6);
return 0;

The steps of function overload resolution are
the following
1. Identify the set of overloaded functions
considered for the call and identify the properties of
the argument list in the function call.

2. Select the functions from the set of overloaded
functions that can be called with the arguments
specified in the call.

3. Select the function that best matches the call.

The first step of function overload resolution identifies the set
of overloaded functions considered for the call.

The functions in this set are called candidate functions.

A candidate function is a function with the same name as the
function that is called and for which a declaration is visible at
the point of the call.

In the example, there are four candidate functions in the
given example as follows.....

f(), f(int), f(double, double), and f(char*, char*).

The first step of function overload resolution also identifies
the properties of the argument list in the function call, that is,
the number of arguments and their types.

In the example, the argument list consists of one argument of
type double. f( 5.6);

« The second step of function overload resolution selects
the functions from the set of candidate functions found
in step 1 that can be called with the arguments specified
in the call.

« The functions thus selected are called the viable
functions.

+ Aviable function has the same number of parameters in
the argument list of the function call, or a viable function
has more parameters than there are arguments in the
argument list in the call and each additional parameter
has an associated default argument there must exist
conversions that can convert each argument in the list to
its corresponding parameter type.

In the example, there are two viable functions that can be
called with the argument list specified.

f(int) is a viable function because it has only one parameter
and because a conversion exists that can convert the
argument of type double to the parameter of type int.

f(double, double) is a viable function because a default
argument is provided for the function's second parameter
and its first parameter is of type double, which matches
exactly the type of the argument.

If the second step of the function overload resolution
process finds no viable function that can be called with the
given argument list, then the function call is in error. There
is no function that matches the call, and it is a no match
situation.

The third step of function overload resolution consists of
selecting the function that matches the function call the best.

This function is called the best viable function (also often called
the best match function). To select this function, the conversions
used to convert the arguments to the corresponding parameter
types are ranked.

In the example, When the viable function f(int) is considered, the
conversion applied to the argument of type double to convert it
to type int is a standard conversion.

When the viable function f(double, double) is considered, the
argument of type double is an exact match for the corresponding
parameter.

« Because an exact match is better than a standard
conversion— because not to do a conversion is
better than to do any conversion— the best viable
function selected for the call is f(double, double).

* If the third step of function overload resolution finds
no best viable function, then the function call is
ambiguous; that is, the call does not match any
viable function better than any other.