Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 68

U23CS402 - Object Oriented Programming using C++

Syllabus for Unit 1 - Foundations of C++


Introduction to C++ : features, identifiers, data types, namespace, keywords,
operators, input & output, streams, control statements; arrays; strings; functions:
inline functions, default arguments; references & pointers; dynamic memory
management
Lecture Materials:
Introduction to C++:
1. Features
2. Identifiers
3. Data types
4. Namespace
5. Keywords
6. Operators
7. Input & Output
8. Streams

General Introduction:

 C++ can be found in today's operating systems, Graphical User


Interfaces, and embedded systems.

 C++ is an object-oriented programming language which gives a clear


structure to programs and allows code to be reused, lowering development
costs.

 C++ is portable and can be used to develop applications that can be adapted
to multiple platforms.

C++ is a general-purpose programming language that was developed as an


enhancement of the C language to include object-oriented paradigm. It is an imperative
and a compiled language.

1. C++ is a high-level, general-purpose programming language designed for system


and application programming. It was developed by Bjarne Stroustrup at Bell
Labs in 1983 as an extension of the C programming language. C++ is an object-
oriented, multi-paradigm language that supports procedural, functional, and
generic programming styles.
2. One of the key features of C++ is its ability to support low-level, system-level
programming, making it suitable for developing operating systems, device
drivers, and other system software. At the same time, C++ also provides a rich
set of libraries and features for high-level application programming, making it a
popular choice for developing desktop applications, video games, and other
complex applications.
3. Object-Oriented Programming: C++ supports object-oriented programming,
allowing developers to create classes and objects and to define methods and
properties for these objects.
4. Templates: C++ templates allow developers to write generic code that can work
with any data type, making it easier to write reusable and flexible code.
5. Standard Template Library (STL): The STL provides a wide range of
containers and algorithms for working with data, making it easier to write
efficient and effective code.
6. Exception Handling: C++ provides robust exception handling capabilities,
making it easier to write code that can handle errors and unexpected situations.

Overall, C++ is a powerful and versatile programming language that is widely used
for a range of applications and is well-suited for both low-level system
programming and high-level application development.

Sample C++ code to print Hello World:

#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}

Output:
Hello, World!

Difference between C and C++


C C++

C was developed by Dennis Ritchie


C++ was developed by Bjarne Stroustrup
between the year 1969 and 1973 at
in 1979.
AT&T Bell Labs.

C does no support polymorphism, C++


encapsulation, and inheritance which supports polymorphism, encapsulation
means that C does not support object and inheritance because it is an object
oriented programming. oriented programming language.

C is (mostly) a subset of C++. C++ is (mostly) a superset of C.

C++ is known as hybrid language


For the development of code, C because C++ supports
supports procedural programming. both procedural and object oriented
programming paradigms .

Data and functions are separated in C


Data and functions are encapsulated
because it is a procedural programming
together in form of an object in C++.
language.

Data is hidden by the Encapsulation to


C does not support information hiding. ensure that data structures and operators
are used as intended.

Built-in & user-defined data types is


Built-in data types is supported in C.
supported in C++.

Function and operator overloading is not Function and operator overloading is


supported in C. supported by C++.

C is a function-driven language. C++ is an object-driven language

Functions in C are not defined inside Functions can be used inside a structure
structures. in C++.

Namespace features are not present Namespace is used by C++, which avoid
C C++

inside the C. name collisions.

Standard IO header is stdio.h. Standard IO header is iostream.h.

Virtual and friend functions are not Virtual and friend functions are
supported by C. supported by C++.

C does not support inheritance. C++ supports inheritance.

C
C++ provides new operator for memory
provides malloc() and calloc() functions
allocation and delete operator for
for dynamic memory allocation ,
memory de-allocation.
and free() for memory de-allocation.

Direct support for exception handling is


Exception handling is supported by C++.
not supported by C.

scanf() and printf() functions are used for cin and cout are used for input/output in
input/output in C. C++.

C follows the top-down approach C++ follows the Bottom-up approach

File extension is “.cpp” or “.c++” or


File extension is “.c”
“.cc” or “.cxx”

Feature of C++

 Object-Oriented Programming
 Machine Independent and Platform-Dependent
 Simple
 High-Level Language
 Popular
 Case-sensitive
 Compiler Based
 Dynamic Memory Allocation
 Memory Management
 Multi-threading
 Rich Library

1. Object-Oriented Programming
C++ is an Object-Oriented Programming Language, unlike C which is
a procedural programming language. This is the most important feature of C++. It
can create/destroy objects while programming. Also, it can create blueprints with
which objects can be created.

Concepts of Object-oriented programming Language:


 Class
 Objects
 Encapsulation
 Polymorphism
 Inheritance
 Abstraction

2. Machine Independent and Platform-Dependent


A C++ executable is not platform-independent (compiled programs on Linux
won’t run on Windows), however, they are machine-independent. Let us understand
this feature of C++ with the help of an example. Suppose you have written a piece of
code that can run on Linux/Windows/Mac OSx which makes the C++ Machine
Independent but the executable file of the C++ cannot run on different operating
systems.

3. Simple
It is a simple language in the sense that programs can be broken down into
logical units and parts, has rich library support and has a variety of data types. Also,
the Auto Keyword of C++ makes life easier.
4. High-Level Language
C++ is a High-Level Language, unlike C which is a Mid-Level Programming
Language. It makes life easier to work in C++ as it is a high-level language it is closely
associated with the human-comprehensible English language.

5. Popular
With its support for object-oriented programming, C++ can be a good basis for a
number of other programming languages. C++ is a favorite today for game
development and complex business applications because of its incredibly fast speed
and precise memory management. The language is applied to a variety of different
fields requiring high-performance applications. Adobe products, Unreal Engine, and
popular browsers such as Chrome and Firefox are all built using C++.

6. Case-sensitive
It is clear that C++ is a case-sensitive programming language. For
example, cin is used to take input from the input stream. But if the “Cin” won’t work.
Other languages like HTML and MySQL are not case-sensitive languages.

7. Compiler Based
C++ is a compiler-based language, unlike Python. That is C++ programs used to
be compiled and their executable file is used to run them. C++ is a relatively faster
language than Java and Python.

8. Dynamic Memory Allocation


When the program executes in C++ then the variables are allocated
the dynamical heap space. Inside the functions, the variables are allocated in the stack
space. Many times, we are not aware in advance how much memory is needed to store
particular information in a defined variable and the size of required memory can be
determined at run time.

9. Memory Management
 C++ allows us to allocate the memory of a variable or an array in run time. This is
known as Dynamic Memory Allocation.
 In other programming languages such as Java and Python, the compiler
automatically manages the memories allocated to variables. But this is not the case
in C++.
 In C++, the memory must be de-allocated dynamically allocated memory
manually after it is of no use.
 The allocation and deallocation of the memory can be done using the new and
delete operators respectively.

10. Multi-threading
 Multithreading is a specialized form of multitasking and multitasking is a feature
that allows your system to execute two or more programs concurrently. In
general, there are two sorts of multitasking: process-based and thread-based.
 Process-based multitasking handles the concurrent execution of programs. Thread-
based multitasking deals with the multiprogramming of pieces of an equivalent
program.
 A multithreaded program contains two or more parts that will run concurrently.
Each part of such a program is named a thread, and every thread defines a separate
path of execution.
 C++ doesn’t contain any built-in support for multithreaded applications. Instead, it
relies entirely upon the OS to supply this feature.
11) Rich Library

C++ provides a lot of inbuilt functions that make the development fast. Following are the
sample libraries used in C++ programming:

 <iostream>
 <cmath>
 <cstdlib>
 <fstream>

Identifiers:
In C++ programming language, identifiers are the unique names assigned to variables,
functions, classes, structs, or other entities within the program. For example, in the below
statement,

Ex:
int minutesPerHour = 60;

Here, minutesPerHour is an identifier.

Rules to Name of an Identifier in C++


We can use any word as an identifier as long as it follows the following rules:

1. An identifier can consist of letters (A-Z or a-z), digits (0-9), and underscores (_).
Special characters and spaces are not allowed.
2. An identifier can only begin with a letter or an underscore only.
3. C++ has reserved keywords that cannot be used as identifiers since they have
predefined meanings in the language. For example, int cannot be used as an
identifier as it has already some predefined meaning in C++. Attempting to use these
as identifiers will result in a compilation error.
4. Identifier must be unique in its namespace.
5. Identifier cannot contain whitespaces or special characters like !, #, %, etc.
6. C++ is a case-sensitive language so the identifier such as Num and num are treated
as different.

// C++ program to illustrate the identifiers


#include <iostream>
using namespace std;

// here Car_24 identifier is used to refer the below class


class Car_24 {
string Brand;
string model;
int year;
};

// calculateSum identifier is used to call the below function


void calculateSum(int a, int b)
{
int _sum = a + b;
cout << "The sum is: " << _sum << endl;
}

int main()
{
// identifiers used as variable names
int studentAge = 20;
double accountBalance = 1000.50;
string student_Name = "Karan";

calculateSum(2, 10);

return 0;
}

Output
The sum is: 12

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 they
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 values
to be stored.

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 3 Types:

1. Primitive Data Types: These data types are built-in or predefined data types and can
be used directly by the user to declare variables. example: int, char, float, bool, etc.
Primitive data types available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
 Wide Character

2. Derived Data Types: Derived data types that are derived from the primitive or built-
in datatypes are referred to as Derived Data Types. These can be of four types namely:
 Function
 Array
 Pointer
 Reference

3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are


defined by the user itself. Like, defining a class in C++ or a structure. C++ provides the
following user-defined datatypes:
 Class
 Structure
 Union
 Enumeration
 Typedef defined Datatype

Datatype size is given according to 32 bit OS.


Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 32,767

int 2 byte -32,768 to 32,767

signed int 2 byte -32,768 to 32,767

unsigned int 2 byte 0 to 32,767

short int 2 byte -32,768 to 32,767

signed short int 2 byte -32,768 to 32,767

unsigned short int 2 byte 0 to 32,767

long int 4 byte

signed long int 4 byte

unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 byte


Datatype Modifiers

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

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


Data Type Size (in bytes) Range

unsigned char 1 0 to 255

float 4 -3.4×10^38 to 3.4×10^38

double 8 -1.7×10^308 to1.7×10^308

long double 12 -1.1×10^4932 to1.1×10^4932

wchar_t 2 or 4 1 wide character

// C++ program to Demonstrate the sizes of data types


#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char) << " byte"
<< endl;

cout << "char minimum value: " << CHAR_MIN << endl;

cout << "char maximum value: " << CHAR_MAX << endl;

cout << "Size of int : " << sizeof(int) << " bytes"
<< endl;

cout << "Size of short int : " << sizeof(short int)


<< " bytes" << endl;

cout << "Size of long int : " << sizeof(long int)


<< " bytes" << endl;

cout << "Size of signed long int : "


<< sizeof(signed long int) << " bytes" << endl;

cout << "Size of unsigned long int : "


<< sizeof(unsigned long int) << " bytes" << endl;

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

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


<< " bytes" << endl;

cout << "Size of wchar_t : " << sizeof(wchar_t)


<< " bytes" << endl;
return 0;
}

Output:
Size of char : 1 byte
char minimum value: -128
char maximum value: 127
Size of int : 4 bytes
Size of short int : 2 bytes
Size of long int : 8 bytes
Size of signed long int : 8 bytes
Size of unsigned long int : 8 bytes
Size of float : 4 bytes
Size of double : 8 bytes
Size of wchar_t : 4 bytes

Namespace in C++

 Namespace provide the space where we can define or declare identifier i.e. variable,
method, classes.
 Using namespace, you can define the space or context in which identifiers are
defined i.e. variable, method, classes. In essence, a namespace defines a scope.

Advantage of Namespace to avoid name collision.

 Example, you might be writing some code that has a function called xyz() and
there is another library available which is also having same function xyz(). Now
the compiler has no way of knowing which version of xyz() function you are
referring to within your code.
 A namespace is designed to overcome this difficulty and is used as additional
information to differentiate similar functions, classes, variables etc. with the same
name available in different libraries.
 The best example of namespace scope is the C++ standard library (std) where all the
classes, methods and templates are declared. Hence while writing a C++ program we
usually include the directive using namespace std;

Defining a Namespace:

 A namespace definition begins with the keyword namespace followed by the


namespace name as follows:

namespace namespace_name
{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}

Namespaces in C++ are used to organize too many classes so that it can be easy to handle
the application.

For accessing the class of a namespace, we need to use namespacename::classname. We


can use using keyword so that we don't have to use complete name all the time.

In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.

C++ namespace Example


Let's see the simple example of namespace which include variable and functions.

1. #include <iostream>
2. using namespace std;
3. namespace First {
4. void sayHello() {
5. cout<<"Hello First Namespace"<<endl;
6. }
7. }
8. namespace Second {
9. void sayHello() {
10. cout<<"Hello Second Namespace"<<endl;
11. }
12. }
13. int main()
14. {
15. First::sayHello();
16. Second::sayHello();
17. return 0;
18. }

Output:
Hello First Namespace
Hello Second Namespace

C++ namespace example: by using keyword


Let's see another example of namespace where we are using "using" keyword so that we
don't have to use complete name for accessing a namespace program.

1. #include <iostream>
2. using namespace std;
3. namespace First{
4. void sayHello(){
5. cout << "Hello First Namespace" << endl;
6. }
7. }
8. namespace Second{
9. void sayHello(){
10. cout << "Hello Second Namespace" << endl;
11. }
12. }
13. using namespace First;
14. int main () {
15. sayHello();
16. return 0;
17. }

Output:
Hello First Namespace

Keywords
Keywords(also known as reserved words) have special meanings to the C++
compiler and are always written or typed in short(lower) cases. Keywords are words
that the language uses for a special purpose, such as void, int, public, etc. It can’t be
used for a variable name or function name or any other identifiers. The total count of
reserved keywords is 95. Below is the table for some commonly used C++ keywords.
C++ Keyword

asm double new switch

auto else operator template

break enum private this

case extern protected throw

catch float public try

char for register typedef

class friend return union


C++ Keyword

const goto short unsigned

continue if signed virtual

default inline sizeof void

delete int static volatile

do long struct while


Operators in C++
An operator is a symbol that operates on a value to perform specific mathematical or
logical computations. They form the foundation of any programming language. In C++,
we have built-in operators to provide the required functionality.
An operator operates the operands.

For example,
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
Operators in C++ can be classified into 6 types:

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators

1) Arithmetic Operators

These operators are used to perform arithmetic or mathematical operations on the


operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used for
multiplication, etc.
Arithmetic Operators can be classified into 2 Types:

A) Unary Operators: These operators operate or work with a single operand. For
example: Increment(++) and Decrement(–) Operators.
Name Symbol Description Example

int a = 5;
Increment Increases the integer value of the
++ a++; // returns
Operator variable by one
6

Decrement Decreases the integer value of the int a = 5;



Operator variable by one a–; // returns 4
B) Binary Operators: These operators operate or work with two operands. For
example: Addition(+), Subtraction(-), etc.
Name Symbol Description Example

int a = 3, b = 6;
Addition + Adds two operands int c = a+b; // c =
9

int a = 9, b = 6;
Subtracts second operand from the
Subtraction – int c = a-b; // c =
first
3

int a = 3, b = 6;
Multiplication * Multiplies two operands int c = a*b; // c =
18

int a = 12, b = 6;
Divides first operand by the second
Division / int c = a/b; // c =
operand
2

int a = 8, b = 6;
Modulo Returns the remainder an integer
% int c = a%b; // c
Operation division
=2

Example-1
// Working of increment and decrement operators

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 100, result_a, result_b;

// incrementing a by 1 and storing the result in result_a


result_a = ++a;
cout << "result_a = " << result_a << endl;

// decrementing b by 1 and storing the result in result_b


result_b = --b;
cout << "result_b = " << result_b << endl;

return 0;
}

Output

result_a = 11
result_b = 99

Example-2
// CPP Program to demonstrate the Binary Operators
#include <iostream>
using namespace std;
int main()
{
int a = 8, b = 3;
// Addition operator
cout << "a + b = " << (a + b) << endl;
// Subtraction operator
cout << "a - b = " << (a - b) << endl;
// Multiplication operator
cout << "a * b = " << (a * b) << endl;
// Division operator
cout << "a / b = " << (a / b) << endl;
// Modulo operator
cout << "a % b = " << (a % b) << endl;
return 0;
}
Output
a + b = 11
a-b=5
a * b = 24
a/b=2
a%b=2

2) Relational Operators

These operators are used for the comparison of the values of two operands. For
example, ‘>’ checks if one operand is greater than the other operand or not, etc. The
result returns a Boolean value, i.e., true or false.
Name Symbol Description Example

int a = 3, b =
6;

Is Equal To == Checks if both operands are equal a==b;


// returns
false

int a = 3, b =
6;
Checks if first operand is greater than the a>b;
Greater Than >
second operand
// returns
false

int a = 3, b =
6;
Greater Than or Checks if first operand is greater than or a>=b;
>=
Equal To equal to the second operand
// returns
false

Less Than < Checks if first operand is lesser than the int a = 3, b =
second operand
Name Symbol Description Example

6;
a<b;
// returns
true

int a = 3, b =
6;
Less Than or Checks if first operand is lesser than or a<=b;
<=
Equal To equal to the second operand
// returns
true

int a = 3, b =
6;

Not Equal To != Checks if both operands are not equal a!=b;


// returns
true

Example:
// CPP Program to demonstrate the Relational Operators
#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Equal to operator
cout << "a == b is " << (a == b) << endl;

// Greater than operator


cout << "a > b is " << (a > b) << endl;

// Greater than or Equal to operator


cout << "a >= b is " << (a >= b) << endl;

// Lesser than operator


cout << "a < b is " << (a < b) << endl;

// Lesser than or Equal to operator


cout << "a <= b is " << (a <= b) << endl;

// true
cout << "a != b is " << (a != b) << endl;
return 0;
}

Output
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1

3) Logical Operators

These operators are used to combine two or more conditions or constraints or to


complement the evaluation of the original condition in consideration. The result returns
a Boolean value, i.e., true or false.
Name Symbol Description Example

int a = 3, b =
Logical Returns true only if all the operands are true 6;
&&
AND or non-zero a&&b;
// returns true

int a = 3, b =
Returns true if either of the operands is true 6;
Logical OR ||
or non-zero a||b;
// returns true
Name Symbol Description Example

int a = 3;
Logical !a;
! Returns true if the operand is false or zero
NOT
// returns
false

Example-1:
#include <iostream>
using namespace std;

int main() {
bool result;

result = (3 != 5) && (3 < 5); // true


cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false


cout << "(3 == 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 > 5); // false


cout << "(3 == 5) && (3 > 5) is " << result << endl;

result = (3 != 5) || (3 < 5); // true


cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5); // true


cout << "(3 != 5) || (3 > 5) is " << result << endl;

result = (3 == 5) || (3 > 5); // false


cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2); // true


cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5); // false


cout << "!(5 == 5) is " << result << endl;

return 0;
}
Output:

(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

Example:

// CPP Program to demonstrate the Logical Operators


#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Logical AND operator


cout << "a && b is " << (a && b) << endl;

// Logical OR operator
cout << "a ! b is " << (a > b) << endl;

// Logical NOT operator


cout << "!b is " << (!b) << endl;

return 0;
}

Output
a && b is 1
a ! b is 1
!b is 0
4) Bitwise Operators
These operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be
performed at the bit level for faster processing.

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for
&, |, and ^ are as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

Name Symbol Description Example

Binary AND & Copies a bit to the evaluated result if it int a = 2, b =


exists in both operands 3;
Name Symbol Description Example

(a & b);
//returns 2

int a = 2, b =
Copies a bit to the evaluated result if it 3;
Binary OR |
exists in any of the operand (a | b);
//returns 3

int a = 2, b =
Copies the bit to the evaluated result if it 3;
Binary XOR ^ is present in either of the operands but not
both (a ^ b);
//returns 1

int a = 2, b =
Shifts the value to left by the number of 3;
Left Shift <<
bits specified by the right operand. (a << 1);
//returns 4

int a = 2, b =
Shifts the value to right by the number of 3;
Right Shift >>
bits specified by the right operand. (a >> 1);
//returns 1

int b = 3;
One’s
~ Changes binary digits 1 to 0 and 0 to 1 (~b); //returns
Complement
-4

Note: Only char and int data types can be used with Bitwise Operators.

Example:
// CPP Program to demonstrate the Bitwise Operators
#include <iostream>
using namespace std;
int main()
{
int a = 6, b = 4;

// Binary AND operator


cout << "a & b is " << (a & b) << endl;

// Binary OR operator
cout << "a | b is " << (a | b) << endl;

// Binary XOR operator


cout << "a ^ b is " << (a ^ b) << endl;

// Left Shift operator


cout << "a<<1 is " << (a << 1) << endl;

// Right Shift operator


cout << "a>>1 is " << (a >> 1) << endl;

// One’s Complement operator


cout << "~(a) is " << ~(a) << endl;

return 0;
}

Output:
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7

5) Assignment Operators

These operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator
is a value. The value on the right side must be of the same data type as the variable on
the left side otherwise the compiler will raise an error.
Namemultiply Symbol Description Example

Assignment Assigns the value on the right to the int a = 2;


=
Operator variable on the left // a = 2

First adds the current value of the int a = 2, b


Add and = 4;
variable on left to the value on the right
Assignment +=
and then assigns the result to the a+=b; // a =
Operator
variable on the left 6

First subtracts the value on the right int a = 2, b


Subtract and = 4;
from the current value of the variable on
Assignment -=
left and then assign the result to the a-=b; // a =
Operator
variable on the left -2

First multiplies the current value of the int a = 2, b


Multiply and = 4;
variable on left to the value on the right
Assignment *=
and then assign the result to the variable a*=b; // a =
Operator
on the left 8

First divides the current value of the int a = 4, b


Divide and = 2;
variable on left by the value on the right
Assignment /=
and then assign the result to the variable a /=b; // a =
Operator
on the left 2

Example:
// CPP Program to demonstrate the Assignment Operators
#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Assignment Operator
cout << "a = " << a << endl;
// Add and Assignment Operator
cout << "a += b is " << (a += b) << endl;

// Subtract and Assignment Operator


cout << "a -= b is " << (a -= b) << endl;

// Multiply and Assignment Operator


cout << "a *= b is " << (a *= b) << endl;

// Divide and Assignment Operator


cout << "a /= b is " << (a /= b) << endl;

return 0;
}

Output
a=6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6

6) Ternary or Conditional Operators(?:)

This operator returns the value based on the condition.


Expression1? Expression2: Expression3
The ternary operator ? determines the answer on the basis of the evaluation
of Expression1. If it is true, then Expression2 gets evaluated and is used as the answer
for the expression. If Expression1 is false, then Expression3 gets evaluated and is used
as the answer for the expression.

This operator takes three operands, therefore it is known as a Ternary Operator.


Example:

// CPP Program to demonstrate the Conditional Operators


#include <iostream>
using namespace std;

int main()
{
int a = 3, b = 4;

// Conditional Operator
int result = (a < b) ? b : a;
cout << "The greatest number is " << result << endl;

return 0;
}

Output
The greatest number is 4

7) There are some other common operators available in C++ besides the operators
discussed above. Following is a list of these operators discussed in detail:
A) sizeof Operator: This unary operator is used to compute the size of its operand or
variable.
sizeof(char); // returns 1
B) Comma Operator(,): This binary operator (represented by the token) is used to
evaluate its first operand and discards the result, it then evaluates the second operand
and returns this value (and type). It is used to combine various expressions together.
int a = 6;
int b = (a+1, a-2, a+5); // b = 11
C) -> Operator: This operator is used to access the variables of classes or structures.
cout<<emp->first_name;
D) Cast Operator: This unary operator is used to convert one data type into another.
float a = 11.567;
int c = (int) a; // returns 11
E) Dot Operator(.): This operator is used to access members of structure variables or
class objects in C++.
cout<<emp.first_name;
F) & Operator: This is a pointer operator and is used to represent the memory address
of an operand.
G) * Operator: This is an Indirection Operator
H) << Operator: It is called the insertion operator. It is used with cout to print the
output.
I) >> Operator: It is called the extraction operator. It is used with cin to get the input.
Operator Precedence Chart

Precedenc
e Operator Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript)

1. . Member selection via object name

-> Member selection via a pointer

++/– Postfix increment/decrement

2. ++/– Prefix increment/decrement right-to-left

+/- Unary plus/minus

!~ Logical negation/bitwise complement

Cast (convert value to temporary value of


(type)
type)

* Dereference

& Address (of operand)


Precedenc
e Operator Description Associativity

Determine size in bytes on this


sizeof
implementation

3. *,/,% Multiplication/division/modulus left-to-right

4. +/- Addition/subtraction left-to-right

5. << , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right

6.
Relational greater than/greater than or equal
> , >= left-to-right
to

7. == , != Relational is equal to/is not equal to left-to-right

8. & Bitwise AND left-to-right

9. ^ Bitwise exclusive OR left-to-right

10. | Bitwise inclusive OR left-to-right

11. && Logical AND left-to-right

12. || Logical OR left-to-right


Precedenc
e Operator Description Associativity

13. ?: Ternary conditional right-to-left

= Assignment right-to-left

+= , -= Addition/subtraction assignment

*= , /= Multiplication/division assignment
14.
%= , &= Modulus/bitwise AND assignment

^= , |= Bitwise exclusive/inclusive OR assignment

<>= Bitwise shift left/right assignment

15. , expression separator left-to-right

Input and Output Streams in C++


C++ comes with libraries that provide us with many ways for performing input and
output. In C++ input and output are performed in the form of a sequence of bytes or
more commonly known as streams.

 Input Stream: If the direction of flow of bytes is from the device (for example,
Keyboard) to the main memory then this process is called input.

 Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory
to device (display screen) then this process is called output.

Header files available in C++ for Input/Output operations are:


1. iostream: iostream stands for standard input-output stream. This header file contains
definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods declared in
these files are used for manipulating streams. This file contains definitions of setw,
setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is used to
handle the data being read from a file as input or data being written into the file as
output.
4. bits/stdc++: This header file includes every standard library.

In C++ after the header files, we often use ‘using namespace std;‘. The reason behind it
is that all of the standard library definitions are inside the namespace std. As the library
functions are not defined at global scope, so in order to use them we use namespace std.
So, that we don’t need to write STD:: at every line (eg. STD::cout etc.).

The two instances cout in C++ and cin in C++ of iostream class are used very often
for printing outputs and taking inputs respectively.

Standard output stream (cout): Usually the standard output device is the display
screen. The C++ cout statement is the instance of the ostream class. It is used to
produce output on the standard output device which is usually the display screen. The
data needed to be displayed on the screen is inserted in the standard output stream
(cout) using the insertion operator(<<).

Standard input stream (cin): Usually the input device in a computer is the keyboard.
C++ cin statement is the instance of the class istream and is used to read input from the
standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The
extraction operator extracts the data from the object cin which is entered using the
keyboard.

Example:
#include <iostream>
using namespace std;
int main()
{ int age;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
return 0;
}
Output:
Enter your age: 18
Your age is: 18

Un-buffered standard error stream (cerr): The C++ cerr is the standard error stream
that is used to output the errors. This is also an instance of the iostream class. As cerr in
C++ is un-buffered so it is used when one needs to display the error message
immediately. It does not have any buffer to store the error message and display it later.

Buffered standard error stream (clog): This is also an instance of ostream class and
used to display errors but unlike cerr the error is first inserted into a buffer and is stored
in the buffer until it is not fully filled. or the buffer is not explicitly flushed (using
flush()). The error message will be displayed on the screen too.

Example:
#include <iostream>
using namespace std;
int main() {
int first_number, second_number, sum;
cout << "Enter two integers: ";
cin >> first_number >> second_number;
sum = first_number + second_number;
cout << first_number << " + " << second_number << " = " << sum;
return 0;
}

Output:
Enter two integers: 4
5
4+5=9
Control statements
1. Conditional Control Structures (Decision making statements)
 if
 if – else Statements
 Swtich Case Statments
2. Looping / Iterative Control Structures
 For Loop
 While Loop
 Do…..While Loop
3. Functions

Apart from these we have certain Jump Statements in C++ which assist in manipulating
the flow of the program execution. Following are those statements –

 The break statement


 The continue statement
 The goto statement
 return statement

Conditional Statements:
Conditional Statements are used in C++ to run a certain piece of program only if a
specific condition is met. There are generally three types of conditional statements
in C++: if, if-else, and switch.
if Statement:
The if statement is the simplest of the three and is used to run a certain piece of
code only if a certain condition is true. For example:

Syntax of if statement in c++


if(condition)
{
//code should be executed;
}

Example:
#include <iostream>
using namespace std;
int main () {
int number = 10;
if (number % 2 == 0)
{
cout << "The Number you have Enter it is Even";
}
return 0;
}

Output:
The Number you have Enter it is Even

If…else statement
The statement C++ if-else also checks the condition. The declaration executes if
the condition is true otherwise the block is carried out.

Syntax of the if-else statement in c++

if(condition)
{
//code should be executed;
}else
{
//code should be executed;
}
Example of if-else Statement

#include<iostream>
using namespace std;
int main () {
int number = 15;
if (number % 2 == 0)
{
cout << "The Number you have Enter it is Even";
}
else
{
cout << "The Number you have Enter it is Odd";
}
return 0;
}

Output:
The Number you have Enter it is Odd

If-else-if ladder statement


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

Syntax of if-else ladder statement

If(condition1)
{
// code should be executed if condition1 is true
}
else if(condition2)
{
// code should be executed if condition2 is true
}
else if(condition3)
{
// code should be executed if condition3 is true
}
...
else{
// code should be executed if all condition is false
}
Example:
#include <iostream>
using namespace std;
int main () {
int number;
cout << "To Check Grade Enter a Number:";
cin >> number;
if (number < 0 || number > 100)
{
cout << "wrong No";
}
else if(number >= 0 && number < 40){
cout << "Fail";
}
else if (number >= 40 && number < 59)
{
cout << "D Grade";
}
else if (number >= 60 && number < 70)
{
cout <<" C Grade";
}
else if (number >= 71 && number < 79)
{
cout << "B Grade";
}
else if (number >= 80 && number < 89)
{
cout << "A Grade";
}
else if (number >= 90 && number <= 100)
{
cout << "A+ Grade";
} }
Output:
To Check Grade Enter a Number: 75
B Grade

C++ Switch Statement


From the multiple conditions, a C++ Switch statement executes a single statement. It’s
like a ladder statement if-else-if in C++.
Syntax of C++ Switch statement

Switch(expression)
{
case value1:
//code should be executed;
break;
case value2:
//code should be executed;
break;

Default:
//Code to execute if not all cases matched
break;
}

Example of C++ Switch Statement


#include<iostream>
using namespace std;
int main () {
int number;
cout << "To check the grade enter a number:";
cin >> number;
switch (number)
{
case 2: cout << "It is 2"; break;
case 3: cout << "It is 3"; break;
case 4: cout << "It is 4"; break;
default: cout << "Not 2, 3 or 4"; break;
}
}
Looping:
In Loop, the statement needs to be written only once and the loop
will be executed N- times. 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.

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

Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}

Example:
using namespace std;

int main()
{
int i = 99;
for (int i = 0; i < 5; i++) {
cout << i << "\t";
}
cout << "\n" << i;
return 0;
}

Output:
0 1 2 3 4
99

While Loop:
In for loop 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:
initialization expression;
while (test_expression)
{
// statements

update_expression;
}

Example:
// C++ program to Demonstrate while loop
#include <iostream>
using namespace std;

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

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

// update expression
i++;
}

return 0;
}

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

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 tested at 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);

Example:

// C++ program to Demonstrate do-while loop


#include <iostream>
using namespace std;

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

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

// update expression
i++;

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

return 0;
}

Output:
Hello World

Jump Statement:
Jump statements are used to manipulate the flow of the program if some conditions are
met. It is used to terminate or continue the loop inside a program or to stop the execution
of a function.

Types of Jump Statements in C++


In C++, there is four jump statement
1. break
2. continue
3. goto
4. return
continue in C++
The C++ continue statement is used to execute other parts of the loop while skipping
some parts declared inside the condition, rather than terminating the loop, it
continues to execute the next iteration of the same loop. It is used with a
decision-making statement which must be present inside the loop.

This statement can be used inside for loop or while or do-while loop.

Syntax:
continue;

Example:

// C++ program to demonstrate the


// continue statement
#include <iostream>
using namespace std;

// Driver code
int main()
{
for (int i = 1; i < 10; i++) {

if (i == 5)
continue;
cout << i << " ";
}
return 0;
}

Output
12346789

break in C++

The C++ break statement is used to terminate the whole loop if the condition is met.
Unlike the continue statement after the condition is met, it breaks the loop and the
remaining part of the loop is not executed.
Break statement forces the loop to stop the execution of the further
iteration.
Syntax:
break;

Example:
// C++ program to demonstrate the
// break statement
#include <iostream>
using namespace std;

// Driver Code
int main()
{
for (int i = 1; i < 10; i++) {

// Breaking Condition
if (i == 5)
break;
cout << i << " ";
}
return 0;
}

Output:
1234

return in C++
The return statement takes control out of the function itself. It is stronger than a break.
It is used to terminate the entire function after the execution of the function or after
some condition.

Syntax
return expression;

Example:

// C++ program to demonstrate the


// return statement
#include <iostream>
using namespace std;
// Driver code
int main()
{
cout << "Begin ";

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

// Termination condition
if (i == 5)
return 0;
cout << i << " ";
}
cout << "end";

return 0;
}

Output:
Begin 0 1 2 3 4

Explanation:
The above program starts execution by printing “Begin” and then the for loop starts to
print the value of, it will print the value of i from 0 to 4 but as soon as i becomes equal
to 5 it will terminate the whole function i.e., it will never go to print the “end” statement
of the program.

Goto statement in C++


The C++ goto statement is used to jump directly to that part of the program to which it
is being called. Every goto statement is associated with the label which takes them to
part of the program for which they are called. The label statements can be written
anywhere in the program it is not necessary to use them before or after
the goto statement.

Syntax

goto label_name;
.
.
.
label_name:
Example:
// C++ program to demonstrate the
// goto statement
#include <iostream>
using namespace std;

// Driver Code
int main()
{
int n = 4;

if (n % 2 == 0)
goto label1;
else
goto label2;

label1:
cout << "Even" << endl;
return 0;

label2:
cout << "Odd" << endl;
}

Output
Even
Arrays
Array is a group of similar types of elements that have contiguous or adjacent
memory location.
A collection of related data items stored in adjacent memory places is referred to as
an array. Elements of an array can be accessed arbitrarily using its indices. They
can be used to store a collection of any type of primitive data type, including int,
float, double, char, etc. An array in C/C++ can also store derived data types like
structures, pointers, and other data types, which is an addition.

Array Types
There are 2 types of arrays in C++ programming:

1. Single Dimensional Array


2. Multidimensional Array

Initialization of Array in C++


int arr[5] = {1, 2, 3, 4, 5};
int arr[] = {1, 2, 3, 4, 5};

Initialize Array after Declaration (Using Loops)


for (int i = 0; i < N; i++) {
arr[i] = value;
}

Single Dimensional Array


Example-1
using namespace std;

int main()
{

int arr[3];

// Inserting elements in an array


arr[0] = 10;
arr[1] = 20;
arr[2] = 30;

// Accessing and printing elements of the array


cout << "arr[0]: " << arr[0] << endl;
cout << "arr[1]: " << arr[1] << endl;
cout << "arr[2]: " << arr[2] << endl;

return 0;
}

Output
arr[0]: 10
arr[1]: 20
arr[2]: 30

Example-2
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i = 0; i < 5; i++)
8. {
9. cout<<arr[i]<<"\n";
10. }
11. }

Output:

10
0
20
0
30

C++ Array Example: Traversal using foreach loop


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

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
6. //traversing array
7. for (int i: arr)
8. {
9. cout<<i<<"\n";
10. }
11. }

Output:
10
20
30
40
50

Two Dimensional or Multi-Dimensional Array


A two-dimensional array in C++ is the simplest form of a multi-dimensional
array. It can be visualized as an array of arrays.

Initializing a 2D array in C++


int arr[4][2] = {
{1234, 56},
{1212, 33},
{1434, 80},
{1312, 78}
};

So, as you can see, we initialize a 2D array arr, with 4 rows and 2 columns as an
array of arrays. Each element of the array is yet again an array of integers.

We can also initialize a 2D array in the following way.

int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78};

Example-1:

#include<iostream>
using namespace std;
main( )
{
int arr[4][2] = {
{ 10, 11 },
{ 20, 21 },
{ 30, 31 },
{ 40, 41 }
};

int i,j;

cout<<"Printing a 2D Array:\n";
for(i=0;i<4;i++)
{
for(j=0;j<2;j++)
{
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
}

Output:
Taking 2D Array Elements As User Input
#include<iostream>
using namespace std;
main( )
{
int s[2][2];
int i, j;
cout<<"\n2D Array Input:\n";
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"\ns["<<i<<"]["<<j<<"]= ";
cin>>s[i][j];
}
}

cout<<"\nThe 2-D Array is:\n";


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"\t"<<s[i][j];
}
cout<<endl;
}
}

Output:
Example: Matrix Addition using Two Dimensional
Arrays in C++
#include<iostream>
using namespace std;
main()
{
int m1[5][5], m2[5][5], m3[5][5];
int i, j, r, c;

cout<<"Enter the no.of rows of the matrices to be added(max 5):";


cin>>r;
cout<<"Enter the no.of columns of the matrices to be added(max 5):";
cin>>c;

cout<<"\n1st Matrix Input:\n";


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<"\nmatrix1["<<i<<"]["<<j<<"]= ";
cin>>m1[i][j];
}
}

cout<<"\n2nd Matrix Input:\n";


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<"\nmatrix2["<<i<<"]["<<j<<"]= ";
cin>>m2[i][j];
}
}

cout<<"\nAdding Matrices...\n";

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
m3[i][j]=m1[i][j]+m2[i][j];
}
}

cout<<"\nThe resultant Matrix is:\n";

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<"\t"<<m3[i][j];
}
cout<<endl;
}

Output:
Strings
C++ strings are sequences of characters stored in a char array. Strings are used to store
words and text. They are also used to store data, such as numbers and other types of
information. Strings in C++ can be defined either using the std::string class or the
C-style character arrays.

1. C Style Strings

These strings are stored as the plain old array of characters terminated by a null
character ‘\0’. They are the type of strings that C++ inherited from C language.
Syntax:
char str[] = "GeeksforGeeks";

Example 1:
// C++ Program to demonstrate strings
#include <iostream>
using namespace std;

int main()
{

char s[] = "GeeksforGeeks";


cout << s << endl;
return 0;
}
Output:
GeeksforGeeks

2. std::string Class

These are the new types of strings that are introduced in C++ as std::string class defined
inside <string> header file. This provides many advantages over conventional C-style
strings such as dynamic size, member functions, etc.
Syntax:
std::string str("GeeksforGeeks");

Ways to Define a String in C++


1. string s = "GeeksforGeeks";
2. string s("GeeksforGeeks");
3. char s[] = {'g', 'f', 'g', '\0'};
4. char s[4] = {'g', 'f', 'g', '\0'};
5. char s[4] = "gfg";
6. char s[] = "gfg";

Example:
// C++ program to create std::string objects
#include <iostream>
using namespace std;

int main()
{

string str("GeeksforGeeks");
cout << str;
return 0;
}

Output:
GeeksforGeeks
How to Take String Input in C++
String input means accepting a string from a user. In C++. We have different types of
taking input from the user which depend on the string. The most common way is to take
input with cin keyword with the extraction operator (>>) in C++. Methods to take a
string as input are:
 cin
 getline
 stringstream

1. Using Cin

Example:
// C++ Program to demonstrate string input using cin
#include <iostream>
using namespace std;

int main() {

string s;

cout<<"Enter String"<<endl;
cin>>s;

cout<<"String is: "<<s<<endl;


return 0;
}

Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks

2. Using getline

The getline() function in C++ is used to read a string from an input stream. It is
declared in the <string> header file.
Syntax:
getline(cin,s);

Example:
// C++ Program to demonstrate use of getline function
#include <iostream>
using namespace std;

int main()
{

string s;
cout << "Enter String" << endl;
getline(cin, s);
cout << "String is: " << s << endl;
return 0;
}

Output:
Enter String
GeeksforGeeks
String is: GeeksforGeeks

3. Using stringstream

The stringstream class in C++ is used to take multiple strings as input at once.
Syntax:
stringstream stringstream_object(string_name);
Example:

// C++ Program to demonstrate use of stringstream object


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

using namespace std;

int main()
{
string s = " GeeksforGeeks to the Moon ";
stringstream obj(s);
// string to store words individually
string temp;
// >> operator will read from the stringstream object
while (obj >> temp) {
cout << temp << endl;
}
return 0;
}

Output:
GeeksforGeeks
to
the
Moon

Commonly Used String Functions in C++


The std::string class contains functions to provide some common string operations. The
below table contains some of the most commonly used functions in C++:

S. Functions and
No. Category Operators Functionality

It will return the length of


1. length() or size()
String Length the string.

To access individual
Indexing (using
characters using array
array[index])
indexing.

Accessing Used to access a character


2. at()
Characters at a specified index.

3. Appending and + Operator + operator is used to


concatenate two strings.
S. Functions and
No. Category Operators Functionality

The append() function adds


Concatenating append() one string to the end of
Strings another.

You can compare strings


== Operator
using the == operator.

The compare() function


returns an integer value
compare()
String indicating the comparison
4.
Comparison result.

Use the substr() function to


substr() extract a substring from a
5.
Substrings string.

The find() function returns


find() the position of the first
6.
Searching occurrence of a substring.

Use the replace() function


replace() to modify a part of the
string.

The insert() function adds a


insert() substring at a specified
position.

Use the erase() function to


7. erase()
Modifying Strings remove a part of the string.

To obtain a C-style string


c_str() from a std::string, you can
8.
Conversion use the c_str() function.

9 String Copy strcpy(Destination, Source);


S. Functions and
No. Category Operators Functionality

10 strcat(Str1, Str2);
String Concat

Example-1: - String Compare


1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main ()
5. {
6. char key[] = "mango";
7. char buffer[50];
8. do {
9. cout<<"What is my favourite fruit? ";
10. cin>>buffer;
11. } while (strcmp (key,buffer) != 0);
12. cout<<"Answer is correct!!"<<endl;
13. return 0;
14. }

Output:
What is my favourite fruit? apple
What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!

Example-2: - String Concat


1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char key[25], buffer[25];
7. cout << "Enter the key string: ";
8. cin.getline(key, 25);
9. cout << "Enter the buffer string: ";
10. cin.getline(buffer, 25);
11. strcat(key, buffer);
12. cout << "Key = " << key << endl;
13. cout << "Buffer = " << buffer<<endl;
14. return 0;
15. }

Output:
Enter the key string: Welcome to
Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.

Example-3: - String Copy


1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char key[25], buffer[25];
7. cout << "Enter the key string: ";
8. cin.getline(key, 25);
9. strcpy(buffer, key);
10. cout << "Key = "<< key << endl;
11. cout << "Buffer = "<< buffer<<endl;
12. return 0;
13. }

Output:
Enter the key string: C++ Tutorial
Key = C++ Tutorial
Buffer = C++ Tutorial

Example-4: - String Length


1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. int main()
5. {
6. char ary[] = "Welcome to C++ Programming";
7. cout << "Length of String = " << strlen(ary)<<endl;
8. return 0;
9. }

Output:
Length of String = 26

You might also like