C++ - Chapter 1
C++ - Chapter 1
1|Page
Features of the Object-Oriented programming
1. Emphasis is on doing rather than procedure.
2. programs are divided into what are known as objects.
3. Data structures are designed such that they characterize
the objects.
4. Functions that operate on the data of an object are tied
together in the data structure.
5. Data is hidden and can’t be accessed by external
functions.
6. Objects may communicate with each other through
functions.
7. New data and functions can be easily added.
8. Follows bottom-up approach in program design.
2|Page
1.2 Basic concepts of OOPs:
1. Classes
A Class is a user-defined data-type which has data members
and member functions.
Data members are the data variables and member functions are the
functions used to manipulate these variables and together these
data members and member functions define the properties and
behaviour of the objects in a Class.
For Example: Consider the Class of Cars.
There may be many cars with different names and brand but all of
them will share some common properties like all of them will have
4 wheels, Speed Limit, Mileage range etc.
So here, Car is the class and wheels, speed limits, mileage are their
properties.
2. Objects
An Object is an identifiable entity with some characteristics and
behaviour.
An Object is an instance of a Class.
When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
Object take up space in memory and have an associated address
like structure or union in C.
When a program is executed the objects interact by sending
messages to one another.
Each object contains data and code to manipulate the data.
Objects can interact without having to know details of each other’s
data or code, it is sufficient to know the type of message accepted
and type of response returned by the objects.
3|Page
3. Data abstraction
Abstraction means displaying only essential information and
hiding the details.
Data abstraction refers to providing only essential information
about the data to the outside world, hiding the background details
or implementation.
For example: phone call, we don't know the internal processing.
In C++, we use abstract class and interface to achieve abstraction.
4. Data encapsulation
In Object-Oriented Programming, Encapsulation is defined as
binding together the data and the functions that manipulate them.
For example: capsule, it is wrapped with different medicines.
5. Inheritance
Inheritance is the process by which objects of one class acquire the
properties of another class.
In the concept of inheritance provides the idea of reusability.
This mean that we can add additional features to an existing class
without modifying it.
This is possible by designing a new class will have the combined
features of both the classes.
6. Polymorphism
The word polymorphism means having many forms.
In simple words, we can define polymorphism as the ability of a
message to be displayed in more than one form.
A person at the same time can have different characteristic. Like a
man at the same time is a father, a husband, an employee.
So, the same person posses different behaviour in different
situations. This is called polymorphism.
4|Page
An operation may exhibit different behaviours in different
instances.
The behaviour depends upon the types of data used in the
operation.
C++ supports operator overloading and function overloading.
Operator Overloading: The process of making an operator to
exhibit different behaviours in different instances is known as
operator overloading.
Function Overloading: Function overloading is using a single
function name to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
7. Dynamic binding
Binding refers to the linking of a procedure call to the code to the
executed in response to the call.
Dynamic binding means the code associated with a given
procedure call is not known until the time of the call at run-time.
It is associated with a polymorphic reference depends upon the
dynamic type of that reference.
8. Message passing
Objects communicate with one another by sending and receiving
information to each other.
A message for an object is a request for execution of a procedure
and therefore will invoke a function in the receiving object that
generates the desired results.
Message passing involves specifying the name of the object, the
name of the function and the information to be sent.
5|Page
1.3 Benefits of OOPs:
Oop offers several benefits to both the program designer
and the user.
Object-oriented contributes to the solution of many
problems associated with the development and quality of
software products.
The principal advantages are:
1. Through inheritance we can eliminate redundant code
and extend the use of existing classes.
2. We can build programs from the standard working
modules that communicate with one another, rather than
having to start writing the code from scratch. This leads to
saving of development time and higher productivity.
3. This principle of data hiding helps the programmer to
build secure programs that can’t be invaded by code in
other parts of the program.
4. It is possible to have multiple instances of an object to
co-exist without any interference.
5. It is easy to partition the work in a project based on
objects.
6. Object-oriented systems can be easily upgraded from
small to large systems.
7. Message passing techniques for communication between
objects makes the interface description with external
systems much simpler.
8. Software complexity can be easily managed.
6|Page
C vs. C++
7|Page
1.4 C++ Tokens, Variables, Constants and data types:
C++ TOKENS:
The smallest individual units in program are known as
tokens.
C++ has the following tokens.
i . Keywords - Keywords are reserved words which have
fixed meaning, and its meaning cannot be changed.
The meaning and working of these keywords are already
known to the compiler.
The keywords not found in ANSI C are shown in red letter.
8|Page
ii. Identifiers - Identifiers are names given to different
entries such as variables, structures, and functions.
Also, identifier names should have to be unique because
these entities are used in the execution of the program.
Ex. int minutesPerHour = 60;
iii. Constants - Constants are like a variable, except that
their value never changes during execution once defined.
Ex. const int SIDE = 50;
iv. Strings - Strings are objects that signify sequences of
characters.
Ex. char greeting[] = "Cloud";
v. Operators - C++ operator is a symbol that is used to
perform mathematical or logical manipulations.
Ex. ++ Increment operator
C++ Variable
Variable definition
A variable is a name of memory location.
It is used to store data. Its value can be changed and it can
be reused many times.
It is a way to represent memory location through symbol so
that it can be easily identified.
Syntax:
type variable_list;
Example:
int width, height, age;
char letter;
float area;
9|Page
Variable initialization
Variables are declared in the above example, but none of
them has been assigned any value. Variables can be
initialized, and the initial value can be assigned along with
their declaration.
Example:
int width, height=5, age=32;
char letter='A';
float area = 20.5;
Rules of declaring variables
1. Only alphabetic chars, digits and underscore are
permitted.
2. The name can’t start with a digit.
3. Upper case and lower-case letters are distinct.
4. A declared keyword can’t be used as a variable name.
In ANSI C the maximum length of a variable is 32 chars
but in C++ there is no bar.
C++ Constants:
Constants definition
Constants refer to as fixed values, unlike variables whose
value can be altered, constants - as the name implies does
not change, they remain constant.
Constant must have to be initialized at the time of creating
it, and new values cannot be assigned later to it.
There are two other different ways to define constants in
C++. These are:
-By using const keyword
-By using #define preprocessor
10 | P a g e
Syntax:
-const type constant_name;
-#define constant_name;
Example:
const int SIDE = 50;
#define VAL1 20
#include <iostream>
using namespace std;
#define VAL1 20
#define VAL2 6
#define Newline '\n'
int main()
{
int tot;
tot = VAL1 * VAL2;
cout << tot;
cout << Newline;
}
//Output:
120
11 | P a g e
C++ Data Types:
All variables use data-type during declaration to restrict the
type of data to be stored.
Therefore, we can say that data types are used to tell the
variables the type of data it can store.
Whenever a variable is defined in C++, the compiler
allocates some memory for that variable based on the data-
type with which it is declared.
Every data type requires a different amount of memory.
12 | P a g e
Integers typically requires 4 bytes of memory space and
ranges from -2147483648 to 2147483647.
-Character: Keyword used for character data type is char.
Characters typically requires 1 byte of memory space and
ranges from -128 to 127 or 0 to 255.
-Boolean: A boolean variable can store either true or false.
Keyword used for boolean data type is bool.
-Floating Point: Floating Point data type is used for
storing single precision floating point values or decimal
values. Keyword used for floating point data type is float.
Float variables typically requires 4 byte of memory space.
-Double Floating Point: Double Floating Point data type is
used for storing double precision floating point values or
decimal values.
Keyword used for double floating point data type is double.
Double variables typically requires 8 byte of memory
space.
-Valueless or Void: Void means without any value. void
datatype represents a valueless entity.
Void data type is used for those function which does not
returns a value.
-Wide Character: Wide character data type is also a
character data type but this data type has size greater than
the normal 8-bit datatype.
Represented by wchar_t.
It is generally 2 or 4 bytes long.
2.Derived Data Types: The data-types that are derived
from the primitive or built-in datatypes are referred to as
Derived Data Types. These can be of four types namely:
13 | P a g e
-Function
-Array
-Pointer
-Reference
3.Abstract or User-Defined Data Types: These data types
are defined by user itself. Like, defining a class in C++ or a
structure. C++ provides the following user-defined
datatypes:
-Class
-Structure
-Union
-Enumeration
-Typedef defined DataType
Datatype Modifiers
As the name implies, datatype modifiers are used with the
built-in data types to modify the length of data that a
particular data type can hold.
14 | P a g e
-Unsigned
-Short
-Long
// C++ program to sizes of data types
#include<iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char)
<< " byte" << endl;
cout << "Size of int : " << sizeof(int)
<< " bytes" << endl;
cout << "Size of short int : " << sizeof(short int)
<< " bytes" << endl;
cout << "Size of long int : " << sizeof(long int)
<< " bytes" << endl;
cout << "Size of signed long int : " << sizeof(signed long
int)
<< " bytes" << endl;
cout << "Size of unsigned long int : " << sizeof(unsigned
long int)
<< " bytes" << endl;
cout << "Size of float : " << sizeof(float)
<< " bytes" <<endl;
cout << "Size of double : " << sizeof(double)
<< " bytes" << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t)
15 | P a g e
<< " bytes" <<endl;
return 0;
}
//Output:
Size of char : 1 byte
Size of int : 4 bytes
Size of short int : 2 bytes
Size of long int : 8 bytes
Size of signed long int : 8 bytes
Size of unsigned long int : 8 bytes
Size of float : 4 bytes
Size of double : 8 bytes
Size of wchar_t : 4 bytes
16 | P a g e
1.5 Scope Resolution Operator:
In C++, scope resolution operator is ::. It is used for
following purposes.
1) To access a global variable when there is a local variable
with same name:
#include<iostream>
using namespace std;
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
//Output:
Value of global x is 0
Value of local x is 10
17 | P a g e
2) To define a function outside a class.
3) To access a class’s static variables.
4) In case of multiple Inheritance: If same variable name
exists in two ancestor classes, we can use scope resolution
operator to distinguish.
5) For namespace: If a class having the same name exists
inside two namespace we can use the namespace name with
the scope resolution operator to refer that class without any
conflicts
18 | P a g e
1.6 Basic Input / Output Statements:
C++ comes with libraries that provide us with many ways
for performing input and output.
In C++ input and output are performed in the form of a
sequence of bytes or more commonly known as streams.
Input Stream: If the direction of flow of bytes is from the
device(for example, Keyboard) to the main memory then
this process is called input.
Output Stream: If the direction of flow of bytes is opposite,
i.e. from main memory to device( display screen ) then this
process is called output.
19 | P a g e
Header files available in C++ for Input/Output operations
are:
iostream: iostream stands for standard input-output stream.
This header file contains definitions to objects like cin,
cout, cerr etc.
iomanip: iomanip stands for input output manipulators.
The methods declared in this files are used for
manipulating streams. This file contains definitions of setw,
setprecision, etc.
fstream: This header file mainly describes the file stream.
This header file is used to handle the data being read from a
file as input or data being written into the file as output.
The two keywords cout in C++ and cin in C++ are used
very often for printing outputs and taking inputs
respectively.
These two are the most basic methods of taking input and
printing output in C++.
To use cin and cout in C++ one must include the header file
iostream in the program.
Standard output stream (cout): Usually the standard
output device is the display screen.
The C++ cout statement is the instance of the ostream class.
It is used to produce output on the standard output device
which is usually the display screen.
The data needed to be displayed on the screen is inserted in
the standard output stream (cout) using the insertion
operator(<<).
20 | P a g e
#include <iostream>
int main() {
char str[] = "Hello C++";
21 | P a g e
#include <iostream>
using namespace std;
int main()
{
int age;
return 0;
}
Input :
18
Output:
Enter your age:
Your age is: 18
The above program asks the user to input the age.
The object cin is connected to the input device.
The age entered by the user is extracted from cin using the
extraction operator(>>) and the extracted data is then stored
in the variable age present on the right side of the
extraction operator.
Un-buffered standard error stream (cerr): The C++ cerr
is the standard error stream which is used to output the
errors.
This is also an instance of the iostream class.
22 | P a g e
As cerr in C++ is un-buffered so it is used when one needs
to display the error message immediately.
It does not have any buffer to store the error message and
display later.
#include <iostream>
int main()
{
cerr << "An error occured";
return 0;
}
Output:
An error occurred
buffered standard error stream (clog): This is also an
instance of iostream class and used to display errors but
unlike cerr the error is first inserted into a buffer and is
stored in the buffer until it is not fully filled.
The error message will be displayed on the screen too.
#include <iostream>
int main()
{
23 | P a g e
clog << "An error occured";
return 0;
}
Output:
An error occured
24 | P a g e
1.7 Structure of a C ++ program:
A C++ program is structured in a specific and particular
manner. In C++, a program is divided into the following
three sections:
1.Standard Libraries Section
2.Main Function Section
3.Function Body Section
For example, let’s look at the implementation of the Hello
World program:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
return 0;
}
25 | P a g e
namespace is a prefix that is applied to all the names in a
certain set. iostream file defines two names used in this
program - cout and endl.
This code is saying: Use the cout and endl tools from the
std toolbox.
26 | P a g e
1.8 Control Structure:
Control Structures are just a way to specify flow of control
in programs.
Any algorithm or program can be more clear and
understood if they use self-contained modules called as
logic or control structures.
It basically analyzes and chooses in which direction a
program flows based on certain parameters or conditions.
There are three basic types of logic, or flow of control,
known as:
1. Sequential Logic (Sequential Flow)
Sequential logic as the name suggests follows a serial or
sequential flow in which the flow depends on the series of
instructions given to the computer.
Unless new instructions are given, the modules are
executed in the obvious sequence.
The sequences may be given, by means of numbered steps
explicitly.
Also, implicitly follows the order in which modules are
written.
Most of the processing, even some complex problems, will
generally follow this elementary flow pattern.
27 | P a g e
Sequential Control flow
29 | P a g e
3.Iteration Logic (Repetitive Flow)
The Iteration logic employs a loop which involves a repeat
statement followed by a module known as the body of a
loop.
The two types of these structures are:
1.Repeat-For Structure
This structure has the form:
Repeat for i = A to N by I:
[Module]
[End of loop]
Here, A is the initial value, N is the end value and I is the
increment. The loop ends when A>B. K increases or
decreases according to the positive and negative value of I
respectively.
30 | P a g e
Repeat-For Flow
2.Repeat-While Structure
It also uses a condition to control the loop. This structure
has the form:
Repeat while condition:
[Module]
[End of Loop]
31 | P a g e
Repeat While Flow
32 | P a g e
1.8.1 Conditional Statements:
C++ conditional statements allow you to make a decision,
based upon the result of a condition.
These statements are called Decision Making Statements or
Conditional Statements.
So far, we have seen that all set of statements in a C++
program gets executed sequentially in the order in which
they are written and appear.
This occurs when there is no jump based statements or
repetitions of certain calculations.
But some situations may arise where we may have to
change the order of execution of statements depending on
some specific conditions.
This involves a kind of decision making from a set of
calculations.
It is to be noted that C++ assumes any non-zero or non-null
value as true and if zero or null, treated as false.
This type of structure requires that the programmers
indicate several conditions for evaluation within a program.
The statement(s) will get executed only if the condition
becomes true and optionally, alternative statement or set of
statements will get executed if the condition becomes false.
The flowchart of the Decision-making technique in C++
can be expressed as:
33 | P a g e
C++ languages have such decision-making capabilities
within its program by the use of following the decision
making statements:
Decision Making Statements in C++
1.if statement
2.if-else statement
3. nested if statements
4. if-else-if ladder
5. switch statement
34 | P a g e
if statement in C++
if statement is the most simple decision making statement.
It is used to decide whether a certain statement or block of
statements will be executed or not i.e if a certain condition
is true then a block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, condition after evaluation will be either true or false.
C if statement accepts boolean values – if the value is true
then it will execute the block of statements below it
35 | P a g e
otherwise not. If we do not provide the curly braces ‘{‘ and
‘}’ after if(condition) then by default if statement will
consider the first immediately below statement to be inside
its block.
Example:
// C++ program to illustrate If statement
#include<iostream>
using namespace std;
int main()
{
int i = 10;
36 | P a g e
if (i > 15)
{
cout<<"10 is less than 15";
}
cout<<"I am Not in if";
}
Output:
I am Not in if
As the condition present in the if statement is false. So, the
block below the if statement is not executed.
if-else in C++
The if statement alone tells us that if a condition is true it
will execute a block of statements and if the condition is
false it won’t.
But what if we want to do something else if the condition is
false.
We can use the else statement with if statement to execute
a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
37 | P a g e
}
Flowchart:
Example:
// C++ program to illustrate if-else statement
#include<iostream>
using namespace std;
int main()
{
int i = 20;
if (i < 15)
cout<<"i is smaller than 15";
else
38 | P a g e
cout<<"i is greater than 15";
return 0;
}
Output:
i is greater than 15
nested-if in C++
Nested if statements means an if statement inside another if
statement.
C++ allows us to nested if statements within if statements,
i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
39 | P a g e
Flowchart
Example:
// C++ program to illustrate nested-if statement
#include <iostream>
using namespace std;
int main()
{
int i = 10;
40 | P a g e
if (i == 10)
{
// First if statement
if (i < 15)
cout<<"i is smaller than 15\n";
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
cout<<"i is smaller than 12 too\n";
else
cout<<"i is greater than 15";
}
return 0;
}
Output:
i is smaller than 15
i is smaller than 12 too
42 | P a g e
Example:
// C++ program to illustrate if-else-if ladder
#include<iostream>
using namespace std;
int main()
{
int i = 20;
if (i == 10)
cout<<"i is 10";
else if (i == 15)
cout<<"i is 15";
else if (i == 20)
cout<<"i is 20";
else
cout<<"i is not present";
}
Output:
i is 20
43 | P a g e
Switch is a control statement that allows a value to change
control of execution.
Syntax:
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any
cases
}
Important Points about Switch Case Statements:
1.The expression provided in the switch should result in a
constant value otherwise it would not be valid.
Valid expressions for switch:
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)
// Variable expression are allowed provided
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)
2.Duplicate case values are not allowed.
3.The default statement is optional.
Even if the switch case statement do not have a default
statement,it would run without any problem.
4.The break statement is used inside the switch to terminate
a statement sequence. When a break statement is reached,
44 | P a g e
the switch terminates, and the flow of control jumps to the
next line following the switch statement.
5.The break statement is optional. If omitted, execution will
continue on into the next case. The flow of control will fall
through to subsequent cases until a break is reached.
6.Nesting of switch statements are allowed, which means
you can have switch statements inside another switch.
However nested switch statements should be avoided as it
makes program more complex and less readable.
Flowchart
45 | P a g e
Example:
// Following is a simple C++ program
// to demonstrate syntax of switch.
include <iostream>
using namespace std;
int main() {
int x = 2;
switch (x)
{
case 1:
cout << "Choice is 1";
break;
case 2:
cout << "Choice is 2";
break;
case 3:
cout << "Choice is 3";
break;
default:
cout << "Choice other than 1, 2 and 3";
break;
}
return 0;
}
Output:
Choice is 2
46 | P a g e
1.8.2 Looping Statements:
Loops in programming come into use when we need to
repeatedly execute a block of statements.
In computer programming, a loop is a sequence of
instructions that is repeated until a certain condition is
reached.
-An operation is done, such as getting an item of data and
changing it, and then some condition is checked such as
whether a counter has reached a prescribed number.
-Counter not Reached: If the counter has not reached the
desired number, the next instruction in the sequence returns
to the first instruction in the sequence and repeat it.
-Counter reached: If the condition has been reached, the
next instruction “falls through” to the next sequential
instruction or branches outside the loop.
There are mainly two types of loops:
-Entry Controlled loops: In this type of loops the test
condition is tested before entering the loop body. For Loop
and While Loop are entry controlled loops.
-Exit Controlled Loops: In this type of loops the test
condition is tested or evaluated at the end of loop body.
Therefore, the loop body will execute atleast once,
irrespective of whether the test condition is true or false. do
– while loop is exit controlled loop.
47 | P a g e
for Loop
A for loop is a repetition control structure which allows us
to write a loop that is executed a specific number of times.
The loop enables us to perform n number of steps together
in one line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
In for loop, a loop variable is used to control the loop. First
initialize this loop variable to some value, then check
whether this variable is less than or greater than counter
value. If statement is true, then loop body is executed and
loop variable gets updated . Steps are repeated till exit
condition comes.
48 | P a g e
Initialization Expression: In this expression we have to
initialize the loop counter to some value. for example: int
i=1;
Test Expression: In this expression we have to test the
condition. If the condition evaluates to true then we will
execute the body of loop and go to update expression
otherwise we will exit from the for loop. For example: i <=
10;
Update Expression: After executing loop body this
expression increments/decrements the loop variable by
some value. for example: i++;
Equivalent flow diagram for loop :
49 | P a g e
Example:
// C++ program to illustrate for loop
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
50 | P a g e
cout << "Hello World\n";
}
return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
While Loop
While studying for loop we have seen that the number of
iterations is known beforehand, i.e. the number of times the
loop body is needed to be executed is known to us.
while loops are used in situations where we do not know
the exact number of iterations of loop beforehand.
The loop execution is terminated on the basis of test
condition.
Syntax:
We have already stated that a loop is mainly consisted of
three statements – initialization expression, test expression,
update expression.
51 | P a g e
The syntax of the three loops – For, while and do while
mainly differs on the placement of these three statements.
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
Flow Diagram:
52 | P a g e
Example:
// C++ program to illustrate while loop
#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{
cout << "Hello World\n";
// update expression
i++;
}
return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
53 | P a g e
do while loop
In do while loops also the loop execution is terminated on
the basis of test condition.
The main difference between do while loop and while loop
is in do while loop the condition is tested at the end of loop
body, i.e do while loop is exit controlled whereas the other
two loops are entry controlled loops.
Note: In do while loop the loop body will execute at least
once irrespective of test condition.
Syntax:
initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
Flow Diagram:
54 | P a g e
Example:
// C++ program to illustrate do-while loop
#include <iostream>
using namespace std;
int main()
{
int i = 2; // Initialization expression
do
{
// loop body
cout << "Hello World\n";
// update expression
i++;
return 0;
}
Output:
Hello World
break:
This loop control statement is used to terminate the loop.
As soon as the break statement is encountered from within
a loop, the loop iterations stops there and control returns
from the loop immediately to the first statement after the
loop.
Syntax:
break;
Basically break statements are used in the situations when
we are not sure about the actual number of iterations for the
loop or we want to terminate the loop based on some
condition.
Flowchart
56 | P a g e
Example:
// CPP program to illustrate
// Linear Search
#include <iostream>
using namespace std;
return 0;
}
57 | P a g e
Output:
Element found at position: 3
continue:
This loop control statement is just like the break statement.
The continue statement is opposite to that of break
statement, instead of terminating the loop, it forces to
execute the next iteration of the loop.
As the name suggest the continue statement forces the loop
to continue or execute the next iteration.
When the continue statement is executed in the loop, the
code inside the loop following the continue statement will
be skipped and next iteration of the loop will begin.
Syntax:
continue;
Flowchart
58 | P a g e
Example:
// C++ program to explain the use
// of continue statement
#include <iostream>
using namespace std;
int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {
else
// otherwise print the value of i
cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 5 7 8 9 10
59 | P a g e
goto:
The goto statement in C/C++ also referred to as
unconditional jump statement can be used to jump from
one point to another within a function.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
In the above syntax, the first line tells the compiler to go to
or jump to the statement marked as a label.
Here label is a user-defined identifier which indicates the
target statement.
The statement immediately followed after ‘label:’ is the
destination statement.
The ‘label:’ can also appear before the ‘goto label;’
statement in the above syntax.
Flowchart
60 | P a g e
Example:
// C++ program to print numbers
// from 1 to 10 using goto statement
#include <iostream>
using namespace std;
return:
The return in C or C++ returns the flow of the execution to
the function from where it is called.
This statement does not mandatorily need any conditional
statements.
As soon as the statement is executed, the flow of the
program stops immediately and return the control from
where it was called.
The return statement may or may not return anything for a
void function, but for a non-void function, a return value is
must be returned.
Syntax:
return[expression];
62 | P a g e
Example:
// C++ code to illustrate return
// statement
#include <iostream>
using namespace std;
// non-void return type
// function to calculate sum
int SUM(int a, int b)
{
int s1 = a + b;
return s1;
}
// returns void
// function to print
void Print(int s2)
{
cout << "The sum is "<< s2;
return;
}
int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
Print(sum_of);
return 0;
}
Output:
The sum is 20
63 | P a g e
1.9 Arrays, Pointer, References:
Arrays
An array in C++ is a collection of items stored at
contiguous memory locations and elements can be accessed
randomly using indices of an array.
They are used to store similar type of elements as in the
data type must be the same for all elements.
They can be used to store collection of primitive data types
such as int, float, double, char, etc of any particular type.
To add to it, an array in C or C++ can store derived data
types such as the structures, pointers etc.
Given below is the picturesque representation of an array.
We can use normal variables (v1, v2, v3, ..) when we have
a small number of objects, but if we want to store a large
number of instances, it becomes difficult to manage them
with normal variables.
The idea of an array is to represent many instances in one
variable.
1.Array declaration in C/C++:
There are various ways in which we can declare an array. It
can be done by specifying its type and size, by initializing it
or both.
64 | P a g e
1.Array declaration by specifying size
// Array declaration by specifying size
int arr1[10];
// With recent C/C++ versions, we can also declare an array
of user specified size
int n = 10;
int arr2[n];
2.Array declaration by initializing elements
// Array declaration by initializing elements
int arr[] = { 10, 20, 30, 40 }
// Compiler creates an array of size 4.
// above is same as "int arr[4] = {10, 20, 30, 40}"
3.Array declaration by specifying size and initializing
elements
// Array declaration by specifying size and initializing
// elements
int arr[6] = { 10, 20, 30, 40 }
// Compiler creates an array of size 6, initializes first
//4 elements as specified by user and rest two elements as 0.
// above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"
65 | P a g e
5.Sorting becomes easy as it can be accomplished by
writing less line of code.
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing
array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output:/p>
10
0
66 | P a g e
20
0
30
Pointer
Pointer is a variable in C++ that holds the address of
another variable.
They have data type just like variables, for example an
integer type pointer can hold the address of an integer
variable and an character type pointer can hold the address
of char variable.
Syntax
data_type *pointer_name;
int *ptr; //ptr can point to an address which holds int data
67 | P a g e
Assigning the address of a variable to a pointer using unary
operator (&) which returns the address of that variable.
Accessing the value stored in the address using unary
operator (*) which returns the value of the variable located
at the address specified by its operand.
The reason we associate data type to a pointer is that it
knows how many bytes the data is stored in.
When we increment a pointer, we increase the pointer by
the size of data type to which it points.
Example
// C++ program to illustrate Pointers in C++
#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗ p;
p=&number;//stores the address of number variable
68 | P a g e
cout<<"Address of number variable
is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
Output:
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
Value of p variable is:30
Advantage of pointer
1) Pointer reduces the code and improves the performance,
it is used to retrieving strings, trees etc. and used with
arrays, structures and functions.
2) We can return multiple values from function using
pointer.
3) It makes you able to access any memory location in the
computer's memory.
Usage of pointer
There are many usage of pointers in C++ language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using
malloc() and calloc() functions where pointer is used.
2) Arrays, Functions and Structures
Pointers in c language are widely used in arrays, functions
and structures. It reduces the code and improves the
performance.
69 | P a g e
Symbols used in pointer
Symbol Name Description
& (ampersand Address Determine the address
sign) operator of a variable.
∗ (asterisk Indirection Access the value of an
sign) operator address.
}
return 0;
}
Output:
1
2
3
4
5
6
71 | P a g e
// Pointer moves to the next int position (as if it was an
array)
++p;
/* All the following three cases are same they increment the
value
* of variable that the pointer p points.
*/
++*p;
++(*p);
++*(p);
Pointers to pointers
In C++, we can create a pointer to a pointer that in turn
may point to data or other pointer.
The syntax simply requires the unary operator (*) for each
level of indirection while declaring the pointer.
char a;
char *b;
char ** c;
a = ’g’;
b = &a;
c = &b;
Here b points to a char that stores ‘g’ and c points to the
pointer b.
Void Pointers
This is a special type of pointer available in C++ which
represents absence of type.
72 | P a g e
void pointers are pointers that point to a value that has no
type (and thus also an undetermined length and
undetermined dereferencing properties).
This means that void pointers have great flexibility as it can
point to any data type.
There is payoff for this flexibility.
These pointers cannot be directly dereferenced.
They have to be first transformed into some other pointer
type that points to a concrete data type before being
dereferenced.
NULL Pointers
Null pointer is a pointer which point nowhere and not just
an invalid address.
Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
int *ptr2 = NULL;
References
A reference variable is an alias, that is, another name for an
already existing variable.
Once a reference is initialized with a variable, either the
variable name or the reference name may be used to refer
to the variable.
73 | P a g e
Creating References in C++
Think of a variable name as a label attached to the
variable's location in memory.
You can then think of a reference as a second label attached
to that memory location.
Therefore, you can access the contents of the variable
through either the original variable name or the reference.
For example, suppose we have the following example −
int i = 17;
We can declare reference variables for i as follows.
int& r = i;
Read the & in these declarations as reference. Thus, read
the first declaration as "r is an integer reference initialized
to i" and read the second declaration as "s is a double
reference initialized to d.".
When a variable is declared as reference, it becomes an
alternative name for an existing variable.
A variable can be declared as reference by putting ‘&’ in
the declaration.
Example
#include<iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
74 | P a g e
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << endl ;
return 0;
}
Output:
x = 20
ref = 30
Applications :
1.Modify the passed parameters in a function : If a
function receives a reference to a variable, it can modify
the value of the variable. For example, in the following
program variables are swapped using references.
Example
#include<iostream>
using namespace std;
int main()
{
int a = 2, b = 3;
swap( a, b );
cout << a << " " << b;
return 0;
}
Output:
32
2.Avoiding copy of large structures : Imagine a function
that has to receive a large object. If we pass it without
reference, a new copy of it is created which causes wastage
of CPU time and memory. We can use references to avoid
this.
Example
struct Student {
string name;
string address;
int rollNo;
}
int main()
{
vector<int> vect{ 10, 20, 30, 40 };
// Printing elements
for (int x : vect)
cout << x << " ";
return 0;
}
int main()
{
vector<string> vect{"geeksforgeeks practice",
"geeksforgeeks write",
"geeksforgeeks ide"};
return 0;
}
References vs Pointers
Both references and pointers can be used to change local
variables of one function inside another function.
Both of them can also be used to save copying of big
objects when passed as arguments to functions or returned
from functions, to get efficiency gain.
Despite above similarities, there are following differences
between references and pointers.
A pointer can be declared as void but a reference can never
be void.
78 | P a g e
1.10 Function: Call by value, Call by reference:
Functions in C++
A function is a set of statements that take inputs, do some
specific computation and produces output.
The idea is to put some commonly or repeatedly done task
together and make a function so that instead of writing the
same code again and again for different inputs, we can call
the function.
The general form of a function is:
return_type function_name([ arg1_type arg1_name, ... ])
{
code
}
Example:
Below is a simple C/C++ program to demonstrate
functions.
#include <iostream>
using namespace std;
79 | P a g e
int main() {
int a = 10, b = 20;
Call by Value
In this parameter passing method, values of actual
parameters are copied to function’s formal parameters and
the two types of parameters are stored in different memory
locations.
80 | P a g e
So any changes made inside functions are not reflected in
actual parameters of caller.
Example
In the below code, value of x is not modified using the
function fun().
#include <iostream>
using namespace std;
void fun(int x) {
x = 30;
}
int main() {
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
Output:
x = 20
Call by Reference
Call by Reference Both actual and formal parameters refer
to same locations, so any changes made inside the function
are actually reflected in actual parameters of caller.
we can use pointers to get the effect of pass by reference.
Example, consider the below program.
81 | P a g e
The function fun() expects a pointer ptr to an integer (or an
address of an integer).
It modifies the value at the address ptr.
The dereference operator * is used to access the value at an
address.
In the statement ‘*ptr = 30’, value at address ptr is changed
to 30.
The address operator & is used to get the address of a
variable of any data type.
In the function call statement ‘fun(&x)’, the address of x is
passed so that x can be modified using its address.
#include <iostream>
using namespace std;
int main() {
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
}
Output:
x = 30
82 | P a g e
1.11 Inline function, Default arguments:
Inline function
C++ provides an inline functions to reduce the function call
overhead.
Inline function is a function that is expanded in line when it
is called.
When the inline function is called whole code of the inline
function gets inserted or substituted at the point of inline
function call.
This substitution is performed by the C++ compiler at
compile time.
Inline function may increase efficiency if it is small.
The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
Remember, inlining is only a request to the compiler, not a
command.
Compiler can ignore the request for inlining.
Compiler may not perform inlining in such circumstances
like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return
statement doesn’t exist in function body.
5) If a function contains switch or goto statement.
83 | P a g e
Example
The following program demonstrates the use of use of
inline function.
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
Output:
The cube of 3 is: 27
84 | P a g e
#include<iostream>
using namespace std;
25
50
80
Default arguments are different from constant arguments as
constant arguments can't be changed whereas default
arguments can be overwritten if required.
Default arguments are overwritten when calling function
provides values for them. For example, calling of function
85 | P a g e
sum(10, 15, 25, 30) overwrites the value of z and w to 25
and 30 respectively.
During calling of function, arguments from calling function
to called function are copied from left to right. Therefore,
sum(10, 15, 25) will assign 10, 15 and 25 to x, y, and z.
Therefore, the default value is used for w only.
Once default value is used for an argument in function
definition, all subsequent arguments to it must have default
value. It can also be stated as default arguments are
assigned from right to left. For example, the following
function definition is invalid as subsequent argument of
default variable z is not default.
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
86 | P a g e
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
Output:
Here is int 10
Here is float 10.1
Here is char* ten
87 | P a g e
Advantages of Function overloading
The main advantage of function overloading is to the
improve the code readability and allows code reusability.
Imagine if we didn’t have function overloading, we either
have the limitation to add only two integers or we had to
write different name functions for the same task addition,
this would reduce the code readability and reusability.
88 | P a g e