0% found this document useful (0 votes)
17 views61 pages

C++ Notes Unit-I

The document provides an overview of different programming paradigms, focusing on imperative and declarative paradigms, along with their subcategories such as procedural, object-oriented, and functional programming. It discusses key concepts in object-oriented programming including classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing. Additionally, it outlines the structure of a C++ program and the use of comments for code readability.

Uploaded by

21-5C1 D.Swetha.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views61 pages

C++ Notes Unit-I

The document provides an overview of different programming paradigms, focusing on imperative and declarative paradigms, along with their subcategories such as procedural, object-oriented, and functional programming. It discusses key concepts in object-oriented programming including classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing. Additionally, it outlines the structure of a C++ program and the use of comments for code readability.

Uploaded by

21-5C1 D.Swetha.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

UNIT-I

Different paradigms for problem solving

Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming
language . Apart from varieties of programming language there are lots of paradigms to
fulfil each and every demand. They are discussed below:

1. Imperative programming paradigm

a) Procedural programming paradigm


b) Object oriented programming
c) Parallel processing approach

2. Declarative programming paradigm

a) Logic programming paradigms


b) Functional programming paradigms
c) Database/Data driven programming approach

1. Imperative programming paradigm

It is one of the oldest programming paradigm. It features close relation relation to machine
architecture. It is based on Von Neumann architecture. It works by changing the program
state through assignment statements. It performs step by step task by changing state.
The main focus is on how to achieve the goal. The paradigm consist of several statements
and after execution of all the result is stored.

Advantage:

Very simple to implement


It contains loops, variables etc.

Disadvantage:

Complex problem cannot be solved


Less efficient and less productive
Parallel programming is not possible

Eg:
C, FORTRAN, BASIC

a) Procedural programming paradigm

This paradigm emphasizes on procedure in terms of under lying machine model.

1
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

There is no difference in between procedural and imperative approach. It has the ability to
reuse the code and it was boon at that time when it was in use because of its reusability.

Eg: C, C++, JAVA etc.

b) Object oriented programming

The program is written as a collection of classes and object which are meant for
communication. The smallest and basic entity is object and all kind of computation is
performed on the objects only. More emphasis is on data rather procedure. It can handle
almost all kind of real life problems.

Advantages:

Data security
Inheritance
Code reusability
Flexible and abstraction is also present

Eg:

Simula(first OOP language) , Java , C++ ,Objective-C , Visual Basic .NET, Python, Ruby,
Smalltalk

b) Parallel processing approach

Parallel processing is the processing of program instructions by dividing them


among multiple processors. A parallel processing system posses many numbers of
processor with the objective of running a program in less time by dividing them. This
approach seems to be like divide and conquer. Examples are NESL (one of the oldest one)
and C/C++ also supports because of some library function.

2. Declarative programming paradigm

It is divided as Logic, Functional, Database. In computer science the declarative


programming is a style of building programs that expresses logic of computation without
talking about its control flow. It often considers programs as theories of some logic.It may
simplify writing parallel programs. The focus is on what needs to be done rather how it
should be done basically emphasize on what code code is actually doing. It just declare
the result we want rather how it has be produced. This is the only difference between
imperative (how to do) and declarative (what to do) programming paradigms.

a) Logic programming paradigms

It can be termed as abstract model of computation. It would solve logical problems


like puzzles, series etc. In logic programming we have a knowledge base which we know
before and along with the question and knowledge base which is given to machine, it

2
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

produces result. In normal programming languages, such concept of knowledge base is


not available but while using the concept of artificial intelligence, machine learning we
have some models like Perception model which is using the same mechanism.In logical
programming the main emphasize is on knowledge base and the problem. The execution
of the program is very much like proof of mathematical statement,
e.g., Prolog

b) Functional programming paradigms

The functional programming paradigms has its roots in mathematics and it is language
independent. The key principal of this paradigms is the execution of series of
mathematical functions. The central model for the abstraction is the function which are
meant for some specific computation and not the data structure. Data are loosely coupled
to functions.The function hide their implementation. Function can be replaced with their
values without changing the meaning of the program. Some of the languages like perl,
javascript mostly uses this paradigm.
c) Database/Data driven programming approach

This programming methodology is based on data and its movement. Program statements
are defined by data rather than hard-coding a series of steps. A database program is the
heart of a business information system and provides file creation, data entry, update, query
and reporting functions. There are several programming languages that are developed
mostly for database application. For example SQL. It is applied to streams of structured
data, for filtering, transforming, aggregating (such as computing statistics), or calling other
programs. So it has its own wide application.

Differences between Procedural and Object Oriented Programming

Procedural Programming:
Procedural Programming can be defined as a programming model which is derived from
structured programming, based upon the concept of calling procedure. Procedures, also
known as routines, subroutines or functions, simply consist of a series of computational
steps to be carried out. During a program’s execution, any given procedure might be called
at any point, including by other procedures or itself.

Languages used in Procedural Programming:

FORTRAN, ALGOL, COBOL,


BASIC, Pascal and C.

Object Oriented Programming:


Object oriented programming can be defined as a programming model which is based
upon the

3
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

concept of objects. Objects contain data in the form of attributes and code in the form of
methods. In object oriented programming, computer programs are designed using the
concept of objects that interact with real world. Object oriented programming languages
are various but the most popular ones are class-based, meaning that objects are instances
of classes, which also determine their types.

Languages used in Object Programming:Java, C++, C#, Python,

PHP, JavaScript, Ruby, Perl,


Objective-C, Dart, Swift, Scala. Oriented

Procedural Oriented Programming Object Oriented Programming


In procedural programming, program is In object oriented programming, program
divided into small parts calledfunctions . is divided into small parts calledobjects .
Procedural programming followstop down Object oriented programming follows
approach . bottom up approach .
There is no access specifier in procedural Object oriented programming have access
programming. specifiers like private, public, protected
etc.
Adding new data and function is not easy. Adding new data and function is easy.
Procedural programming does not have Object oriented programming provides
any proper way for hiding data so it isless data hiding so it ismore secure .
secure .
In procedural programming, overloading is Overloading is possible in object oriented
not possible. programming.
In procedural programming, function is In object oriented programming, data is
more important than data. more important than function.
Procedural programming is based on Object oriented programming is based on
unreal world . real world .
Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.

Object-oriented programming – As the name suggests uses objects in programming.


Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc in programming. The main aim of OOP is to bind together the data and
the functions that operate on them so that no other part of the code can access this data
except that function.

Class:

The building block of C++ that leads to Object Oriented programming is a Class. It is a user
defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A class is like a blueprint for an
object.

4
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

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.

 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.
 In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can apply brakes, increase speed etc.

We can say that a Class in C++ is a blu-print representing a group of objects which shares
some common properties and behaviours.

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

Encapsulation:

In normal terms, Encapsulation is defined as wrapping up of data and information under a


single unit. In Object Oriented Programming, Encapsulation is defined as binding together
the data and the functions that manipulate them.

Consider a real-life example of encapsulation, in a company, there are different sections


like the accounts section, finance section, sales section etc. The finance section handles
all the financial transactions and keeps records of all the data related to finance. Similarly,
the sales section handles all the sales related activities and keeps records of all the sales.
Now there may arise a situation when for some reason an official from the finance section
needs all the data about sales in a particular month. In this case, he is not allowed to
directly access the data of the sales section. He will first have to contact some other
officer in the sales section and then request him to give the particular data. This is what
encapsulation is. Here the data of the sales section and the employees that can
manipulate them are wrapped under a single name “sales section”.

5
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Encapsulation also leads to data abstraction or hiding . As using encapsulation also hides
the data. In the above example, the data of any of the section like sales, finance or
accounts are hidden from any other section.

Abstraction:

Data abstraction is one of the most essential and important features of object-oriented
programming in C++. 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.

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car but he
does not know about how on pressing accelerator the speed is actually increasing, he
does not know about the inner mechanism of the car or the implementation of accelerator,
brakes etc in the car. This is what abstraction is.

 Abstraction using Classes : We can implement Abstraction in C++ using classes.


The class helps us to group data members and member functions using available
access specifiers. A Class can decide which data member will be visible to the
outside world and which is not.
 Abstraction in Header files : One more type of abstraction in C++ can be header files.
For example, consider the pow() method present in math.h header file. Whenever
we need to calculate the power of a number, we simply call the function pow()
present in the math.h header file and pass the numbers as arguments without
knowing the underlying algorithm according to which the function is actually
calculating the power of numbers.

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.

6
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

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.

Inheritance:

The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object Oriented
Programming.

 Sub Class: The class that inherits properties from another class is called Sub class
or Derived Class.
 Super Class:The class whose properties are inherited by sub class is called Base
Class or Super class.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that
we want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.

Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

7
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Dynamic Binding:
In dynamic binding, the code to be executed in response to function call is decided at
runtime. C++ has virtual functions to support this.

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.

STRUCTURE OF C++ PROGRAM

Programs are a sequence of instructions or statements. These statements form the


structure of a C++ program. C++ program structure is divided into various sections,
namely,headers, class definition, member functions definitions andmain function.

8
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

C++ provides the flexibility of writing a program with or without a class and its member
functions definitions. A simple C++ program (without a class) includes comments,
headers, namespace, main() and input/output statements.

Comments:

Comments are used to increase the readability of a program and to describe its
functioning. Comments are not executable statements and hence, do not increase the size
of a file.

C++ supports two comment styles:

1. single line comment

2. multiline comment.

Single line comments are used to define line-by-line descriptions. Double slash (//) is
used to represent single line comments. To understand the concept of single line
comment, consider this statement.

/ / An example to demonstrate single line comment It can also be written as

Multiline comments are used to define multiple lines descriptions and are represented as /
* * /. For example, consider this statement.

/* An example to demonstrate

multiline comment */

Generally, multiline comments are not used in C++ as they require more space on the line.
However, they are useful within the program statements where single line comments

9
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

cannot be used. For example, consider this statement.

for(int i = 0; i<10; //loop runs 10 times i++)

Compiler ignores everything written after the single line comment and hence, an error
occurs. Therefore, in this case multiline comments are used. For example, consider this
statement.

for(int i = 0; i<10; /*loop runs 10 times */ i++)

Headers:

Generally, a program includes various programming elements like built-in functions,


classes, keywords, constants, operators, etc., that are already defined in the standard C++
library. In order to use such pre-defined elements in a program, an appropriate header
must be included in the program. The standard headers contain the information like
prototype, definition and return type of library functions, data type of constants, etc. As a
result, programmers do not need to explicitly declare (or define) the predefined
programming elements.

Standard headers are specified in a program through the preprocessor directive"


#include. For example, When the compiler processes the instruction #inc1ude<iostream>,
it includes the contents of iostream in the program. This enables the programmer to use
standard input, output and error facilities that are provided only through the standard
streams defined in <iostream>. These standard streams process data as a stream of
characters, that is, data is read and displayed in a continuous flow. The standard streams
defined in <iostream> are listed here.

• cin (pronounced "see in") : It is the standard input stream that is associated with the
standard input device (keyboard) and is used to take the input from users.

• cout (pronounced "see out") : It is the standard output stream that is associated with the
standard output device (monitor) and is used to display the output to users.

• cerr (pronounced "see err") : It is the standard error stream that is associated with the
standard error device (monitor) and is used to report errors to the users. The cerr object
does not have a buffer (temporary storage area) and hence, immediately reports errors to
users. '

• clog (pronounced "see log"): It is the buffered error stream that is associated with the
standard error device (computer screen) and is used to report errors to users. Unlike cerr,
clog reports errors to users only when the buffer is full

For many years, C++ applied C-style headers, that is, .h extension in the headers. However,
the standard C++ library introduced new-style headers that include only header name.
Hence, the most modem compilers do not require any extension, though they support the
older .h extension.

10
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Eg:

In C <iostream.h>
In C++ <iostream>

Namespace:

One of the new features added to this language is namespace. A namespace permits
grouping of various entities like classes, objects, functions and various C++ tokens, etc.,
under a single name. Different users can create separate namespaces and thus can use
similar names of the entities. This avoids compile-time error that may exist due to
identical-name conflicts.

The C++ Standards Committee has rearranged the entities of the standard library under a
namespace called std. Namespace std informs the compiler to include all the entities
present in the namespace std. The entities of a namespace can be accessed in different
ways which are listed here.

• By specifying the using directive

using namespace std;

cout<<"Hello World";

• By specifying the full member name

std: :cout<<"Hello World";

• By specifying the using declaration

using std:: cout;

cout<<"Hello World";

As soon as the new-style header is included, its contents are included in the std
namespace. Thus, all the modern C++ compilers support these statements.

#include<iostream>

using namespace std;

However, some old compilers may not support these statements. In that case, the
statements are replaced by this single statement.

#include<iostream.h>

11
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Main Function:

The main () is a startup function that starts the execution of a c++ program. All C++
statements that need to be executed are written within main ( ). The compiler executes all
the instructions written within the opening and closing curly braces' {}' that enclose the
body of main ( ). Once all the instructions in main () are executed, the control passes out of
main ( ), terminating the entire program and returning a value to the operating system.

By default, main () in C++ returns an int value to the operating system. Therefore, main ()
should end with the return 0 statement. A return value zero indicates success and a non-
zero value indicates failure or error.

DATA TYPES IN C++

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 different amount of memory. Data types in C++ is mainly divided into two types:

1. Primitive Data Types: These data types are built-in or predefined data types and can be used directly by
the user to declare variables. example: int, char , float, bool etc. Primitive data types available in C++ are:

Integer

Character

Boolean

Floating Point

Double Floating Point

Valueless or Void

Wide Character

2. Abstract or user defined data type: These data types are defined by user itself. Like, defining a class in
C++ or a structure.

Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of memory space
and ranges from -2147483648 to 2147483647.

Character: Character data type is used for storing characters. 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: Boolean data type is used for storing boolean or logical values. 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

12
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

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.

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.

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. Data type modifiers available in C++ are:

Signed

Unsigned

Short

Long

Below table summarizes the modified size and range of built-in datatypes when combined with the type
modifiers:

Data Type Size (in bytes) Range

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

unsigned int 4 0 to 4,294,967,295

int 4 -2,147,483,648 to 2,147,483,647

long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

long long int 8 -(2^63) to (2^63)-1

unsigned long long int 8 0 to 18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

float 4

double 8

13
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

long double 12

wchar_t 2 or 4 1 wide character

OPERATORS IN C++

Operators are special type of functions, that takes one or more arguments and produces a
new value. For example : addition (+), substraction (-), multiplication (*) etc, are all
operators. Operators are used to perform various operations on variables and constants.

Types of operators

1. Assignment Operator
2. Mathematical Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Shift Operators
7. Unary Operators
8. Ternary Operator
9. Comma Operator

Assignment Operator (=)


Operates '=' is used for assignment, it takes the right-hand side (called rvalue) and copy it
into the left-hand side (called lvalue). Assignment operator is the only operator which can
be overloaded but cannot be inherited.

Mathematical(Arithmetic) Operators
There are operators used to perform basic mathematical operations. Addition (+) ,
subtraction (-) , diversion (/) multiplication (*) and modulus (%) are the basic mathematical
operators. Modulus operator cannot be used with floating-point numbers.
C++ and C also use a shorthand notation to perform an operation and assignment at same
type.Example ,
int x=10;
x += 4 // will add 4 to 10, and hence assign 14 to X.
x -= 5 // will subtract 5 from 10 and assign 5 to x.

14
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Relational Operators
These operators establish a relationship between operands. The relational operators are :
less than (<) , grater thatn (>) , less than or equal to (<=), greater than equal to (>=),
equivalent (==) and not equivalent (!=).
You must notice that assignment operator is (=) and there is a relational operator, for
equivalent (==). These two are different from each other, the assignment operator assigns
the value to any variable, whereas equivalent operator is used to compare values, like in if-
else conditions,Example
int x = 10; //assignment operator
x=5; // again assignment operator
if(x == 5) // here we have used equivalent relational operator, for comparison
{
cout <<"Successfully compared";
}

Logical Operators
The logical operators are AND (&&) and OR (||). They are used to combine two different
expressions together.
If two statement are connected using AND operator, the validity of both statements will be
considered, but if they are connected using OR operator, then either one of them must be
valid. These operators are mostly used in loops (especially while loop) and in Decision
making.
Bitwise Operators
There are used to change individual bits into a number. They work with only integral data
types like char, int and long and not with floating point values.

 Bitwise AND operators &


 Bitwise OR operator |
 And bitwise XOR operator ^
 And, bitwise NOT operator ~

They can be used as shorthand notation too, & = , |= , ^= , ~= etc.

Shift Operators
Shift Operators are used to shift Bits of any variable. It is of three types,

1. Left Shift Operator <<


2. Right Shift Operator >>
3. Unsigned Right Shift Operator >>>

Unary Operators
These are the operators which work on only one operand. There are many unary operators,

15
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

but increment ++ and decrement -- operators are most used.

Other Unary Operators : address of &, dereference *, new and delete, bitwise not ~, logical
not !, unary minus - and unary plus +.

Ternary Operator
The ternary if-else ? : is an operator which has three operands.

int a = 10;
a > 5 ? cout << "true" : cout << "false"

Comma Operator
This is used to separate variable names and to separate expressions. In case of
expressions, the value of last expression is produced and used.

Example :

int a,b,c; // variables declaration using comma operator


a=b++, c++; // a = c++ will be done.

Operator Precedence and Associativity in C


Operator precedence determines which operator is performed first in an expression with
more than one operators with different precedence.

For example: Solve

10 + 20 * 30

16
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30

Operators Associativity is used when two operators of same precedence appear in an


expression. Associativity can be either Left to Right or Right to Left.

For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so
the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

17
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Operators Precedence and Associativity are two characteristics of operators that


determine the evaluation order of sub-expressions in absence of brackets

For example: Solve

100 + 200 / 10 - 3 * 10

18
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

1) Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single
operator are evaluated. For example, consider the following program, associativity of the +
operator is left to right, but it doesn’t mean f1() is always called before f2(). The output of
the following program is in-fact compiler dependent. See this for details.

filter_none

edit

play_arrow

brightness_4

// Associativity is not used in the below program.


// Output is compiler dependent.

#include <stdio.h>

int x = 0;
int f1()
{
x = 5;
return x;
}
int f2()

19
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

{
x = 10;
return x;
}
int main()
{
int p = f1() + f2();
printf("%d ", x);
return 0;
}

2) All operators with the same precedence have same associativity


This is necessary, otherwise, there won’t be any way for the compiler to decide evaluation
order of expressions which have two operators of same precedence and different
associativity. For example + and – have the same associativity.

3) Precedence and associativity of postfix ++ and prefix ++ are different


Precedence of postfix ++ is more than prefix ++, their associativity is also different.
Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left.

4) Comma has the least precedence among all operators and should be used carefully
For example consider the following program, the output is 1.

#include <stdio.h>
int main()
{
int a;
a = 1, 2, 3; // Evaluated as (a = 1), 2, 3
printf("%d", a);
return 0;
}

5) There is no chaining of comparison operators in C


In Python, expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining
doesn’t happen in C. For example consider the following program. The output of following
program is “FALSE”.

#include <stdio.h>
int main()
{
int a = 10, b = 20, c = 30;

// (c > b > a) is treated as ((c > b) > a), associativity of '>'


// is left to right. Therefore the value becomes ((30 > 20) > 10)
// which becomes (1 > 20)
if (c > b > a)
printf("TRUE");
else
printf("FALSE");
return 0;
}

20
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Please see the following precedence and associativity table for reference.

Operator Description
Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ — Postfix increment/decrement (see Note 2)
++ — Prefix increment/decrement right-to-left
+– Unary plus/minus
!~ Logical negation/bitwise complement
(type ) Cast (convert value to temporary value oftype )
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right

EXPRESSIONS IN C++

A combination of variables, constants and operators that represents a computation forms


an expression. Depending upon the type of operands involved in an expression or the
result obtained after evaluating expression, there are different categories of an expression.
These categories of an expression are discussed here.

21
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

• Constant expressions: The expressions that comprise only constant values are called
constant expressions. Some examples of constant expressions are 20,‘ a‘ and 2/5+30 .
• Integral expressions: The expressions that produce an integer value as output after
performing all types of conversions are called integral expressions. For example, x, 6*x-y
and 10 +int (5.0) are integral expressions. Here, x and yare variables of type into
• Float expressions: The expressions that produce floating-point value as output after
performing all types of conversions are called float expressions. For example, 9.25, x-y
and 9+ float (7) are float expressions. Here, x 'and yare variables of type float.
• Relational or Boolean expressions: The expressions that produce a bool type value, that
is, either true or false are called relational or Boolean expressions. For example, x + y<100,
m + n==a-b and a>=b + c .are relational expressions.
• Logical expressions: The expressions that produce a bool type value after combining
two or more relational expressions are called logical expressions. For example, x==5
&&m==5 and y>x I I m<=n are logical expressions.
• Bitwise expressions: The expressions which manipulate data at bit level are
called bitwise expressions. For example, a >> 4 and b<< 2 are bitwise expressions.
• Pointer expressions: The expressions that give address values as output are
called pointer expressions. For example, &x, ptr and -ptr are pointer expressions. Here, x is
a variable of any type and ptr is a pointer.
• Special assignment expressions: An expression can be categorized further depending
upon the way the values are assigned to the variables.
• Chained assignment: Chained assignment is an assignment expression in which the
same value is assigned to more than one variable, using a single statement. For example,
consider these statements.
a = (b=20); or a=b=20;

In these statements, value 20 is assigned to variable b and then to variable a. Note that
variables cannot be initialized at the time of declaration using chained assignment. For
example, consider these statements.
int a=b=30; // illegal
int a=30, int b=30; //valid
• Embedded assignment: Embedded assignment is an assignment expression, which
is enclosed within another assignment expression. For example, consider this statement
a=20+(b=30); //equivalent to b=30; a=20+30;

In this statement, the value 30 is assigned to variable b and then the result of (20+ 30) that
is, 50 is assigned to variable a. Note that the expression (b=30) is an embedded
assignment.
Compound Assignment: Compound Assignment is an assignment expression, which uses
a compound assignment operator that is a combination of the assignment operator with a
binary arithmetic operator. For example, consider this statement.

22
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

a + =20; //equivalent to a=a+20;


In this statement, the operator += is a compound assignment operator, also known as
short-hand assignment operator.

Type Conversion

An expression· may involve variables and constants either of same data type or of
different data types. However, when an expression consists of mixed data types then they
are converted to the same type while evaluation, to avoid compatibility issues. This is
accomplished by type conversion, which is defined as the process of converting one
predefined data type into another. Type conversions are of two types,
namely,implicit conversions andexplicit conversions also known astypecasting.

Implicit Conversions
Implicit conversion, also known as automatic type conversion refers to the type
conversion that is automatically performed by the compiler. Whenever compiler confronts
a mixed type expression, first of all char and short int values are converted to int. This
conversion is known as integral promotion. After applying this conversion, all the other
operands are converted to the type of the largest operand and the result is of the type of
the largest operand. The following table illustrates the implicit conversion of data type
starting from the smallest to largest data type. For example, in expression 5 + 4.25, the
compiler converts the int into float as float is larger than int and then performs the addition.

Typecasting
Typecasting refers to the type conversion that is performed explicitly using type cast
operator. In C++, typecasting can be performed by using two different forms which are
given here.
data_type (expression) //expression in parentheses

23
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

(data_type)expression //data type in parentheses


where,
data_type = data type (also known ascast operator) to which the expression is to be
converted.
To understand typecasting, consider this example.
float (num)+ 3.5; //num is of int type
In this example, float () acts as a conversion function which converts int to float. However,
this form of conversion cannot be used in some situations. For example, consider this
statement.
ptr=int * (x) ;
In such cases, conversion can be done using the second form of typecasting (which is
basically C-style typecasting) as shown here.
ptr=(int*)x;

Inline Functions in C++


When the program executes the function call instruction, the CPU stores the
memory address of the instruction following the function call, copies the arguments of the
function on the stack and finally transfers control to the specified function. The CPU then
executes the function code, stores the function return value in a predefined memory
location/register and returns control to the calling function. This can become overhead if
the execution time of function is less than the switching time from the caller function to
called function (callee). For functions that are large and/or perform complex tasks, the
overhead of the function call is usually insignificant compared to the amount of time the
function takes to run. However, for small, commonly-used functions, the time needed to
make the function call is often a lot more than the time needed to actually execute the
function’s code. This overhead occurs for small functions because execution time of small
function is less than the switching time.
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
}

24
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Remember, inlining is only a request to the compiler, not a command. Compiler may not
perform inlining in some 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.
Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of calling
context and the called context.
5) Inline function may be useful (if it is small) for embedded systems because inline can
yield less code than the function call preamble and return.
Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers, After in-
lining function if variables number which are going to use register increases than they may
create overhead on register variable resource utilization. This means that when inline
function body is substituted at the point of function call, total number of variables used by
the function also gets inserted. So the number of register going to be used for the
variables will also get increased. So if after function inlining variable numbers increase
drastically then it would surely cause an overhead on register utilization.
2) If you use too many inline functions then the size of the binary executable file will be
large, because of the duplication of same code.
3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the
speed of instruction fetch from that of cache memory to that of primary memory.
4) Inline function may increase compile time overhead if someone changes the code
inside the inline function then all the calling location has to be recompiled because
compiler would require to replace all the code once again to reflect the changes, otherwise
it will continue with old functionality.
5) Inline functions may not be useful for many embedded systems. Because in embedded
systems code size is more important than speed.

25
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

6) Inline functions might cause thrashing because inlining might increase size of the
binary executable file. Thrashing in memory causes performance of computer to degrade.

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

Inline function and classes:

It is also possible to define the inline function inside the class. In fact, all the functions
defined inside the class are implicitly inline. Thus, all the restrictions of inline functions are
also applied here. If you need to explicitly declare inline function in the class then just
declare the function inside the class and define it outside the class using inline keyword.
For example:
class S
{
public:
int square(int s); // declare the function
};

inline int S::square(int s) // use inline prefix


{

dynamic memory Allcation operators in C++

Dynamic memory allocation in C/C++ refers to performing memory allocation manually by


programmer. Dynamically allocated memory is allocated on Heap and non-static and local
variables get memory allocated on Stack.
What are applications?

 One use of dynamically allocated memory is to allocate memory of variable size


which is not possible with compiler allocated memory except variable length arrays.
 The most important use is flexibility provided to programmers. We are free to

26
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

allocate and deallocate memory whenever we need and whenever we don’t need
anymore. There are many cases where this flexibility helps. Examples of such cases
are Linked List, Tree, etc.

How is it different from memory allocated to normal variables?


For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and
deallocated. For dynamically allocated memory like “int *p = new int[10]”, it is
programmers responsibility to deallocate memory when no longer needed. If programmer
doesn’t deallocate memory, it causes memory leak (memory is not deallocated until
program terminates).
How is memory allocated/deallocated in C++?
C uses malloc() and calloc() function to allocate memory dynamically at run time and uses
free() function to free dynamically allocated memory. C++ supports these functions and
also has two operators new and delete that perform the task of allocating and freeing the
memory in a better and easier way.
new operator
The “new” operator denotes a request for memory allocation on the Heap. If sufficient
memory is available, new operator initializes the memory and returns the address of the
newly allocated and initialized memory to the pointer variable.

 Syntax to use new operator: To allocate memory of any data type, the syntax is:
pointer-variable = new data-type;

Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in
data type including array or any user defined data types including structure and
class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;

 Initialize memory: We can also initialize the memory using new operator:
pointer-variable = new data-type(value);

27
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Example:
int *p = new int(25);
float *q = new float(75.25);

 Allocate block of memory: new operator is also used to allocate a block(an array)
of memory of typedata-type .
pointer-variable = new data-type[size];

where size(a variable) specifies the number of elements in an array.


Example:
int *p = new int[10]

Dynamically allocates memory for 10 integers continuously of type int and returns pointer
to the first element of the sequence, which is assigned to p(a pointer). p[0] refers to first
element, p[1] refers to second element and so on.

Normal Array Declaration vs Using new


There is a difference between declaring a normal array and allocating a block of memory
using new. The most important difference is, normal arrays are deallocated by compiler (If
array is local, then deallocated when function returns or completes). However, dynamically
allocated arrays always remain there until either they are deallocated by programmer or
program terminates.

What if enough memory is not available during runtime?


If enough memory is not available in the heap to allocate, the new request indicates failure
by throwing an exception of type std::bad_alloc, unless “nothrow” is used with the new
operator, in which case it returns a NULL pointer (scroll to section “Exception handling of
new operator” in this article). Therefore, it may be good idea to check for the pointer
variable produced by new before using it program.

int *p = new(nothrow) int;


if (!p)
{
cout << "Memory allocation failed\n";
}

delete operator
Since it is programmer’s responsibility to deallocate dynamically allocated memory,

28
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

programmers are provided delete operator by C++ language.


Syntax:
// Release memory pointed by pointer-variable
delete pointer-variable;

Here, pointer-variable is the pointer that points to the data object created bynew .
Examples:
delete p;
delete q;

To free the dynamically allocated array pointed by pointer-variable, use following form of
delete :
// Release block of memory
// pointed by pointer-variable
delete[] pointer-variable;

Example:
// It will free the entire array
// pointed by p.
delete[] p;

SELECTION STATEMENTS
The selection (if, if-else, if-else-if, and switch) statements allows to choose the set-of-
instructions for execution depending upon an expression's truth value. C++ provides
following two types of selection statements:

 if statement
 switch statement
In addition, in certain circumstances ? operator can be used as an alternative to if
statement. The selection statements are also called conditional statements or decision
statements . selection statements of C++ , divided into these parts:

 if statement
 if-else statement
 nested ifs statement
 if-else-if ladder
 switch statement
 nested switch statement
if Statement
An “if statement” tests a particular condition; if the condition evaluates to true, a course-of-
action is followed i.e., a statement or set-of-statements is executed. Otherwise (if the

29
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

condition evaluates to false), the course-of-action is ignored. Here is the syntax or general
form of the if statement:
if(expression)
{
statement(s);
}

Here, statement may be a single statement or a block of statements, or nothing (in case of
empty statement). The expression must be enclosed in parentheses.
if-else Statement
The examples of if statement, you have seen so far allow you to execute a set of
statements if a condition or expression evaluates to true. What if there is another course
of action to be followed if the expression evaluates to false ?
There is another form of if that allows for this kind of either-or condition by providing an
else clause. The syntax of the if-else statement is the following :
if(expression)
{
statement 1;
}
else
{
statement 2;
}

If the expression evaluates to true i.e., a nonzero value, the statement 1 is executed,
otherwise, statement 2 is executed. The statement 1 and statement 2 can be a single
statement, or a compound statement, or a null statement.
Nested Ifs Statement
A nested if is an if that has another if in its if's body or in its else's body. The nested if can
have one of the following three forms. Here is the first form:
if(expression 1)
{
if(expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
else

30
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

{
body-of-else;
}

This is the second form of nested ifs statement


if(expression 1)
{
body-of-if;
else
{
if(expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
}

Now, this is the third form of nested ifs statement


if(expression 1)
{
if(expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
if(expression 3)
{
statement 3;
}
else
{
statement 4;
}
}

In an if statement, either there can be if statement(s) in its body-of-if or in its body-of-else

31
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

or in both. The inner ifs can themselves be nested ifs, but the inner if must terminate
before an outer if.
if-else-if Ladder
A common programming construct in C++ is the if-else-if ladder, which is often also called
the if-else-if staircase because of its appearance. It takes the following general form :
if(expression)
{
statement 1;
}
else if(expression 2)
{
statement 2;
}
else if(expression 3)
{
statement 3;
}
.
.
.
else
{
statement N;
}

The expression are evaluated from the top downward. As soon as an expression evaluates
to true, the statement associated with it is executed and the rest of the ladder is bypassed.
If none of the expression are true, the final else gets executed. If the final else is missing,
no action takes place if all the conditions are false.
switch Statement
C++ provides a multiple-branch selection statement known as switch. This selection
statement successively tests the value of an expression against a list of integer or
character constants. When a match is found, the statements associated with that
constant are executed. The syntax of switch statement is as follows:
switch(expression)
{
case constant1 : statement sequence 1;
break;
case constant2 : statement sequence 2;
break;
case constant3 : statement sequence 3;
break;
.
.

32
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

.
case constant n-1 : statement sequence n-1;
break;
default : statement sequence n;
}

The expression is evaluated and its values are matched against the values of the
constants specified in the case statements. When a match is found, the statement
sequence associated with that case is executed until the break statement or the end of
switch statement is reached. If a case statement does not include a break statement, then
the control continues right on the next case statement(s) until either a break is
encountered or end of switch is reached. This situation (i.e., missing break in case
statement) is called fall through. The default statement gets executed when no match is
found. The default statement is optional and, if it is missing , no action takes place if all
matches fail.
NOTE: The ANSI standard specifies that a switch can have upto 257 case
statements, however, you must always limit the number of case statements to a smaller
amount for the sake of efficiency.

Differences between if and switch

if switch
It can evaluate a relational or logical can only test for equality
expression i.e., multiple conditions.
a series of expressions that may involve The switch statement selects its branches
unrelated variables and complex by testing the value of same variable
expressions. (against a set of constants)
if-else can handle ranges whereas switch Each switch case label must be a single
cannot. value.
The if-else statement can handle floating- switch cannot handle floating-point tests.
point tests also apart from handling integer The case labels of switch must be an
and character tests integer (which includes char also).
if two or more variables are to be compared, The switch case label value must be a
use if-else. constant.

LOOPS in C++

Loops in programming comes into use when we need to repeatedly execute a block of
statements. For example: Suppose we want to print “Hello World” 10 times. This can be

33
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

done in two ways as shown below:


Iterative Method
Iterative method to do this is to write the “cout<<” statement 10 times.
Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10
times as shown below.
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:
1. 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.
2. 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.

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

34
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

repeated till exit condition comes.

 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++;
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:
loop contains three statements – initialization expression, test expression, update
expression. 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;
}

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
{

35
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

// statements

update_expression;
} while (test_expression);

goto statement
The goto statement is a jump statement which is sometimes also referred to as
unconditional jump statement. The goto statement can be used to jump from anywhere to
anywhere 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 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 above syntax.

36
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Disadvantages of using goto statement:

 The use of goto statement is highly discouraged as it makes the program logic very
complex.
 use of goto makes really hard to modify the program.
 Use of goto can be simply avoided using break and continue statements.

Break statement
Break Statement is a loop control statement which 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.

usage of break statement with three different types of loops:

 Simple loops
 Nested loops
 Infinite loops

37
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Simple loops: Consider the situation where we want to search an element in an array. To
do this, use a loop to traverse the array starting from the first index and compare the array
elements with the given key.
Eg. for(------------) -----------> loop1
{
if(--------------)
break;
}
In the above example break causes flow of execution to come out of loop1.
Nested Loops:
We can also use break statement while working with nested loops. If the break statement
is used in the innermost loop. The control will come out only from the innermost loop.
Below is the example of using break with nested loops:
Eg. for(------------) -----------> loop1
{
for(---------) -------->inner loop
{
if(--------------)
break;
}
}
In above example break statement causes flow of execution to exit from the inner loop.
continue statement
Continue is also a loop control statement just like the break statement.continue
statement is opposite to that of breakstatement , 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:

38
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

continue;

Eg: for(i=1;i<=10;i++)
if(i==6)
continue;
else
cout<<i;
The above code prints numbers from 1 to 10, except 6.

ARRAYS IN C++

An array is a collection of elements of the same type placed in contiguous memory


locations that can be individually referenced by using an index to a unique identifier.
Five values of type int can be declared as an array without having to declare five different
variables.
For example, a five element integer array foo may be logically represented as;

39
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

where each blank panel represents an element of the array. In this case, these are values
of type int. These elements are numbered from 0 to 4, with 0 being the first while 4 being
the last; In C++, the index of the first array element is always zero. As expected, an n array
must be declared prior its use. A typical declaration for an array in C++ is:
type name [elements];
where type is a valid type (such as int, float ...), name is a valid identifier and the elements
field (which is always enclosed in square brackets []), specifies the size of the array.
Thus, the foo array, with five elements of type int, can be declared as:
int foo [5];

NOTE
: The elements field within square brackets [], representing the number of elements in the
array, must be a constant expression, since arrays are blocks of static memory whose size
must be known at compile time.

INITIALIZING ARRAYS
By default, are left uninitialized. This means that none of its elements are set to any
particular value; their contents are undetermined at the point the array is declared.
The initializer can even have no values, just the braces:
int baz [5] = { };
This creates an array of five int values, each initialized with a value of zero:

But, the elements in an array can be explicitly initialized to specific values when it is
declared, by enclosing those initial values in braces {}. For example:
int foo [5] = { 16, 2, 77, 40, 12071 };
This statement declares an array that can be represented like this:

The number of values between braces {} shall not be greater than the number of elements
in the array. For example, in the example above, foo was declared having 5 elements (as
specified by the number enclosed in square brackets, []), and the braces {} contained
exactly 5 values, one for each element. If declared with less, the remaining elements are

40
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

set to their default values (which for fundamental types, means they are filled with zeroes).
For example:
int bar [5] = { 10, 20, 30 };
Will create an array like this:

When an initialization of values is provided for an array, C++ allows the possibility of
leaving the square brackets empty[]. In this case, the compiler will assume automatically a
size for the array that matches the number of values included between the braces {}:
int foo [] = { 16, 2, 77, 40, 12071 };
After this declaration, array foo would be five int long, since we have provided five
initialization values.
Finally, the evolution of C++ has led to the adoption of universal initialization also for
arrays. Therefore, there is no longer need for the equal sign between the declaration and
the initializer. Both these statements are equivalent:
int foo[] = { 10, 20, 30 };
int foo[] { 10, 20, 30 };
Here, the number of the array n is calculated by the compiler by using the formula n= #of
initializers/sizeof(int).
Static arrays, and those declared directly in a namespace (outside any function), are
always initialized. If no explicit initializer is specified, all the elements are default-initialized
(with zeroes, for fundamental types).

ARRAY ACCESSING
The values of any of the elements in an array can be accessed just like the value of a
regular variable of the same type. The syntax is:
name[index]

Following the previous examples in which foo had 5 elements and each of those elements
was of type int, the name which can be used to refer to each element is the following:

For example, the following statement stores the value 75 in the third element of foo:
foo [2] = 75;
and, for example, the following copies the value of the fourth element of foo to a variable
called x:
x = foo[3];

41
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Therefore, the expression foo[2] or foo[4] is always evaluated to an int. Notice that the
third element of foo is specified foo[2], the second one is foo[1], since the first one
is foo[0]. It’s last element is therefore foo[4]. If we write foo[5], we would be accessing the
sixth element of foo, and therefore actually exceeding the size of the array.
In C++, it is syntactically correct to exceed the valid range of indices for an array. This can
create problems, since accessing out-of-range elements do not cause errors on
compilation, but can cause errors on runtime. The reason for this being allowed because
index checking slows down program execution. At this point, it is important to be able to
clearly distinguish between the two uses that brackets [] have related to arrays. They
perform two different tasks: one is to specify the size of arrays when they are declared;
and the second one is to specify indices for concrete array elements when they are
accessed. Do not confuse these two possible uses of brackets [] with arrays.
int foo[5]; // declaration of a new array
foo[2] = 75; // access to an element of the array.
The main difference is that the declaration is preceded by the type of the elements, while
the access is not.
Some other valid operations with arrays:
foo[0] = a;
foo[i] = 75;
b = foo [i+2];
foo[foo[i]] = foo[i] + 5;

MULTIDIMENSIONAL ARRAYS
Multidimensional arrays can be described as "arrays of arrays". For example, a bi-
dimensional array can be imagined as a two-dimensional table made of elements, all of
them hold same type of elements.

Table represents a bi-dimensional array of 3 per 5 elements of type int. The C++ syntax for
this is
int Table [3][5];
and, for example, the way to reference the second element vertically and fourth
horizontally in an expression would be:
Table[1][3]

42
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

(remember that array indices always begin with zero).


Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can
contain as many indices as needed. Although be careful: the amount of memory needed
for an array increases exponentially with each dimension. For example:
char century [100][365][24][60][60];
Declares an array with an element of type char for each second in a century. This amounts
to more than 3 billion char! So this declaration would consume more than 3 gigabytes of
memory! And such a declaration is highly improbable and it underscores inefficient use of
memory space.
At the end, multidimensional arrays are just an abstraction for programmers, since the
same results can be achieved with a simple array, by multiplying its indices:
int Table [3][5]; // is equivalent to
int Table [15]; // (3 * 5 = 15)
With the only difference that with multidimensional arrays, the compiler automatically
remembers the depth of each imaginary dimension.

POINTER IN C++

Every variable is a memory location and every memory location has its address defined
which can be accessed using ampersand (&) operator which denotes an address in
memory. Consider the following which will print the address of the variables defined −
#include <iostream>

using namespace std;


int main () {
int var1;
char var2[10];

cout << "Address of var1 variable: ";


cout << &var1 << endl;

cout << "Address of var2 variable: ";

43
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

cout << &var2 << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: 0xbfebd5c0
Address of var2 variable: 0xbfebd5b6

What are Pointers?


A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a
pointer variable declaration is −
type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name
of the pointer variable. The asterisk you used to declare a pointer is the same asterisk
that you use for multiplication. However, in this statement the asterisk is being used to
designate a variable as a pointer. Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address.
The only difference between pointers of different data types is the data type of the
variable or constant that the pointer points to.

Using Pointers in C++


There are few important operations, which we will do with the pointers very
frequently.
(a) We define a pointer variable.
(b) Assign the address of a variable to a pointer.
(c) Finally access the value at the address available in the pointer variable. This is
done by using unary operator * that returns the value of the variable located at the
address specified by its operand.
Following example makes use of these operations −

#include <iostream>

using namespace std;

44
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}
When the above code is compiled and executed, it produces result something as follows

Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

POINTER AND ARRAYS

Consider the following program:


#include<stdio.h>

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;

printf("%p\n", ptr);
return 0;
}
In this program, we have a pointerptr that points to the 0th element of the array.
Similarly, we can also declare a pointer that can point to whole array instead of only one
element of the array. This pointer is useful when talking about multidimensional arrays.

Syntax:

data_type (*var_name)[size_of_array];

45
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Example:

int (*ptr)[10];
Hereptr is pointer that can point to an array of 10 integers. Since subscript have
higher precedence than indirection, it is necessary to enclose the indirection operator and
pointer name inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points to the
whole array are totally different. The following program shows this:

int main()
{
// Pointer to an integer
int *p;

// Pointer to an array of 5 integers


int (*ptr)[5];
int arr[5];

// Points to 0th element of the arr.


p = arr;

// Points to the whole array arr.


ptr = &arr;

cout<<"p =” <<p<<”, ptr =”<<ptr;

p++;
ptr++;

cout<<"p =” <<p<<”, ptr =”<<ptr;

return 0;
}

Output:
p = 0x7fff4f32fd50, ptr = 0x7fff4f32fd50
p = 0x7fff4f32fd54, ptr = 0x7fff4f32fd64

p : is pointer to 0th element of the arrayarr , whileptr is a pointer that points to the whole
arrayarr .
 The base type ofp is int while base type ofptr is ‘an array of 5 integers’.
 We know that the pointer arithmetic is performed relative to the base size, so if we
write ptr++, then the pointerptr will be shifted forward by 20 bytes.
The following figure shows the pointer p and ptr. Darker arrow denotes pointer to an array.

46
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

On dereferencing a pointer expression we get a value pointed to by that pointer


expression. Pointer to an array points to an array, so on dereferencing it, we should get the
array, and the name of array denotes the base address. So whenever a pointer to an array
is dereferenced, we get the base address of the array to which it points.

STRINGS

C++ provides following two types of string representations −

 The C-style character string.

 The string class type introduced with Standard C++.

The C-Style Character String


The C-style character string originated within the C language and continues to be
supported within C++. This string is actually a one-dimensional array of characters which
is terminated by a nullcharacter '\0'. Thus a null-terminated string contains the characters
that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization, then you can write the above statement as
follows −
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++ −

47
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the array.
Let us try to print above-mentioned string –
#include <iostream>

using namespace std;

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

cout << "Greeting message: ";


cout << greeting << endl;

return 0;
}
OUTPUT
Greeting message: Hello

C++ supports a wide range of functions that manipulate null-terminated strings −


Sr.No Function & Purpose

1
strcpy(s1, s2);
Copies string s2 into string s1.

2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3
strlen(s1);
Returns the length of string s1.

4
strcmp(s1, s2);

48
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.

6
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.

The String Class in C++


The standard C++ library provides a string class type that supports all the operations
mentioned above, additionally much more functionality. Let us check the following
example −
#include <iostream>
#include <string>

using namespace std;

int main () {

string str1 = "Hello";


string str2 = "World";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total length of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}
When the above code is compiled and executed, it produces result something as follows

str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10

49
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

STRUCTURES
C++ arrays allow you to define variables that combine several data items of the same
kind, but structure is another user defined data type which allows you to combine data
items of different kinds.
Structures are used to represent a record, suppose you want to keep track of your books
in a library. You might want to track the following attributes about each book −

 Title

 Author

 Subject

 Book ID

Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member, for your program. The format of the struct
statement is this −
struct [structure tag]
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but
it is optional. Here is the way you would declare the Book structure −
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name and
the structure member that we wish to access. You would use struct keyword to define
variables of structure type. Following is the example to explain usage of structure −
#include <iostream>

50
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

#include <cstring>

using namespace std;

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

// Print Book2 info


cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha

51
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Book 2 subject : Telecom


Book 2 id : 6495700

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.

References vs Pointers
References are often confused with pointers but three major differences between
references and pointers are −
 You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.
 Once a reference is initialized to an object, it cannot be changed to refer to another
object. Pointers can be pointed to another object at any time.
 A reference must be initialized when it is created. Pointers can be initialized at any
time.

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.". Following example makes use of references on int and double

#include <iostream>

using namespace std;

int main () {
// declare simple variables
int i;
double d;

// declare reference variables


int& r = i;
double& s = d;

52
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;

d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;

return 0;
}
When the above code is compiled together and executed, it produces the following result

Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7

FUNCTIONS

A function is a group of statements that together perform a task. Every C++


program has at least one function, which is main(), and all the most trivial programs can
define additional functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is such that each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can call.
For example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.

Defining a Function
The general form of a C++ function definition is as follows –

return_type function_name( parameter list )


{
body of the function
}

A C++ function definition consists of a function header and a function body. Here are all

53
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

the parts of a function −


 Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
 Function Body − The function body contains a collection of statements that define
what the function does.

SCOPE OF VARIABLES

In general, scope is defined as the extent upto which something can be worked with. In
programming also scope of a variable is defined as the extent of the program code within
which the variable can be accessed. There are mainly two types of variable scopes as
discussed below:
Local Variables
Variables defined within a function or block are said to be local to those functions.
 Anything between ‘{‘ and ‘}’ is said to inside a block.
 Local variables do not exist outside the block in which they are declared, i.e. they can
not be accessed or used outside that block.
 Declaring local variables: Local variables are declared inside a block.

#include<iostream>
using namespace std;

void func()
{
// this variable is local to the
// function func() and cannot be
// accessed outside this function
int age=18;
}

int main()
{
cout<<"Age is: "<<age;

return 0;
}

54
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

Output:
Error: age was not declared in this scope

The above program displays an error saying “age was not declared in this scope”. The
variable age was declared within the function func() so it is local to that function and not
visible to portion of program outside this function.
Rectified Program : To correct the above error we have to display the value of variable age
from the function func() only. This is shown in the below program:
filter_none
edit
play_arrow
brightness_4
// CPP program to illustrate
// usage of local variables
#include<iostream>
using namespace std;

void func()
{
// this variable is local to the
// function func() and cannot be
// accessed outside this function
int age=18;
cout<<age;
}

int main()
{
cout<<"Age is: ";
func();

return 0;
}
Output:
Age is: 18
Global Variables
As the name suggests, Global Variables can be accessed from any part of the program.
 They are available through out the life time of a program.
 They are declared at the top of the program outside all of the functions or blocks.
 Declaring global variables: Global variables are usually declared outside of all of the
functions and blocks, at the top of the program. They can be accessed from any
portion of the program.

#include<iostream>
using namespace std;

55
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

// global variable
int global = 5;

// global variable accessed from


// within a function
void display()
{
cout<<global<<endl;
}

// main function
int main()
{
display();

// changing value of global


// variable from main function
global = 10;
display();
}
Output:
5
10
In the program, the variable “global” is declared at the top of the program outside all of the
functions so it is a global variable and can be accessed or updated from anywhere in the
program.

56
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

PARAMETER PASSING

There are different ways in which parameter data can be passed into and out of methods
and functions. Let us assume that a functionB() is called from another functionA() . In this
caseA is called the“caller function” andB is called the“called function or callee function” .
Also, the arguments whichA sends toB are calledactual arguments and the parameters
ofB are calledformal arguments .

Terminology
 Formal Parameter : A variable and its type as they appear in the prototype of the
function or method.
 Actual Parameter : The variable or expression corresponding to a formal parameter
that appears in the function or method call in the calling environment.

Important methods of Parameter Passing


1. Pass By Value : This method usesin-mode semantics. Changes made to formal
parameter do not get transmitted back to the caller. Any modifications to the formal
parameter variable inside the called function or method affect only the separate
storage location and will not be reflected in the actual parameter in the calling
environment. This method is also called ascall by value .

#include <stdio.h>

void func(int a, int b)


{
a += b;
cout<<”In func, a=”<<a<<”b=”<<b;
}
int main(void)
{
int x = 5, y = 7;

// Passing parameters
func(x, y);
cout<<”In main, x=”<<x<<”y=”<<y;
return 0;
}
Output:
In func, a = 12 b = 7
In main, x = 5 y = 7
Languages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value.

1. Pass by reference(aliasing) : This technique usesin/out-mode semantics. Changes


made to formal parameter do get transmitted back to the caller through parameter
passing. Any changes to the formal parameter are reflected in the actual parameter in
the calling environment as formal parameter receives a reference (or pointer) to the

57
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

actual data. This method is also called as call by reference. This method is efficient in
both time and space.

#include <stdio.h>

void swapnum(int* i, int* j)


{
int temp = *i;
*i = *j;
*j = temp;
}

int main(void)
{
int a = 10, b = 20;

// passing parameters
swapnum(&a, &b);

cout<<”a is <<a <<”and b is “<<b


return 0;
}
Output:
a is 20 and b is 10
C and C++ both support call by value as well as call by reference whereas Java does’nt support call by
reference.

Default Arguments in C++

A default argument is a value provided in a function declaration that is automatically


assigned by the compiler if the caller of the function doesn’t provide a value for the
argument with a default value.
Following is a simple C++ example to demonstrate the use of default arguments. We don’t
have to write 3 sum functions, only one function works by using default values for 3rd and
4th arguments.
#include<iostream>
using namespace std;

// A function with default arguments, it can be called with


// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}

/* Driver program to test above function*/


int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;

58
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

cout << sum(10, 15, 25, 30) << endl;


return 0;
}
Output:
25
50
80

Key Points:
 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 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.

Recursion
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are Towers of Hanoi
(TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
What is base condition in recursion?
In the recursive program, the solution to the base case is provided and the solution of the
bigger problem is expressed in terms of smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, base case for n < = 1 is defined and larger value of number can be
solved by converting to smaller one till base case is reached.
How a particular problem is solved using recursion?
The idea is to represent a problem in terms of one or more smaller problems, and add one
or more base conditions that stop the recursion. For example, we compute factorial n if we

59
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

know factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0.
Why Stack Overflow error occurs in recursion?
If the base case is not reached or not defined, then the stack overflow problem may arise.
Let us take an example to understand this.
int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;

else
return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8), fact(7) and so on but the number will never
reach 100. So, the base case is not reached. If the memory is exhausted by these
functions on the stack, it will cause a stack overflow error.
Why do we need an extra bracket around function pointers like fun_ptr in above example?
If we remove bracket, then the expression “void (*fun_ptr)(int)” becomes “void *fun_ptr(int)” which is
declaration of a function that returns void pointer.

PRE-PROCESSOR DIRECTIVES

The preprocessors are the directives, which give instructions to the compiler to
preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may appear
before a preprocessor directive on a line. Preprocessor directives are not C++ statements,
so they do not end in a semicolon (;).
#include is a directive. This macro is used to include a header file into the source file.
There are number of preprocessor directives supported by C++ like #include, #define, #if,
#else, #line, etc. Let us see important directives −

The #define Preprocessor


The #define preprocessor directive creates symbolic constants. The symbolic constant is
called a macro and the general form of the directive is −
#define macro-name replacement-text
When this line appears in a file, all subsequent occurrences of macro in that file will be
replaced by replacement-text before the program is compiled. For example −
#include <iostream>

60
II B.TECH I SEM R18 (2020-21)
JITS KARIMNAGAR( JNTUH ) C++ NOTES UNIT-I

using namespace std;

#define PI 3.14159

int main () {
cout << "Value of PI :" << PI << endl;

return 0;
}

61
II B.TECH I SEM R18 (2020-21)

You might also like