0% found this document useful (0 votes)
19 views

Unit-1 C++-ECE-SEM2-2020

The document provides an overview of C++, including its history, features, and applications in software development. It covers fundamental concepts such as object-oriented programming, standard libraries, basic input/output operations, and the structure of a simple C++ program. Additionally, it highlights important keywords and commenting practices in C++ programming.

Uploaded by

iamsilentperson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Unit-1 C++-ECE-SEM2-2020

The document provides an overview of C++, including its history, features, and applications in software development. It covers fundamental concepts such as object-oriented programming, standard libraries, basic input/output operations, and the structure of a simple C++ program. Additionally, it highlights important keywords and commenting practices in C++ programming.

Uploaded by

iamsilentperson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

C++ Content-ECE-SEM2-2020Batch

Unit-1:
 Review of C:

 strings,

 arrays,

 pointers,

 Programming in C++,

 Build and execute a C program in C++,

 C++ as better C: Procedural Execution of C

1
 What is C++:-
C++ is a general purpose, cas e-sensitive, free-form programming that supports object-
language
oriented, procedural and generic programming.

C++ is a middle-level language, as it encapsulates both high and low lev le language features.
C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX

C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey,as
an enhancement to the C language and originally named C with Classes but later it was renamed C++
in 1983.

C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

Some of the features & key-points to note about the programming language are
as follows:

 Simple: It is a simple language in the sense that programs can be brok en down into logical
units and parts, has a rich li brary support and a variety of data-types.
 Machine Independent b ut Platform Dependent: A C++ executable is not platform-
independent (compiled programs on Linux won’t run on Windows), however they are machine
independent.

2
 Mid-level language: It is a mid-level language as we can do both systems-programming
(drivers, kernels, networking etc.) and build large-scale user applications (Media Players,
Photoshop, Game Engines etc.)
 Rich library support: Has a rich library support (Both standard ~ built-in data structures,
algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast and rapid development.
 Speed of execution: C++ programs excel in execution speed. Since, it is a compiled language,
and also hugely procedural. Newer languages have extra in-built default features such as garbage-
collection, dynamic typing etc. which slow the execution of the program overall. Since there is no
additional processing overhead like this in C++, it is blazing fast.
 Pointer and direct Memory-Access: C++ provides pointer support which aids users to directly
manipulate storage address. This helps in doing low-level programming (where one might need
to have explicit control on the storage of variables).
 Object-Oriented: One of the strongest points of the language which sets it apart from C. Object-
Oriented support helps C++ to make maintainable and extensible programs. i.e. Large- scale
applications can be built. Procedural code becomes difficult to maintain as code-size grows.
 Compiled Language: C++ is a compiled language, contributing to its speed.

 Applications of C++ Programming:-


As mentioned before, C++ is one of the most widely used programming languages. It has it's
presence in almost every area of software development. I'm going to list few of them here:
Application Software Development - C++ programming has been used in developing almost
all the major Operating Systems like Windows, Mac OSX and Linux. Apart from the operating
systems, the core part of many browsers like Mozilla Firefox and Chrome have been written
using C++. C++ also has been used in developing the most popular database system called
MySQL.
Programming Languages Development - C++ has been used extensively in developing new
programming languages like C#, Java, JavaScript, Perl, UNIX’s C Shell, PHP and Python, and
Verilog etc.
Computation Programming - C++ is the best friends of scientists because of fast speed and
computational efficiencies.
Games Development - C++ is extremely fast which allows programmers to do procedural
programming for CPU intensive functions and provides greater control over hardware,
because of which it has been widely used in development of gaming engines.
Embedded System - C++ is being heavily used in developing Medical and Engineering
Applications like softwares for MRI machines, high-end CAD/CAM systems etc.
This list goes on, there are various areas where software developers are happily using C++ to provide
great softwares. I highly recommend you to learn C++ and contribute great softwares to the
community.

3
 Object-Oriented Programming:-

C++ supports the object-oriented programming, the four major pillar of object-oriented
programming(OOPs) used in C++ are:
Encapsulation
Data hiding

Inheritance
Polymorphism

 Standard Libraries:-
Standard C++ consists of three important parts −
The core language giving all the building blocks including variables, data types and literals,
etc.
The C++ Standard Library giving a rich set of functions manipulating files, strings, etc.
The Standard Template Library (STL) giving a rich set of methods manipulating datastructures,
etc.

Some interesting facts about C++:


Here are some awesome facts about C++ that may interest you:
1. The name of C++ signifies the evolutionary nature of the changes from C. “++” is the C
increment operator.
2. C++ is one of the predominant languages for the development of all kind of technical and
commercial software.
3. C++ introduces Object-Oriented Programming, not present in C. Like other things, C++
supports the four primary features of OOP: encapsulation, polymorphism, abstraction, and
inheritance.
4. C++ got the OOP features from Simula67 Programming language.
5. A function is a minimum requirement for a C++ program to run.(at least main() function)

4
When we consider a C++ program, it can be defined as a collection of objects that communicate via
invoking each other's methods(functions). Let us now briefly look into what a class, object, methods,
and instant variables mean.

 Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors - wagging, barking, eating. An object is an instance of a class.
 Class − A class can be defined as a template/blueprint that describes the behaviors/states that
object of its type support.
 Methods(functions) − A method is basically a behavior. A class can contain many methods. It
is in methods where the logics are written, data is manipulated and all the actions are
executed.
 Instance Variables − Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.

 Writing First C++ Program – Hello World Example:


The “Hello World” program is the first step towards learning any programming language and is
also one of the simplest programs you will learn.

// C++ program to display "Hello World"


// Header file for input output functions
#include <iostream>
using namespace std;

// Main() function: where the execution of program


beginsint main()
{
// prints hello world
cout << "Hello World";

return 0;
}

Output
Hello World

5
Let us now understand every line and the terminologies of the above program:
1) // C++ program to display “Hello World”: This line is a comment line. A comment is used to display
additional information about the program. A comment does not contain any programming logic.
When a comment is encountered by a compiler, the compiler simply skips that line of code. Any
line beginning with ‘//’ without quotes OR in between /*…*/ in C++ is comment.
2) #include: In C++, all lines that start with pound (#) sign are called directives and are processed
by a preprocessor which is a program invoked by the compiler. The #include directive tells the
compiler to include a file and #include<iostream>. It tells the compiler to include the standard
iostream file which contains declarations of all the standard input/output library functions.
3) using namespace std: This is used to import the entirety of the std namespace into the current
namespace of the program.
4) int main(): This line is used to declare a function named “main” which returns data of integer
type. A function is a group of statements that are designed to perform a specific task. Execution of
every C++ program begins with the main() function, no matter where the function is located in the
program. So, every C++ program must have a main() function.
5) { and }: The opening braces ‘{‘ indicates the beginning of the main function and the closing
braces ‘}’ indicates the ending of the main function. Everything between these two comprises the
body of the main function.
6) cout<<“Hello World”;: This line tells the compiler to display the message “Hello World” onthe
screen. This line is called a statement in C++. Every statement is meant to perform some task. A
semi-colon ‘;’ is used to end a statement. Semi-colon character at the end of the statement is
used to indicate that the statement is ending there. Everything followed by the character “<<” is
displayed to the output device
7) return 0; : This is also a statement. This statement is used to return a value from a function and
indicates the finishing of a function. This statement is basically used in functions to return the
results of the operations performed by a function.
8) Indentation: As you can see the cout and the return statement have been indented or moved
to the right side. This is done to make the code more readable. In a program as Hello World, it
doesnot hold much relevance, but as the programs become more complex, it makes the code more
readable, less error-prone. Therefore, you must always use indentations and comments to make the
code more readable

6
 C++ Basic Input/Output:-
The C++ standard libraries provide an extensive set of input/output capabilities which we will see in
subsequent chapters. This chapter will discuss very basic and most common I/O operations
requiredfor C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a
keyboard, a disk drive, or a network connection etc. to main memory, this is called input
operation and if bytes flow from main memory to a device like a display screen, a printer, a disk
drive, or a network connection, etc., this is called output operation.

I/O Library Header Files

There are following header files important to C++ programs −

Sr.No Header File & Function and Description

1
<iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to the standard input
stream, the standard output stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.

2
<iomanip>
This file declares services useful for performing formatted I/O with so-called parameterized
stream manipulators, such as setw and setprecision.

3
<fstream>
This file declares services for user-controlled file processing. We will discuss about it in detailin
File and Stream related chapter.

The Standard Output Stream (cout):-


The predefined object cout is an instance of ostream class. The cout object is said to be "connected
to" the standard output device, which usually is the display screen. The cout is used in conjunction
with the stream insertion operator, which is written as << which are two less than signs as shown
inthe following example.
#include <iostream>
using namespace std;

int main() {
char str[] = "Hello C++";

cout << "Value of str is : " << str << endl;


}

When the above code is compiled and executed, it produces the following result −
7
Value of str is : Hello C++

8
The C++ compiler also determines the data type of variable to be output and selects the appropriate
stream insertion operator to display the value. The << operator is overloaded to output data items of
built-in types integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as shown above
and endl is used to add a new-line at the end of the line.

The Standard Input Stream (cin)


The predefined object cin is an instance of istream class. The cin object is said to be attached to the
standard input device, which usually is the keyboard. The cin is used in conjunction with the stream
extraction operator, which is written as >> which are two greater than signs as shown in the
following example.
#include <iostream>

using namespace std;

int main() {
char name[50];

cout << "Please enter your name: ";


cin >> name;
cout << "Your name is: " << name << endl;

}
When the above code is compiled and executed, it will prompt you to enter a name. You enter a
value and then hit enter to see the following result −
Please enter your name:
cplusplusYour name is: cplusplus

The C++ compiler also determines the data type of the entered value and selects the appropriate
stream extraction operator to extract the value and store it in the given variables.
The stream extraction operator >> may be used more than once in a single statement. To
requestmore than one datum you can use the following −
cin >> name >> age;
This will be equivalent to the following two statements
−cin >> name;
cin >> age;

The Standard Error Stream (cerr)


The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to
the standard error device, which is also a display screen but the object cerr is un-buffered and each
stream insertion to cerr causes its output to appear immediately.
The cerr is also used in conjunction with the stream insertion operator as shown in the following
example.

#include <iostream>
using namespace std;

int main() { 9
char str[] = "Unable to read ... ";
cerr << "Error message : " << str << endl;
}
When the above code is compiled and executed, it produces the following result –
Error message : Unable to read....

The Standard Log Stream (clog)


The predefined object clog is an instance of ostream class. The clog object is said to be attached
to the standard error device, which is also a display screen but the object clog is buffered. This
means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled
or until the buffer is flushed.
The clog is also used in conjunction with the stream insertion operator as shown in the following
example.

#include <iostream>
using namespace std;

int main() {
char str[] = "Unable to read ... ";

clog << "Error message : " << str << endl;


}
When the above code is compiled and executed, it produces the following result −
Error message : Unable to read....

You would not be able to see any difference in cout, cerr and clog with these small examples, but
while writing and executing big programs the difference becomes obvious. So it is good practice to
display error messages using cerr stream and while displaying other log messages then clog
shouldbe used.

Important Points to Note while Writing a C++ Program:


1. Always include the necessary header files for the smooth execution of functions. For
example, <iostream> must be included to use std::cin and std::cout.
2. The execution of code begins from the main() function.
3. each individual statement must be ended with a semicolon. It indicates the end of one
logicalentity.
4. It is a good practice to use Indentation and comments in programs for easy understanding.
5. cout is used to print statements and cin is used to take inputs.

 C++ Keywords:-
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of 32
Keywords in C++ Language which are also available in C language are given below.

10
Auto Break Case char const continue default do

11
Double Else enum extern float for goto if

Int Long register return short signed sizeof static

Struct Switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C language are given below.
Asm dynamic_cast namespace reinterpret_cast bool

Explicit New static_cast False catch

Operator Template friend Private class

This Inline public Throw const_cast

Delete Mutable protected True try

Typeid Typename using Virtual wchar_t

 C++ comments:-
Program comments are explanatory statements that you can include in the C++ code. These
comments help anyone reading the source code. All programming languages allow for some form of
comments.

C++ supports single-line and multi-line comments. All characters available inside any comment are
ignored by C++ compiler.

C++ comments start with /* and end with */. For example −

/* This is a comment */

/* C++ comments can also


span multiple lines */
A comment can also start with //, extending to the end of the line. For example −

#include <iostream>
using namespace std;

main() {
cout << "Hello World"; // prints Hello World
return 0; 12
}
When the above code is compiled, it will ignore // prints Hello World and final executable will
produce the following result −

Hello World

Within a // comment, /* and */ have no special meaning. Thus, you can "nest" one kind of
commentwithin the other kind. For example −

/* Comment out printing of Hello World:


cout << "Hello World"; // prints Hello World
*/

 C++ Data Types:-


All variables use data-type during declaration to restrict the type of data to be stored. Therefore,
we can say that data types are used to tell the variables the type of data it can store. Whenever a
variable is defined in C++, the compiler allocates some memory for that variable based on the data
type with which it is declared. Every data type requires a different amount of memory.
C++ supports a wide variety of data types and the programmer can select the data type appropriate to
the needs of the application. Data types specify the size and types of value to be stored. However,
storage representation and machine instructions to manipulate each data type differ from machine to
machine, although C++ instructions are identical on all machines.

C++ supports the following data types:

1. Primary or Built in or Fundamental data type


2. Derived data types
3. User defined data types

Data types in C++ are mainly divided into three 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:
13
 Integer
 Character
 Boolean

14
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character
2. Derived Data Types: The data types that are derived from the primitive or built-in datatypes
arereferred to as Derived Data Types. These can be of four types namely:
 Function
 Array
 Pointer
 Reference
3. Abstract or User-Defined Data Types: These data types are defined by the user itself. Like, as
defining a class in C++ or a structure. C++ provides the following user-defined datatypes:
 Class
 Structure
 Union
 Enumeration
 Typedef defined DataType

This article discusses primitive data types available in C++.


 Integer: The keyword used for integer data types is int. Integers typically require 4 bytes of
memory space and range from -2147483648 to 2147483647.
 Character: Character data type is used for storing characters. The keyword used for the
character data type is char. Characters typically require 1 byte of memory space and range 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. The keyword used for the boolean data type is bool.
 Floating Point: Floating Point data type is used for storing single-precision floating-point values
or decimal values. The keyword used for the floating-point data type is float. Float variables
typically require 4 bytes of memory space.
 Double Floating Point: Double Floating Point data type is used for storing double-precision
floating-point values or decimal values. The keyword used for the double floating-point data type
is double. Double variables typically require 8 bytes of memory space.
 void: Void means without any value. void data type represents a valueless entity. A void data
type is used for those function which does not return a value.
 Wide Character: Wide character data type is also a character data type but this data type has a
size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4 bytes
long.
The size of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.

sizeof operator — sizeof operator is used to find the number of bytes occupied by a variable/data
type in computer memory. Eg: int m , x[50]; cout<<sizeof(m); //returns 4 which is the number
of bytes occupied by the integer variable “m”. cout<<sizeof(x); //returns 200 which is the number
of bytes occupied by the integer array variable “x”.
15
// Following is the example, which will produce correct size of various data types on your

16
computer.
#include <iostream>
using namespace
std;

int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;

cout << "Size of long : " << sizeof(long) << endl;


cout << "Size of float : " << sizeof(float) << endl;

cout << "Size of double : " << sizeof(double) << endl;

return 0;
}

Output
Size of char : 1
Size of int : 4 Size
of long : 8 Size of
float : 4 Size of
double : 8

Datatype Modifiers
As the name implies, datatype modifiers are used with the built-in data types to modify the length
ofdata that a particular data type can hold.

Data type modifiers available in C++ are:


 Signed
 Unsigned
 Short
17
 Long

18
The 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

long double 12

wchar_t 2 or 4 1 wide character

Note: Above values may vary from compiler to compiler. In the above example, we have considered
GCC 32 bit.
We can display the size of all the data types by using the sizeof() operator and passing the
keywordof the datatype as an argument to this function as shown below:
Now to get the range of data types refer to the following chart
Note: syntax<limits.h> header file is defined to find the range of fundamental data-types. Unsigned
modifiers have minimum value is zero. So, no macro constants are defined for the unsigned
minimum value.

 C++ Identifiers:-
19
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
C++.

Here are some examples of acceptable identifiers −

mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal

 Variable in C++:-
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.
Let's see the syntax to declare a variable:

type variable_list;
The example of declaring variable is given below:

int x;
float y;
char z;
Here, x, y, z are variables and int, float, char are data types. We can also provide values
whiledeclaring the variables as given below:

int x=5,b=10; //declaring 2 variable of integer type


float f=30.8;
char c='A';

Rules for defining variables


1. A variable can have alphabets, digits and underscore.
2. A variable name can start with alphabet and underscore only. It can't start with digit.
3. No white space is allowed within variable name.
4. A variable name must not be any reserved word or keyword e.g. char, float etc.

Valid variable names:


int a;
int _ab;
int a30;

Invalid variable names:


20
int 4;
int x y;
int double;

21
Variable Scope in C++:-
A scope is a region of the program and broadly speaking there are three places, where variables
canbe declared −

Inside a function or a block which is called local variables,


In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
We will learn what is a function and it's parameter in subsequent chapters. Here let us explain
whatare local and global variables.

Local Variables

Variables that are declared inside a function or block are local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions
outside their own. Following is the example using local variables −

#include <iostream>
using namespace std;

int main () {
// Local variable declaration:
int a, b;
int c;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c;

return 0;
}

Global Variables
Global variables are defined outside of all the functions, usually on top of the program. The global
variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. Following is the example using global and local
variables −
#include <iostream>
using namespace std;

// Global variable declaration:


int g;
22
int main () {
// Local variable declaration:
int a, b;

// actual initialization
a = 10;
b = 20;
g = a + b;

cout << g;

return 0;
}

A program can have same name for local and global variables but value of local variable inside a
function will take preference. For example :

#include <iostream>
using namespace std;

// Global variable declaration:


int g = 20;

int main () {
// Local variable declaration:
int g = 10;

cout << g;

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

10

Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you must initialize it yourself.Global
variables are initialized automatically by the system when you define them as follows −

Data Type Initializer

Int 0

Char '\0'

Float 0

Double 0

Pointer NULL

23
It is a good programming practice to initialize variables properly, otherwise sometimes programwould
produce unexpected result.

Differences between Identifiers and Keywords

The following is the list of differences between identifiers and keywords:

Identifiers Keywords

Identifiers are the names defined by the programmer to the Keywords are the reserved words whose meaningis
basic elements of a program. known by the compiler.

It is used to identify the name of the variable. It is used to specify the type of entity.

It can consist of letters, digits, and underscore. It contains only letters.

It can use both lowercase and uppercase letters. It uses only lowercase letters.

No special character can be used except the underscore. It cannot contain any special character.

24
The starting letter of identifiers can be lowercase, It can be started only with the lowercase letter.
uppercase or underscore.

It can be classified as internal and external identifiers. It cannot be further classified.

Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.

 C++ Expressions:-
C++ expression consists of operators, constants, and variables which are arranged according to the rules
of the language. It can also contain function calls which return values. An expression can consist of one
or more operands, zero or more operators to compute a value. Every expression produces some value
which is assigned to the variable with the help of an assignment operator.

Examples of C++ expression:

1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c 4.
(a+b) * (x+y)

An expression can be of following types:


o Constant expressions

o Integral expressions

o Float expressions

o Pointer expressions

o Relational expressions

o Logical expressions

o Bitwise expressions

o Special assignment expressions

25
If the expression is a combination of the above expressions, such expressions areknown
as compound expressions.

Constant expressions
A constant expression is an expression that consists of only constant values. It is an expression
whose value is determined at the compile-time but evaluated at the run-time.It can be
composed of integer, character, floating-point, and enumeration constants.

Constants are used in the following situations:

o It is used in the subscript declarator to describe the array bound.

o It is used after the case keyword in the switch statement.

o It is used as a numeric value in an enum

o It specifies a bit-field width.

26
o It is used in the pre-processor #if

In the above scenarios, the constant expression can have integer, character, and enumeration
constants. We can use the static and extern keyword with the constants todefine the function-
scope.

The following table shows the expression containing constant value:

Expression containing constant Constant value

x = (2/3) * 4 (2/3) * 4

extern int y = 67 67

int z = 43 43

static int a = 56 56

Let's see a simple program containing constant expression:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. x=(3/2) + 2; // constant expression
7. cout<<"Value of x is : "<<x; // displaying the value of x.
8. return 0;
9. }

In the above code, we have first declared the 'x' variable of integer type. After
declaration, we assign the simple constant expression to the 'x' variable.

Output
27
Value of x is : 3

Integral Expressions
An integer expression is an expression that produces the integer value as output after
performing all the explicit and implicit conversions.

Following are the examples of integral expression:

1. (x * y) -5
2. x + int(9.0)
3. where x and y are the integers.

Let's see a simple example of integral expression:

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x; // variable declaration.
6. int y; // variable declaration
7. int z; // variable declaration
8. cout<<"Enter the values of x and y";
9. cin>>x>>y;
10. z=x+y;
11. cout<<"\n"<<"Value of z is :"<<z; // displaying the value of z.
12. return 0;
13. }
In the above code, we have declared three variables, i.e., x, y, and z. After declaration, we take the user
input for the values of 'x' and 'y'. Then, we add the values of 'x' and 'y' and stores their result in 'z'
variable.

Output

Enter the values of x and y


8
9
Value of z is :17

Let's see another example of integral expression.


28
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int x; // variable declaration
7. int y=9; // variable initialization
8. x=y+int(10.0); // integral expression
9. cout<<"Value of x : "<<x; // displaying the value of x.
10. return 0;
11. }

In the above code, we declare two variables, i.e., x and y. We store the value of
expression (y+int(10.0)) in a 'x' variable.

Output

Value of x : 19

Float Expressions
A float expression is an expression that produces floating-point value as output after
performing all the explicit and implicit conversions.

The following are the examples of float expressions:

1. x+y
2. (x/10) + y
3. 34.5
4. x+float(10)

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
29
6. float x=8.9; // variable initialization

30
7. float y=5.6; // variable initialization
8. float z; // variable declaration
9. z=x+y;
10. std::cout <<"value of z is :" << z<<std::endl; // displaying the value of z.11.
12.
13. return 0;
14. }

Output

value of z is :14.5

Let's see another example of float expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. float x=6.7; // variable initialization
6. float y; // variable declaration
7. y=x+float(10); // float expression
8. std::cout <<"value of y is :" << y<<std::endl; // displaying the value of y
9. return 0;
10. }

In the above code, we have declared two variables, i.e., x and y. After declaration, we store the
value of expression (x+float(10)) in variable 'y'.

Output

value of y is :16.7

Pointer Expressions
A pointer expression is an expression that produces address value as an output.

The following are the examples of pointer expression:

1. &x

31
2. ptr
3. ptr++
4. ptr-

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5.
6. int a[]={1,2,3,4,5}; // array initialization
7. int *ptr; // pointer declaration
8. ptr=a; // assigning base address of array to the pointer ptr
9. ptr=ptr+1; // incrementing the value of pointer
10. std::cout <<"value of second element of an array : " << *ptr<<std::endl;
11. return 0;
12. }

In the above code, we declare the array and a pointer ptr. We assign the base address to the
variable 'ptr'. After assigning the address, we increment the value of pointer 'ptr'. When pointer is
incremented then 'ptr' will be pointing to the second element of the array.

Output

value of second element of an array : 2

Relational Expressions
A relational expression is an expression that produces a value of type bool, which can be either trueor
false. It is also known as a boolean expression. When arithmetic expressions are used on both sides of
the relational operator, arithmetic expressions are evaluated first, and then their results are compared.

The following are the examples of the relational expression:

1. a>b
2. a-b >= x-y
3. a+b>80

32
Let's understand through an example

33
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=45; // variable declaration
6. int b=78; // variable declaration
7. bool y= a>b; // relational expression
8. cout<<"Value of y is :"<<y; // displaying the value of y.
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. After declaration, we have applied
the relational operator between the variables to check whether 'a' is greater than 'b' or not.

Output

Value of y is :0

Let's see another example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=4; // variable declaration
6. int b=5; // variable declaration
7. int x=3; // variable declaration
8. int y=6; // variable declaration
9. cout<<((a+b)>=(x+y)); // relational expression
10. return 0;
11. }

In the above code, we have declared four variables, i.e., 'a', 'b', 'x' and 'y'. Then, we apply the
relational operator (>=) between these variables.

Output

34
Logical Expressions
A logical expression is an expression that combines two or more relational expressions and
produces a bool type value. The logical operators are '&&' and '||' that combines two or more
relational expressions.

The following are some examples of logical expressions:

1. a>b && x>y


2. a>10 || b==5

Let's see a simple example of logical expression.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=2;
6. int b=7;
7. int c=4;
8. cout<<((a>b)||(a>c));
9. return 0;
10. }

Output

Bitwise Expressions
A bitwise expression is an expression which is used to manipulate the data at a bit level. They are
basically used to shift the bits.

For example:

x=3

x>>3 // This statement means that we are shifting the three-bit position to the right.

In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting the value of 'x' by
three-bit position to the right. Let's understand through the diagrammatic representation.
35
Let's see a simple example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=5; // variable declaration
6. std::cout << (x>>1) << std::endl;
7. return 0;
8. }

In the above code, we have declared a variable 'x'. After declaration, we applied the bitwiseoperator,
i.e., right shift operator to shift one-bit position to right.

Output

36
2

Let's look at another example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int x=7; // variable declaration
6. std::cout << (x<<3) << std::endl;
7. return 0;
8. }

In the above code, we have declared a variable 'x'. After declaration, we applied the left shift
operator to variable 'x' to shift the three-bit position to the left.

Output

56

Special Assignment Expressions


Special assignment expressions are the expressions which can be further classified depending uponthe
value assigned to the variable.

o Chained Assignment

Chained assignment expression is an expression in which the same value is assigned to more thanone
variable by using single statement.

For example:

1. a=b=20
2. or
3. (a=b) = 20

Let's understand through an example.

1. #include <iostream>
2. using namespace std;

37
3. int main()
4.

38
5. int a; // variable declaration
6. int b; // variable declaration
7. a=b=80; // chained assignment
8. std::cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< std::endl;
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we have assigned the
same value to both the variables using chained assignment expression.

Output

Values of 'a' and 'b' are : 80,80

Note: Using chained assignment expression, the value cannot be assigned to the variable
at the time of declaration. For example, int a=b=c=90 is an invalid statement.
o Embedded Assignment Expression

An embedded assignment expression is an assignment expression in which assignment expressionis


enclosed within another assignment expression.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a; // variable declaration
6. int b; // variable declaration
7. a=10+(b=90); // embedded assignment expression
8. std::cout <<"Values of 'a' is " <<a<< std::endl;
9. return 0;
10. }

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we applied embedded
assignment expression (a=10+(b=90)).

Output

Values of 'a' is 100


39
o Compound Assignment

40
A compound assignment expression is an expression which is a combination of an assignment
operator and binary operator.

For example,

1. a+=10;

In the above statement, 'a' is a variable and '+=' is a compound statement.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. int
main()4.
{
5. int a=10; // variable declaration
6. a+=10; // compound assignment
7. std::cout << "Value of a is :" <<a<< std::endl; // displaying the value of a.
8. return 0;
9. }

In the above code, we have declared a variable 'a' and assigns 10 value to this variable. Then,
we applied compound assignment operator (+=) to 'a' variable, i.e., a+=10 which is equal to
(a=a+10).This statement increments the value of 'a' by 10.

Output

Value of a is :20

41
 C++ Operators:-
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:
Example
int x = 100 + 50;

Although the + operator is often used to add together two values, like in the example above, it can also
beused to add together a variable and a value, or a variable and another variable:
Example
int sum1= 100 + 50; // 150 (100 + 50)
int sum2= sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

C++ divides the operators into the following groups:

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Assignment Operators
Assignment operators are used to assign values to variables.
42
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:

43
Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable:


Example
int x = 10;
x += 5;

A list of all assignment operators:


Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x–3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison Operators
Comparison operators are used to compare two values.
Note: The return value of a comparison is either true (1) or false (0).
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3

A list of all comparison operators:

Operator Name Example

44
== Equal to x == y

45
!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


You will learn much more about comparison operators and how to use them in a later chapter.

Logical Operators
Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true

Predefined Math functions


C++ has many functions that allows you to perform mathematical tasks on numbers.

Max and min


The max(x,y) function can be used to find the highest value of x and y:
Example
cout << max(5, 10);
And the min(x,y) function can be used to find the lowest value of x and y:
Example
cout << min(5, 10);

C++ <cmath> Header


Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can
befound in the <cmath> header file:
Example
// Include the cmath
library#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);

Other Math Functions


46
A list of other popular Math functions (from the <cmath> library) can be found in the table below:

47
Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x

cbrt(x) Returns the cube root of x

ceil(x) Returns the value of x rounded up to its nearest integer

cos(x) Returns the cosine of x

cosh(x) Returns the hyperbolic cosine of x

exp(x) Returns the value of Ex

expm1(x) Returns ex -1

fabs(x) Returns the absolute value of a floating x

fdim(x, y) Returns the positive difference between x and y

floor(x) Returns the value of x rounded down to its nearest integer

hypot(x, y) Returns sqrt(x2 +y2) without intermediate overflow or underflow

fma(x, y, z) Returns x*y+z without losing precision

fmax(x, y) Returns the highest value of a floating x and y

fmin(x, y) Returns the lowest value of a floating x and y

fmod(x, y) Returns the floating point remainder of x/y

pow(x, y) Returns the value of x to the power of y

sin(x) Returns the sine of x (x is in radians)

sinh(x) Returns the hyperbolic sine of a double value

tan(x) Returns the tangent of an angle

tanh(x) Returns the hyperbolic tangent of a double value

48
 Manipulators in C++ with Examples:-
Manipulators are helping functions that can modify the input/output stream. It does not mean
thatwe change the value of a variable, it only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.
 Manipulators are special functions that can be included in the I/O statement to alter the
formatparameters of a stream.
 Manipulators are operators that are used to format the data display.
 To access manipulators, the file iomanip should be included in the program.

For example, if we want to print the hexadecimal value of 100 then we can print it as:

cout<<setbase(16)<<100

Types of Manipulators There are various types of manipulators:


1. Manipulators without arguments: The most important manipulators defined by
the IOStream library are provided below.
 endl: It is defined in ostream. It is used to enter a new line and after entering a new line
itflushes (i.e. it forces all the output written on the screen or in the file) the output
stream.
 ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
 ends: It is also defined in ostream and it inserts a null character into the output stream.

Examples:

#include <iostream>
#include <istream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
istringstream str(" Programmer");
string line;
// Ignore all the whitespace in string
// str before the first word.
getline(str >> std::ws, line);

// you can also write str>>ws


// After printing the output it will automatically
// write a new line in the output

49
stream.cout << line << endl;

// without flush, the output will be the same.

50
cout << "only a test" << flush;

// Use of ends
Manipulatorcout << "\na";

// NULL character will be added in the Output


cout << "b" << ends;
cout << "c" << endl;

return 0;
}

Output:
Programmer
only a test
abc

1. Manipulators with Arguments: Some of the manipulators are used with the argument like
setw (20), setfill (‘*’), and many more. These all are defined in the header file. If we want to
use these manipulators then we must include this header file in our program. For Example,
youcan use following manipulators to set minimum width and fill the empty space with any
character you want: std::cout << std::setw (6) << std::setfill (’*’);
 Some important manipulators in <iomanip> are:
1. setw (val): It is used to set the field width in output operations.
2. setfill (character): It is used to fill the character ‘c’ on output stream.
3. setprecision (val): It sets val as the new value for the precision of floating-point values.
4. setbase(val): It is used to set the numeric base value for numeric values.
5. setiosflags(flag): It is used to set the format flags specified by parameter mask.

 Some important manipulators in <ios> are:


1. showpos: It forces to show a positive sign on positive numbers.
2. noshowpos: It forces not to write a positive sign on positive numbers..
3. fixed: It uses decimal notation for floating-point values.
4. scientific: It uses scientific floating-point notation.
5. hex: Read and write hexadecimal values for integers and it works same as
thesetbase(16).
6. dec: Read and write decimal values for integers i.e. setbase(10).
7. oct: Read and write octal values for integers i.e. setbase(10).
8. left: It adjusts output to the left.
9. right: It adjusts output to the right.

There are two types of manipulators used generally:


1] Parameterized and
2] Non-parameterized
51
1] Parameterized Manipulators:-
setw (n) -> To set field width to n
setprecision (p) -> The precision is fixed to p
setfill (‘*’) -> To set the character to be filled
setiosflags (l) -> Format flag is set to l
Setbase(b) -> To set the base of the number to
b
 setw() is a function in Manipulators in C++:
The setw() function is an output manipulator that inserts whitespace between two variables.
You must enter an integer value equal to the needed space.
Example:
int a=15; int b=20;
cout << setw(10) << a << setw(10) << b << endl;
 setfill() is a function in Manipulators in C++:
It replaces setw(whitespaces )’s with a different character. It’s similar to setw() in that it
manipulates output, but the only parameter required is a single character.

Example:
int a,b;
a=15; b=20;
cout<< setfill(‘*’) << endl;
cout << setw(5) << a << setw(5) << b<< endl;
 setprecision() is a function in Manipulators in C++:
It is an output manipulator that controls the number of digits to display after the decimal for a
floating point integer.
Example:
float A = 1.34255;
cout << setprecision(3) << A << endl;
 setbase() is a function in Manipulators in C++:
The setbase() manipulator is used to change the base of a number to a different value. The
following base values are supported by the C++ language:
• hex (Hexadecimal = 16)
• oct (Octal = 8)
• dec (Decimal = 10)
The manipulators hex, oct, and dec can change the basis of input and output numbers.

// Example:

#include <iostream>
#include <iomanip>

using namespace std;


main()
52
{

int number = 100;

53
cout << "Hex Value =" << " " << hex << number << endl;
cout << "Octal Value=" << " " << oct << number << endl;
cout << "Setbase Value=" << " " << setbase(8) << number << endl; cout
<< "Setbase Value=" << " " << setbase(16) << number << endl;

return 0;
}

Output
Hex Value = 64
Octal Value= 144
Setbase Value= 144
Setbase Value= 64

2] Non-parameterized
Examples are endl, fixed, showpoint
• endl – Gives a new line
• ends – Adds null character to close an output string
• hex, oct, dec – Displays the number in hexadecimal or octal or in decimal format

 C++ decision making statements:-


In C++ programming, if statement is used to test the condition. There are various types of if
statements in C++.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder

if Statement
The C++ if statement tests the condition. It is executed if condition is true.

if(condition){
/code to be executed
}

54
Example:

#include <iostream>
using namespace std;

int main ()
{
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}

Output:
It is even number

IF-else Statement
The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwiseelse block is executed.

if(condition){
//code if condition is true
}else{
//code if condition is false
}

55
if-else Example
#include <iostream>
using namespace std;
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}

Output:
It is odd number

if-else Example: with input from user

#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0)
{
cout<<"It is even number"<<endl;
}
else

56
{
cout<<"It is odd number"<<endl;
}

57
return 0;
}

Output:
Enter a number:11
It is odd number

Output:
Enter a number:12
It is even number

if-else-if ladder Statement


The C++ if-else-if ladder statement executes one condition from multiple statements.

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

if else-if Example
#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check
grade:";cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
58
else if(num >= 0 && num < 50){
cout<<"Fail";

59
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}

Output:
Enter a number to check grade:66
C Grade
Output:
Enter a number to check grade:-2
wrong number

 Switch Statements:-
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code
blockbreak;
default:
// code block
}
This is how it works:
 The switch expression is evaluated once
 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break and default keywords are optional, and will be described later in this
60
chapterThe example below uses the weekday number to calculate the weekday name:

61
Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)

The break Keyword


When C++ reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the
block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code
in the switch block.

Loops:-
In programming, sometimes there is a need to perform some operation more than once or (say) n
number of times. Loops come 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 done in two ways as
shown below:
Manual(general) Method (Iterative Method)
Manually we have to write cout statement 10 times. Let’s say you have to write it 20 times (it would
surely take more time to write 20 statements) now imagine you have to write it 100 times, it

62
wouldbe really hectic to re-write the same statement again and again. So, here loops have their role.

// C++ program to illustrate need of


loops#include <iostream>

63
using namespace std;

int main()
{
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
return 0;
}

Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

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.

There are mainly two types of loops:


1. Entry Controlled loops: In this type of loop, the test condition is tested before entering
the loop body. For Loop and While Loop is entry-controlled loops.
2. Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the
end of the loop body. Therefore, the loop body will execute at least once, irrespective of
whether the test condition is true or false. the do-while loop is exit controlled loop.

Loop Type and Description


1. while loop – First checks the condition, then executes the body.
2. for loop – firstly initializes, then, condition check, execute body, update.
3. do-while – firstly, execute the body then condition check

64
for Loop
A for loop is a repetition control structure that 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

65
line.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Example:
for(int i = 0; i < n; i++){
}
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 the counter value. If
the statement is true, then the loop body is executed and the loop variable gets updated.
Steps are repeated till the 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 the loop and go to update expression
otherwise we will exit from the for a loop. For example: i <= 10;
 Update Expression: After executing the loop body this expression
increments/decrements the loop variable by some value. for example: i++;

Example:

// C++ program to illustrate for


loop#include <iostream>
using namespace std;

int main()
{
for (int i = 1; i <= 10; i++)
{
cout << "Hello World\n";
}

return 0;
}

Output:
Hello World
Hello World
Hello World
Hello World
Hello World

66
Hello World
Hello World
Hello World
Hello World

67
Hello World

While Loop
While studying for loop we have seen that the number of iterations is known beforehand,
i.e. the number of times the loop body is needed to be executed is known to us. while loops
are used in situations where we do not know the exact number of iterations of the
loop beforehand. The loop execution is terminated on the basis of the test conditions.
Syntax: We have already stated that a loop mainly consists of three statements –
initialization expression, test expression, and update expression. The syntax of the three
loops – For, while, and do while mainly differs in the placement of these three statements.
initialization expression;
while (test_expression)
{
// statements
update_expression;
}

Example:

// C++ program to illustrate while


loop#include <iostream>
using namespace std;

int main()
{
// initialization
expressionint i = 1;

// test
expressionwhile
(i < 6)
{
cout << "Hello World\n";

// update
expressioni++;
}

return 0;
}

Output:
Hello World
Hello World
Hello World
Hello World

68
Hello World

69
do-while loop
In do-while loops also the loop execution is terminated on the basis of test conditions. The main
difference between a do-while loop and the while loop is in the do-while loop the condition is
testedat the end of the loop body, i.e do-while loop is exit controlled whereas the other two loops are
entry controlled loops.
Note: In a do-while loop, the loop body will execute at least once irrespective of the test condition.

Syntax:
initialization expression;
do
{
// statements

update_expression;
} while (test_expression);

Note: Notice the semi – colon(“;”) in the end of loop.

Example:

// C++ program to illustrate do-while


loop#include <iostream>
using namespace std;

int main()
{
int i = 2; // Initialization expression

do
{
// loop body
cout << "Hello World\n";

// update
expressioni++;

} while (i < 1); // test expression

return 0;
}

Output:
Hello World

In the above program, the test condition (i<1) evaluates to false. But still, as the loop is
anexit – controlled the loop body will execute once.

Infinite Loop?
70
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks
a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition is

71
always evaluated to be true. Usually, this is an error.

Using For loop:

// C++ program to demonstrate infinite loops using


for#include <iostream>
using namespace
std;int main ()
{
int i;

// This is an infinite for loop as the condition


// expression is
blankfor ( ; ; )
{
cout << "This loop will run forever.\n";
}
}

Output:
This loop will run forever.
This loop will run forever.
...................

Using While loop:

#include <iostream>
using namespace
std;

int main()
{

while (1)
cout << "This loop will run forever.\n";
return 0;
}

Output:
This loop will run forever.
This loop will run forever.
...................

Using Do-While loop:

#include <iostream>
using namespace
72
std;

int main() {

73
do{
cout << "This loop will run forever.\n";
} while(1);

return 0;
}

Output:
This loop will run forever.
This loop will run forever.
...................

 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.
Functions are used to perform certain actions, and they are important for reusing code: Define the
code once, and use it many times.

Advantage of functions
There are many advantages of functions.
1) Code Reusability
By creating functions in C++, you can call it many times. So we don't need to write the same
code again and again.
2) Code optimization
It makes the code optimized, we don't need to write much code.
Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime number or not.
Without using function, you need to write the prime number logic 3 times. So, there is
repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it several
times.

Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C++ header files such as
ceil(x), cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++ programmer, so

74
that he/she can use it many times. It reduces complexity of a big program and optimizes the
code.

75
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can
alsocreate your own functions to perform certain actions.

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

Note: If a user-defined function, such as myFunction() is declared after the main() function, an error will
occur:
Example
int main() {
myFunction();
return 0;
76
}

void myFunction() {

77
cout << "I just got executed!";
}

// Error
However, it is possible to separate the declaration and the definition of the function - for code
optimization.

You will often see C++ programs that have function declaration above main(), and function
definitionbelow main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();

// The main
methodint main() {
myFunction(); // call the
functionreturn 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}

Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executedlater, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"

A function can be called multiple times:


Example
void myFunction() {
cout << "I just got executed!\n";
}

78
int main() {
myFunction();
myFunction();
myFunction();

79
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

Example:
Below is a simple program to demonstrate functions.

#include <iostream>
using namespace
std;

int max(int x, int y)


{
if (x > y)
return x;
else
return y;
}

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

// Calling above function to find max of 'a' and


'b'int m = max(a, b);

cout << "m is " << m;


return 0;
}

Output:
m is 20

Parameter Passing to functions


The parameters passed to function are called actual parameters. For example, in the above
program 10 and 20 are actual parameters.
The parameters received by function are called formal parameters. For example, in the above
program x and y are formal parameters.
There are two most popular ways to pass parameters.
Pass by Value: In this parameter passing method, values of actual parameters are copied to
function’s formal parameters and the two types of parameters are stored in different memory
locations. So any changes made inside functions are not reflected in actual parameters of caller.
Pass by Reference Both actual and formal parameters refer to same locations, so any changes
made inside the function are actually reflected in actual parameters of caller.
Parameters are always passed by value in C. For example. in the below code, value of x is not
modified using the function fun().

80
#include <iostream>
using namespace
std;

void fun(int x) {

81
x = 30;
}

int main() {
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}

Output:
x = 20

However, in C, we can use pointers to get the effect of pass-by reference. For example, consider
the below program. The function fun() expects a pointer ptr to an integer (or an address of an
integer). It modifies the value at the address ptr. The dereference operator * is used to access
thevalue at an address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The address
operator & is used to get the address of a variable of any data type. In the function call statement
‘fun(&x)’, the address of x is passed so that x can be modified using its address.

#include <iostream>
using namespace
std;

void fun(int *ptr)


{
*ptr = 30;
}

int main() {
int x = 20;
fun(&x);
cout << "x = " << x;

return 0;
}

Output:
x = 30

Default Values for Parameters


When you define a function, you can specify a default value for each of the last parameters.
Thisvalue will be used if the corresponding argument is left blank when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the function
definition. If a value for that parameter is not passed when the function is called, the default given
value is used, but if a value is specified, this default value is ignored and the passed value is used
instead. Consider the following example −
82
#include <iostream>
using namespace std;

int sum(int a, int b = 20) {

83
int result;
result = a + b;

return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120

Following are some important points about functions in C++.


1) Every C++ program has a function called main() that is called by operating system when a user
runs the program.
2) Every function has a return type. If a function doesn’t return any value, then void is used as a
return type. Moreover, if the return type of the function is void, we still can use return statement in
the body of function definition by not specifying any constant, variable, etc. with it, by only
mentioning the ‘return;’ statement which would symbolize the termination of the function as
shown below:

void function name(int a)


{
....... //Function Body
return; //Function execution would get terminated
}

3) In C and C++, functions can return any type except arrays and functions. We can get around this
limitation by returning pointer to array or pointer to function.
4) Empty parameter list means that the parameter list is not specified and function can be
called with any parameters. In C, it is not a good idea to declare a function like fun(). To declare a
function that can only be called without any parameter, we should use “void fun(void)”.
As a side note, in C++, an empty list means a function can only be called without any parameter. In
C++, both void fun() and void fun(void) are same.

84
Main Function:
The main function is a special function. Every C++ program must contain a function named main.

85
It serves as the entry point for the program. The computer will start running the code from the
beginning of the main function.
Types of main Function:
1) The first type is – main function without parameters :

// Without
Parametersint main()
{
...
return 0;
}

2) Second type is main function with parameters :

// With Parameters
int main(int argc, char * const argv[])
{
...
return 0;
}

The reason for having the parameter option for the main function is to allow input from the
command line.
When you use the main function with parameters, it saves every group of characters (separated
bya space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return
statement in the code. The number that is returned is used to inform the calling program what the
result of the program’s execution was. Returning 0 signals that there were no problems.

 Storage Classes in C++:-


Storage class is used to define the lifetime and visibility of a variable and/or function within a C++
program.

Lifetime refers to the period during which the variable remains active and visibility refers to the
module of a program in which the variable is accessible.

There are five types of storage classes, which can be used in a C++ program
1. Automatic
2. Register
3. Static
4. External
5. Mutable

Storage Class Keyword Lifetime Visibility Initial Value


86
Automatic Auto Function Block Local Garbage

Register Register Function Block Local Garbage

External Extern Whole Program Global Zero

Static Static Whole Program Local Zero

Automatic Storage Class


It is the default storage class for all local variables. The auto keyword is applied to all local
variables automatically.

{
auto int y;
float y = 3.45;
}
The above example defines two variables with a same storage class, auto can only be used
withinfunctions.

Register Storage Class


The register variable allocates memory in register than RAM. Its size is same of register size. It has
a faster access than other variables. It is recommended to use register variable only for quick
access such as in counter. We can't get the address of register variable.

register int counter=0;

Static Storage Class


The static variable is initialized only once and exists till the end of a program. It retains its value
between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

#include <iostream>
using namespace
std;void func() {
static int i=0; //static
variableint j=0; //local
variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()

87
{
func();
func();
func();

}
Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

External Storage Class


The extern variable is visible to all the programs. It is used if two or more files are sharing same
variable or function.
extern int counter=0;

88
C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location.

In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index starts from
0. We can store only fixed set of elements in C++ array.

Advantages of C++ Array


 Code Optimization (less code)
 Random Access
 Easy to traverse data
 Easy to manipulate data
 Easy to sort data etc.
 Disadvantages of C++ Array
 Fixed size

C++ Array Types


There are 2 types of arrays in C++ programming:
1. Single Dimensional Array
2. Multidimensional Array

C++ Single Dimensional Array


Let's see a simple example of C++ array, where we are going to create, initialize and traverse
array.

#include <iostream>
using namespace
std;int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array

89
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output:
10
0
20
0
30

C++ Array Example: Traversal using for each loop


We can also traverse the array elements using foreach loop. It returns array element one by one.

#include <iostream>
using namespace
std;int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing
arrayfor (int i:
arr)
{
cout<<i<<"\n";
}
}
Output:

10
20
30
40
50

C++ Passing Array to Function


In C++, to reuse the array logic, we can create function. To pass array to function in C++, we need
to provide only array name.

functionname(arrayname); //passing array to function

Let's see an example of C++ function which prints the array elements.

#include <iostream>
using namespace
std;
90
void printArray(int arr[5]);
int main()
{
int arr1[5] = { 10, 20, 30, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };

91
printArray(arr1); //passing array to
functionprintArray(arr2);
}
void printArray(int arr[5])
{
cout << "Printing array elements:"<< endl;
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}

Output:
Printing array
elements:10
20
30
40
50
Printing array
elements:5
15
25
35
45

C++ Passing Array to Function Example 1:


Let's see an example of C++ array which prints minimum number in an array using function.

#include <iostream>
using namespace std;
void printMin(int arr[5]);
int main()
{
int arr1[5] = { 30, 10, 20, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
printMin(arr1);//passing array to
functionprintMin(arr2);
}
void printMin(int arr[5])
{
int min = arr[0];
for (int i = 0; i > 5; i++)
{
if (min > arr[i])
92
{
min = arr[i];
}

93
}
cout<< "Minimum element is: "<< min <<"\n";
}

Output:
Minimum element is: 10
Minimum element is: 5

C++ Passing Array to Function Example 2:


Let's see an example of C++ array which prints maximum number in an array using function.

#include <iostream>
using namespace
std;
void printMax(int arr[5]);
int main()
{
int arr1[5] = { 25, 10, 54, 15, 40 };
int arr2[5] = { 12, 23, 44, 67, 54 };
printMax(arr1); //Passing array to
functionprintMax(arr2);
}
void printMax(int arr[5])
{
int max = arr[0];
for (int i = 0; i < 5; i++)
{
if (max < arr[i])
{
max = arr[i];
}
}
cout<< "Maximum element is: "<< max <<"\n";
}

Output:
Maximum element is: 54
Maximum element is: 67

 Multi dimensional arrays:-


C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration −
type name[size1][size2]...[sizeN];

94
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −
int threedim[5][10][4];

95
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array
ofsize x,y, you would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y number of
columns. A 2-dimensional array a, which contains three rows and four columns can be shown as
below −

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
thename of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays
Multidimensioned arrays may be initialized by specifying bracketed values for each row. Following
is an array with 3 rows and each row have 4 columns.
int a[3][4] = {{0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11}};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
columnindex of the array. For example −
int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in
theabove digram.

96
#include <iostream>
using namespace std;

int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

// output each array element's value


for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ ) {

cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}

return 0;
}

97
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely that
most of the arrays you create will be of one or two dimensions.

C++ Pointer to an Array


It is most likely that you would not understand this chapter until you go through the chapter
relatedC++ Pointers.
So assuming you have bit understanding on pointers in C++, let us start: An array name is a
constantpointer to the first element of the array. Therefore, in the declaration −
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array balance.
Thus, the following program fragment assigns p the address of the first element of balance −
double *p;
double balance[10];
p = balance;
It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is
alegitimate way of accessing the data at balance[4].
Once you store the address of first element in p, you can access array elements using *p, *(p+1),
*(p+2) and so on. Below is the example to show all the concepts discussed above −
#include <iostream>
using namespace std;

int main () {
// an array with 5 elements.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;

p = balance;

// output each array element's value


cout << "Array values using pointer " << endl;

for ( int i = 0; i < 5; i++ ) {


cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
98
cout << "Array values using balance as address " << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "*(balance + " << i << ") : ";
cout << *(balance + i) << endl;
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
Array values using pointer
*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
Array values using balance as address
*(balance + 0) : 1000
*(balance + 1) : 2
*(balance + 2) : 3.4
*(balance + 3) : 17
*(balance + 4) : 50
In the above example, p is a pointer to double which means it can store address of a variable of
double type. Once we have address in p, then *p will give us value available at the address stored
inp, as we have shown in the above example.

C++ Passing Arrays to Functions


C++ does not allow to pass an entire array as an argument to a function. However, You can pass a
pointer to an array by specifying the array's name without an index.
If you want to pass a single-dimension array as an argument in a function, you would have to declare
function formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received.

Way-1(Formal parameters as a pointer as follows) −


void myFunction(int *param) {
.
.
.
}

Way-2(Formal parameters as a sized array as follows) −


void myFunction(int param[10]) {
.
.
.

99
}

Way-3(Formal parameters as an unsized array as follows)

100
void myFunction(int param[]) {
.
.
}
Now, consider the following function, which will take an array as an argument along with another
argument and based on the passed arguments, it will return average of the numbers passed
throughthe array as follows −
double getAverage(int arr[], int size) {
int i, sum = 0;
double avg;

for (i = 0; i < size; ++i) {


sum += arr[i];
}
avg = double(sum) / size;

return avg;
}

Now, let us call the above function as follows −


#include <iostream>
using namespace std;
// function declaration:
double getAverage(int arr[], int size);

int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

// pass pointer to the array as an argument.


avg = getAverage( balance, 5 ) ;

// output the returned value


cout << "Average value is: " << avg << endl;

return 0;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.4
As you can see, the length of the array doesn't matter as far as the function is concerned because
C++performs no bounds checking for the formal parameters.

Return Array from Functions


C++ does not allow to return an entire array as an argument to a function. However, you can return
apointer to an array by specifying the array's name without an index.
If you want to return a single-dimension array from a function, you would have to declare a
101
functionreturning a pointer as in the following example –

102
int * myFunction() {
.
.
}

Second point to remember is that C++ does not advocate to return the address of a local variable
tooutside of the function so you would have to define the local variable as static variable.
Now, consider the following function, which will generate 10 random numbers and return them
using an array and call this function as follows −
#include <iostream>
#include <ctime>

using namespace std;

// function to generate and retrun random numbers.


int * getRandom( ) {

static int r[10];

// set the seed


srand( (unsigned)time( NULL ) );

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


r[i] = rand();
cout << r[i] << endl;
}

return r;
}

// main function to call above defined function.


int main () {

// a pointer to an int.
int *p;

p = getRandom();

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


cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}

return 0;
}
When the above code is compiled together and executed, it produces result something as follows −
624723190
1468735695
807113585
976495677
613357504
1377296355

103
1530315259
1778906708

104
1820354158
667126415
*(p + 0) : 624723190
*(p + 1) : 1468735695
*(p + 2) : 807113585
*(p + 3) : 976495677
*(p + 4) : 613357504
*(p + 5) : 1377296355
*(p + 6) : 1530315259
*(p + 7) : 1778906708
*(p + 8) : 1820354158
*(p + 9) : 667126415

 C++ 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 bya
null character '\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++ −

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 −

105
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;

106
return 0;
}
When the above code is compiled and executed, it produces the following result −
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);
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.

Following example makes use of few of the above-mentioned functions −


#include <iostream>
#include <cstring>
using namespace std;

int main () {
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;

// copy str1 into str3


strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl; 107
return 0;
}
When the above code is compiled and executed, it produces result something as follows −
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

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

 C++ Pointers:-
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with pointers,
andother C++ tasks, such as dynamic memory allocation, cannot be performed without them.

108
As you know every variable is a name of 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: ";


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
doublefloat *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.

Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees

109
etc.and used with arrays, structures and functions.
2) We can return multiple values from function using pointer.
3) It makes you able to access any memory location in the computer's memory.

Usage of pointer

There are many usage of pointers in C++ language.


1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.
2) Arrays, Functions and Structures
Pointers in c language are widely used in arrays, functions and structures. It reduces the code
andimproves the performance.

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
addressspecified by its operand. Following example makes use of these operations −
#include <iostream>
using namespace std;

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
110
Pointer Program to swap 2 numbers without using 3rd variable

#include <iostream>
using namespace std;
int main()
{
int a=20,b=10,∗p1=&a,∗p2=&b;

cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;


∗p1=∗p1+∗p2;
∗p2=∗p1-∗p2;
∗p1=∗p1-∗p2;
cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
return 0;
}
Output:
Before swap: ∗p1=20 ∗p2=10
After swap: ∗p1=10 ∗p2=20

Pointers vs Arrays
Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many
cases. For example, a pointer that points to the beginning of an array can access that array by using
either pointer arithmetic or array-style indexing. Consider the following program −
#include <iostream>

using namespace std;


const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;

for (int i = 0; i < MAX; i++) {


cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


ptr++;
}

return 0;
}

111
When the above code is compiled and executed, it produces result something as follows −
Address of var[0] = 0xbfa088b0
Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200
However, pointers and arrays are not completely interchangeable. For example, consider the
following program −

#include <iostream>

112
113
114
using namespace std;
const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};

for (int i = 0; i < MAX; i++) {


*var = i; // This is a correct syntax
var++; // This is incorrect.
}

return 0;
}
It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value.
The reason for this is that var is a constant that points to the beginning of an array and can not
beused as l-value.
Because an array name generates a pointer constant, it can still be used in pointer-style
expressions, as long as it is not modified. For example, the following is a valid statement that assigns
var[2] the value 500 −
*(var + 2) = 500;
Above statement is valid and will compile successfully because var is not changed.

Passing Pointers to Functions


C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a
pointer type.

Following a simple example where we pass an unsigned long pointer to a function and change the
value inside the function which reflects back in the calling function −

#include <iostream>
#include <ctime>
using namespace std;
void getSeconds(unsigned long *par);

int main () {
unsigned long sec;
getSeconds( &sec );

// print the actual value


cout << "Number of seconds :" << sec << endl;

return 0;
}

void getSeconds(unsigned long *par) {


// get the current number of seconds
*par = time( NULL );
115
return;
}
When the above code is compiled and executed, it produces the following result −
Number of seconds :1294450468
The function which can accept a pointer, can also accept an array as shown in the following example

#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);

int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

// pass pointer to the array as an argument.


avg = getAverage( balance, 5 ) ;

// output the returned value


cout << "Average value is: " << avg << endl;

return 0;
}

double getAverage(int *arr, int size) {


int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}

When the above code is compiled together and executed, it produces the following result −

Average value is: 214.4

 C++ structures:-
C/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 −
116
 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
wayyou 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 −

117
#include <iostream>
#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");

118
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
Book 2 subject : Telecom
Book 2 id : 6495700

Structures as Function Arguments


You can pass a structure as a function argument in very similar way as you pass any other variable or
pointer. You would access structure variables in the similar way as you have accessed in the above
example −

119
#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books book );

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

120
// 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


printBook( Book1 );
// Print Book2 info
printBook( Book2 );

return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}

When the above code is compiled and executed, it produces the following result −

Book title : Learn C++ Programming


Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700

Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other
variableas follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To
findthe address of a structure variable, place the & operator before the structure's name as follows −

struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the -> operator
asfollows −
121
struct_pointer->title;

122
Let us re-write above example using structure pointer, hope this will be easy for you to
understandthe concept −
#include <iostream>
#include <cstring>

using namespace std;


void printBook( struct Books *book );

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, passing address of structure


printBook( &Book1 );

// Print Book1 info, passing address of structure


printBook( &Book2 );

return 0;
}

// This function accept pointer to structure as parameter.


void printBook( struct Books *book ) {
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −

Book title : Learn C++


ProgrammingBook
author : Chand Miyan
Book subject : C++
ProgrammingBook id
: 6495407
123
Book title :
Telecom Billing
Book author :
Yakit Singha
Book subject :
Telecom
Book id : 6495700

Difference Between C Structures and C++ Structures


C Structures C++ Structures

Only data members are allowed, it cannot have


member functions. Can hold both: member functions and data members.

Cannot have static members. Can have static members.

Cannot have a constructor inside a structure. Constructor creation is allowed.

Direct Initialization of data members is not


possible. Direct Initialization of data members is possible.

Writing the ‘struct’ keyword is necessary to Writing the ‘struct’ keyword is not necessary to
declare structure-type variables. declare structure-type variables.

Do not have access modifiers. Supports access modifiers.

124
C Structures C++ Structures

Only pointers to structs are allowed. Can have both pointers and references to the struct.

Sizeof operator will generate 0 for an empty


structure. Sizeof operator will generate 1 for an empty structure.

Data Hiding is not possible. Data Hiding is possible.

Similarities Between the C and C++ Structures


 Both in C and C++, members of the structure have public visibility by default. Lets
discuss some of the above mentioned differences and similarities one by one:

125
The typedef Keyword
There is an easier way to define structs or you could "alias" types you create. For example −typedef
struct {
char title[50]; char
author[50]; char
subject[100];int
book_id;
} Books;
Now, you can use Books directly to define variables of Books type without using struct keyword.
Following is the example −

Books Book1, Book2;


You can use typedef keyword for non-structs as well as follows −typedef long
int *pint32;
pint32 x, y, z;
x, y and z are all pointers to long int.

 Differences Between C and C++:-


C++ is a special-purpose programming language developed by Bjarne Stroustrup atBell
Labs circa 1980. C++ language is very similar to C language, and it is so compatible with C
that it can run 99% of C programs without changing any source of code though C++ is an
object-oriented programming language, so it is safer and well- structured programming
language than C.

Let's understand the differences between C and C++.

126
The following are the differences between C and C++:

ADVERTISEMENT

o Definition
C is a structural programming language, and it does not support classes and
objects, while C++ is an object-oriented programming language that supportsthe
concept of classes and objects.

o Type of programming language


C supports the structural programming language where the code is checked lineby
line, while C++ is an object-oriented programming language that supports the
concept of classes and objects.

127
o
o Developer of the language
Dennis Ritchie developed C language at Bell Laboratories while Bjarne Stroustrup
developed the C++ language at Bell Labs circa 1980.

o Subset
C++ is a superset of C programming language. C++ can run 99% of C code butC
language cannot run C++ code.

o Type of approach
C follows the top-down approach, while C++ follows the bottom-up approach. The
top-down approach breaks the main modules into tasks; these tasks are broken into
sub-tasks, and so on. The bottom-down approach develops the lowerlevel modules
first and then the next level modules.

o Security
In C, the data can be easily manipulated by the outsiders as it does not support the
encapsulation and information hiding while C++ is a very secure language, i.e., no
outsiders can manipulate its data as it supports both encapsulation and data hiding.
In C language, functions and data are the free entities, and in C++ language, all the
functions and data are encapsulated in the form of objects.

o Function Overloading
Function overloading is a feature that allows you to have more than one functionwith
the same name but varies in the parameters. C does not support the function
overloading, while C++ supports the function overloading.

o Function Overriding
Function overriding is a feature that provides the specific implementation to the
function, which is already defined in the base class. C does not support the function
overriding, while C++ supports the function overriding.

o Reference variables
C does not support the reference variables, while C++ supports the reference
variables.

o Keywords
C contains 32 keywords, and C++ supports 52 keywords.

128
o Namespace feature
A namespace is a feature that groups the entities like classes, objects, and

129
functions under some specific name. C does not contain the namespace feature,while
C++ supports the namespace feature that avoids the name collisions.

o Exception handling
C does not provide direct support to the exception handling; it needs to usefunctions
that support exception handling. C++ provides direct support to exception handling by
using a try-catch block.

o Input/Output functions
In C, scanf and printf functions are used for input and output operations,respectively,
while in C++, cin and cout are used for input and output operations, respectively.

o Memory allocation and de-allocation


C supports calloc() and malloc() functions for the memory allocation, and free()function
for the memory de-allocation. C++ supports a new operator for the memory allocation
and delete operator for the memory de-allocation.

o Inheritance
Inheritance is a feature that allows the child class to reuse the properties of theparent
class. C language does not support the inheritance while C++ supports the
inheritance.

o Header file
C program uses <stdio.h> header file while C++ programuses
<iostream.h> header file.

Let's summarize the above differences in a tabular form.

No. C C++

1) C follows the procedural C++ is multi-paradigm. It supports


style programming. both procedural and object oriented.

2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for

130
outside users.

3) C follows the top-down C++ follows the bottom-up approach.


approach.

4) C does not support function C++ supports function overloading.


overloading.

5) In C, you can't use functions in In C++, you can use functions in


structure. structure.

6) C does not support reference C++ supports reference variables.


variables.

7) In C, scanf() and printf() are C++ mainly uses stream cin and
mainly used for input/output. cout to perform input and output
operations.

8) Operator overloading is not Operator overloading is possible in C++.


possible in C.

9) C programs are divided C++ programs are divided into


into procedures and functions and classes.
modules

10) C does not provide the featureof C++ supports the feature of namespace.
namespace.

11) Exception handling is not easy C++ provides exception handling using Try
in C. It has to perform using and Catch block.
other functions.

12) C does not support the C++ supports inheritance.


inheritance.

131
 C++ Dynamic Memory:-
A good understanding of how dynamic memory really works in C++ is essential to becoming a good
C++ programmer. Memory in your C++ program is divided into two parts −
 The stack − All variables declared inside the function will take up memory from the stack. 
 The heap − This is unused memory of the program and can be used to allocate the memory
dynamically when program runs.
Many times, you are not aware in advance how much memory you will need to store particular
information in a defined variable and the size of required memory can be determined at run time.
You can allocate memory at run time within the heap for the variable of a given type using a special
operator in C++ which returns the address of the space allocated. This operator is
called new operator.
If you are not in need of dynamically allocated memory anymore, you can use delete operator, which
de-allocates memory that was previously allocated by new operator.

new and delete Operators


There is following generic syntax to use new operator to allocate memory dynamically for any data-
type.
new data-type;

132
Here, data-type could be any built-in data type including an array or any user defined data types
include class or structure. Let us start with built-in data types. For example we can define a pointer to
type double and then request that the memory be allocated at execution time. We can do this using
the new operator with the following statements −
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had been used up. So it is
good practice to check if new operator is returning NULL pointer and take appropriate action as
below −
double* pvalue = NULL;
if( !(pvalue )) {
cout << "Error: out of memory." <<endl;
exit(1);
}
The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc()
function. The main advantage of new over malloc() is that new doesn't just allocate memory, it
constructs objects which is prime purpose of C++.
At any point, when you feel a variable that has been dynamically allocated is not anymore required,
you can free up the memory that it occupies in the free store with the ‘delete’ operator as follows −
delete pvalue; // Release memory pointed to by pvalue

Initialize memory: We can also initialize the memory for built-in data types using a new operator.
For custom data types, a constructor is required (with the data type as input) for initializing the
value. Here’s an example of the initialization of both data types :
pointer-variable = new data-type(value);

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

Let us put above concepts and form the following example to show how ‘new’ and
‘delete’ work −
#include <iostream>
using namespace std;

int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable

int *q = new int (25); // Pointer initialized with value

*pvalue = 29494.99; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;
cout << "Value of q : " << *q << endl;

delete pvalue; // free up the memory.


delete q;

133
return 0;
}
If we compile and run above code, this would produce the following result −
Value of pvalue : 29495

Dynamic Memory Allocation for Arrays


Allocate a block of memory: new operator is also used to allocate a block(an array) of memory of
type data-type. .
Example:
int *p = new int[10]
Dynamically allocates memory for 10 integers continuously of type int and returns a pointer to the
first element of the sequence, which is assigned top(a pointer). p[0] refers to the first element, p[1]
refers to the 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 differ e nce is, that normal arrays are deallocated by t he compiler (If the
array is local, then deallocated when the function returns or completes). However, dynamically
allocated arrays always remain there until either they are deallocated by the programmer or the
program terminates.

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

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

// C++ program to illustrate dynamic allocation


// and deallocation of memory using new and delete
#include <iostream>
using namespace std;

int main ()
{

// Request block of memory of size n


int n = 5;
int *q = new int[n];

if (!q)
cout << "allocation of memory failed\n";
else
134
{
for (int i = 0; i < n; i++)
q[i] = i+1; // or *(q+i)=i+1

cout << "Values stored in block of memory: "; for (int i = 0; i <
n; i++)
cout << q[i] << " ";
}

// freed the block of allocated memorydelete [] q;

return 0;
}

Output:

Value store in block of memory: 1 2 3 4 5

135
C Revision Topics:-
Arrays,
Strings,
Structures,
Pointers etc..
C Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language whichcan
store the primitive type of data such as int, char, double, float, etc. It also has the capability to
store the collection of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed by using its
index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the
marks of a student in 6 subjects, then we don't need to define different variables for the
marks in the different subject. Instead of that, we can define an array which can store the
marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code arerequired to
access the elements of the array.

Properties of Array
The array contains the following properties.

o Each element of an array is of same data type and carries the same size, i.e., int
= 4 bytes.

o Elements of the array are stored at contiguous memory locations where the firstelement
is stored at the smallest memory location.

o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size ofthe data element.

Advantage of C Array
136
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an arrayeasily.

137
3) Ease of sorting: To sort the elements of the array, we need a few lines of codeonly.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which wewill learn
later.

Declaration of C Array
We can declare an array in the c language in the following way.

1. data_type array_name[array_size];

Now, let us see the example to declare the array.

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

138
C array example

Output

139
C Array: Declaration with
Initialization
We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define. Sth


oeit m
siazyealso be written as the following
code.

int marks[]={20,30,40,50,60};

Let's see the C program to declare and initialize the array in C.

140
C Array Example: Sorting an
array
In the following program, we are using bubble sort method to sort the array i
ascending order.

141
142
C Strings
The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The character array or the string is used to manipulate text such as word orsentences.
Each character in the array occupies one byte of memory, and the last character must
always be 0. The termination character ('\0') is important in a string since it is the only way
to identify where the string ends. When we define a string as char s[10], the character s[10]
is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

1. By char array

2. By string literal

Let's see the example of declaring string by char array in C language.

1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

As we know, array index starts from 0, so it will be represented as in the figure givenbelow.

While declaring string, size is not mandatory. So we can write the above code as givenbelow:

In such case, '\0' will be appended at the end of the string by the compiler.

143
Difference between char array and string literal
There are two main differences between char array and literal.

o We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the characterarray.

o The string literal cannot be reassigned to another set of characters whereas, wecan
reassign the characters of the array.

String Example in C
Let's see a simple example where a string is declared and being printed. The'%s' is
used as a format specifier for the string in c language.

144
Traversing String
Traversing the string is one of the most important aspects in any of the programming
languages. We may need to manipulate a very large text which can be done by traversing
the text. Traversing string is somewhat different from the traversing an integer array. We
need to know the length of the array to traverse an integer array, whereas we may use the
null character in the case of string to identify the end the string and terminate the loop.

Hence, there are two ways to traverse a string.

o By using the length of string

o By using the null character.

Let's discuss each one of them.

Using the length of string


Let's see an example of counting the number of vowels in a string.

145
}

Output

Using the null character


Let's see the same example of counting the number of vowels by using thenull
character.

146
Output

Accepting string as the


input
Till now, we have used scanf to accept the input from the user. However, it can also be us the case of
strings but with a different scenario. Consider the below code which stores the string while space is
147
encountered.

148
It is clear from the output that, the above code will not work for space separated strings. To
make this code working for the space separated strings, the minor changedrequired in the
scanf function, i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which
instructs the compiler to store the string s while the new line (\n) is encountered. Let's
consider the following example to store the space-separated strings.

149
Some important points
However, there are the following points which must be noticed while entering thestrings by
using scanf.

o The compiler doesn't perform bounds checking on the character array. Hence, there can
be a case where the length of the string can exceed the dimension ofthe character array
which may always overwrite some important data.

o Instead of using scanf, we may use gets() which is an inbuilt function defined in a header
file string.h. The gets() is capable of receiving only one string at a time.

150
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far. However pointers
can be used to point to the strings. There are various advantages of using pointe point strings. Let us
consider the following example to access the string via the pointer.

151
As we know that string is an array of characters, the pointers can be used in the same way
they were used with arrays. In the above example, p is declared as a pointer to thearray of
characters s. P affects similar to s since s is the base address of the string and treated as a
pointer internally. However, we can not change the content of s or copy the content of s into
another string directly. For this purpose, we need to use the pointers to store the strings. In
the following example, we have shown the use of pointers to copy the content of a string into
another.

152
Once a string is defined, it cannot be reassigned to another set of characters. However, upointers,
we can assign the set of characters to the string. Consider the following exampl

153
154
C Pointers
The pointer in C language is a variable which stores the address of
another variable. This variable can be of type int, char, array, function, or
any other pointer. The size of the pointer depends onthe architecture.
However, in 32-bit architecture the size of a pointer is 2 byte.

Consider the following example to define a pointer which storesthe


address of an integer.

155
Let's see the pointer example as explained for the above figure.

156
157
Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc()functions


where the pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It reducesthe
code and improves the performance.

Address Of (&) Operator


The address of operator '&' returns the address of a variable. But, we need to use %u to dthe
address of a variable.

158
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't
have any address to be specified in the pointer at the time of declaration, you canassign NULL
value. It will provide a better approach.

Pointer Program to swap two numbers without usingthe 3rd


variable.

159
Output

Reading complex pointers


There are several things which must be taken into the consideration while reading the
complex pointers in C. Lets see the precedence and associativity of the operators whichare
used regarding pointers.

160
C Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the C program. In other words,
we can say that the collection of functions creates a program. The functionis also known as
procedureor subroutinein other programming languages.

Advantage of functions in C
There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in aprogram.

o We can call C functions any number of times in a program and from any place ina
program.

o We can track a large C program easily when it is divided into multiple functions.

o Reusability is the main achievement of C functions.

o However, Function calling is always a overhead in a C program.

Function Aspects
There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to tell the


compiler about the function name, function parameters, and return type.

o Function call Function can be called from anywhere in the program. The parameter
list must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.

o Function definition It contains the actual statements which are to be executed.It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.

161
SN C function Syntax
aspects

1 Function return_type function_name (argumentlist);


declaration

2 Function call function_name (argument_list)

3 Function return_type function_name (argument list)


definition {function body;}

The syntax of creating function in c language is given below:

162
163

You might also like