Empty File
Empty File
Basics
1. Setting up C++Development Environment
Windows Installation: There are lots of IDE available for windows operating system which you can
use to work easily with C++ programming language. One of the popular IDE is Code::Blocks. To
download Code::Blocks you may visit this link. Once you have downloaded the setup file of
Code::Blocks from the given link open it and follow the instruction to install.
1. After successfully installing Code::Blocks, go to File menu -> Select New and create an
Empty file.
2. Now write your C++ program in this empty file and save the file with a ‘.cpp’ extension.
3. After saving the file with ‘.cpp’ extension, go to Build menu and choose the Build and
Run option.
2. Writing first C++ program(Practice)
C++ is a widely used Object Oriented Programming language and is fairly easy to understand.
Learning C++ programming can be simplified into:
Writing your program in a text editor and saving it with correct extension(.CPP, .C, .CP)
Output
Hello World
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. Click to know More about Comments.
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. Click to Know More on
Preprocessors.
3) using namespace std: This is used to import the entirety of the std namespace into the current
namespace of the program. The statement using namespace std is generally considered a bad practice.
When we import a namespace we are essentially pulling all type definitions into the current scope. The
std namespace is huge. The alternative to this statement is to specify the namespace to which the
identifier belongs using the scope operator(::) each time we declare a type. Click to know More about
using namespace std.
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. Click to know More about the 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) std::cout<<“Hello World”;: This line tells the compiler to display the message “Hello World” on the
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. The std::cout is used to identify the standard character output device
which is usually the desktop screen. Everything followed by the character “<<” is displayed to the output
device. Click to know More on Input/Output.
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 does not 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.
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. It is a good practice to use Indentation and comments in programs for easy understanding.
4. cout is used to print statements and cin is used to take inputs.
3. void main or main()
in C++ the default return type of main is void, i.e. main() will not return anything. But, in C default return
type of main is int, i.e. main() will return an integer value by default.
In C, void main() has no defined(legit) usage, and it can sometimes throw garbage results or an error.
However, main() is used to denote the main function which takes no arguments and returns an integer
data type.
To summarize the above, it is never a good idea to use void main() or simply, main() as it doesn’t
confirm standards. It may be allowed by some compilers though.
4. C++ Data Types(Practice)
Variables in C++
A variable is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
In C++, all the variables must be declared before use.
Rules For Declaring Variable:
1.The name of the variable contain letters, digits, and underscores.
2.The name of the variable are case sensitive (ex Arr and arr both are different variable).
3.The name of the variable does not contain any whitespace and special characters (ex #,$,%,* etc).
4.All the variable name must begin with a letter of the alphabet or an underscore(_).
5.We cannot used C++ keyword(ex float,double,class)as a variable name.
How to declare variables?
A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;
// Declaring multiple variables:
type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers and the underscore ‘_’
character. However, the name must not start with a number.
Difference between variable declaration and definition
The variable declaration refers to the part where a variable is first declared or introduced before its first
use. A variable definition is a part where the variable is assigned a memory location and a value. Most of
the time, variable declaration and definition are done together.
Types of variables
There are three types of variables based on the scope of variables in C++ :
Local Variables
A variable defined within a block or method or constructor is called a local variable.
These variables are created when entered into the block or the function is called and
destroyed after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is declared. i.e.
we can access this variable only within that block.
Initialization of Local Variable is Mandatory
Instance Variables
Instance variables are non-static variables and are declared in a class outside any method, constructor or
block.
As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
Initialization of Instance Variable is not Mandatory.
Instance Variable can be accessed only by creating objects.
1. Static VariablesStatic variables are also known as Class variables.
These variables are declared similarly as instance variables, the difference is that
static variables are declared using the static keyword within a class outside any
method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
Static variables are created at the start of program execution and destroyed
automatically when execution ends.
Initialization of Static Variable is not Mandatory. Its default value is 0
If we access the static variable like the Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The
compiler will replace the object name with the class name automatically.
If we access the static variable without the class name, the Compiler will
automatically append the class name.
Instance variable Vs Static variable
Each object will have its own copy of the instance variable whereas We can only have one
copy of a static variable per class irrespective of how many objects we create.
Changes made in an instance variable using one object will not be reflected in other objects
as each object has its own copy of the instance variable. In the case of static, changes will be
reflected in other objects as static variables are common to all objects of a class.
We can access instance
variables through object
references and Static Variables can be
accessed directly using the class
name.
Syntax for static and instance variables:
class Example
{
static int a; // static variable
int b; // instance variable
}
Instance variable Vs Static variable
Each object will have its own copy of the
instance variable whereas We can only have one copy of a static variable per class
irrespective of how many objects we create.
Changes made in an instance variable using one object will not be reflected in other objects
as each object has its own copy of the instance variable. In the case of static, changes will be
reflected in other objects as static variables are common to all objects of a class.
We can access instance variables through object references and Static Variables can be
accessed directly using the class name.
Syntax for static and instance variables:
class Example
{
static int a; // static variable
int b; // instance variable
}
Scope of Variables in C++
In general, the scope is defined as the extent up to which something can be worked with. In programming
also the scope of a variable is defined as the extent of the program code within which the variable can be
accessed or declared or worked with. There are mainly two types of variable scopes:
1. Local Variables
Variables defined within a function or block are said to be local to those functions.
Anything between ‘{‘ and ‘}’ is said to inside a block.
Local variables do not exist outside the block in which they are declared, i.e. they can not be
accessed or used outside that block.
Declaring local variables: Local variables are declared inside a block.
2. Global Variables
As the name suggests, Global Variables can be accessed from any part of the program.
They are available through out the life time of a program.
They are declared at the top of the program outside all of the functions or blocks.
Declaring global variables: Global variables are usually declared outside of all of the
functions and blocks, at the top of the program. They can be accessed from any portion of the
program.
Scope resolution operator in C++
In C++, scope resolution operator is ::. It is used for following purposes.
1) To access a global variable when there is a local variable with same name:
// C++ program to show that we can access a global variable
// using scope resolution operator :: when there is a local
// variable with same name
#include<iostream>
using namespace std;
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
2) To define a function outside a class.
Output:
Value of static x is 1
Value of local x is 3
Test::y = 2;
Output:
A's x is 10
B's x is 20
5) For namespace
If a class having the same name exists inside two namespace we can use the namespace name with the
scope resolution operator to refer that class without any conflicts
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
Float 4
Double 8
long double 12
Data Type Size (in bytes) Range
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.
Macro Constants
Name
Expresses
CHAR_MIN :Minimum value for an object of type char
CHAR_MAX :Maximum value for an object of type char
SCHAR_MIN :Minimum value for an object of type Signed char
SCHAR_MAX : Maximum value for an object of type Signed char
UCHAR_MAX :Maximum value for an object of type Unsigned char
CHAR_BIT :Number of bits in a char object
MB_LEN_MAX :Maximum number of bytes in a multi-byte character
SHRT_MIN :Minimum value for an object of type short int
SHRT_MAX :Maximum value for an object of type short int
USHRT_MAX :Maximum value for an object of type Unsigned short int
INT_MIN : Minimum value for an object of type int
INT_MAX :Maximum value for an object of type int
UINT_MAX :Maximum value for an object of type Unsigned int
LONG_MIN :Minimum value for an object of type long int
LONG_MAX :Maximum value for an object of type long int
ULONG_MAX : Maximum value for an object of type Unsigned long int
LLONG_MIN : Minimum value for an object of type long long int
LLONG_MAX : Maximum value for an object of type long long int
ULLONG_MAX :Maximum value for an object of type Unsigned long long int
2. Derived Data Types: The data types that are derived from the primitive or built-in datatypes are
referred to as Derived Data Types. These can be of four types namely:
Function
A function is a block of code or program-segment that is defined to perform a specific well-defined task. A
function is generally defined to save the user from writing the same lines of code again and again for the
same input. All the lines of code are put together inside a single function and this can be called anywhere
required. main() is a default function that is defined in every program of C++.
Syntax:
FunctionType FunctionName(parameters)
Array
An array is a collection of items stored at continuous memory locations. The idea of array is to represent
many instances in one variable.
Syntax:
DataType ArrayName[size_of_array];
Pointer
Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference
as well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the
format:
Syntax:
datatype *var_name;
Reference
When a variable is declared as reference, it becomes an alternative name for an existing variable. A
variable can be declared as reference by putting ‘&’ in the declaration.
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
The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data
type, which holds its own data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.
Syntax:
Structure
A structure is a user defined data type in C/C++. A structure creates a data type that can be used to
group items of possibly different types into a single type.
Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Union
Like Structures, union is a user defined data type. In union, all members share the same memory
location. For example in the following C program, both x and y share the same location. If we change x,
we can see the changes being reflected in y.
Ex: // Declaration of union is same as the structures
union test {
int x, y;
};
Enumeration
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};
Typedef defined Datatype
C++ allows you to define explicitly new data type names by using the keyword typedef. Using typedef
does not actually create a new data class, rather it defines a name for an existing type. This can increase
the portability(the ability of a program to be used across different types of machines; i.e., mini,
mainframe, micro, etc; without much changes into the code)of a program as only the typedef statements
would have to be changed. Using typedef one can also aid in self-documenting code by allowing
descriptive names for the standard data types.
Syntax:
typedef type name;
where type is any C++ data type and name is the new name for this data type.
This defines another name for the standard type of C++.
5. Basic Input/Output
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.
It is a manipulator. It is a character.
It is a keyword and would not specify any It can be stored in a string and will still convey its
meaning when stored in a string. specific meaning of line break.
We cannot write ‘endl’ in between double We can write ‘\n’ in between double quotations like
quotations. cout<<“\n”;
It keeps flushing the queue in the output buffer It flushes the output buffer only once at the end of
throughout the process. the program
Note: cout << “\n” looks performance wise better but in real cout << endl is much better in C++; As it
doesn’t occupies any memory and also if flushing of stream is required.
Problem With Using fgets()/gets()/scanf() After scanf() in C
scanf() is a library function in C. It reads standard input from stdin. fgets() is a library function in C. It
reads a line from the specified stream and stores it into the string pointed to by the string variable. It only
terminates when either:
end-of-file is reached
n-1 characters are read
the newline character is read
Explanation: We can notice that the above program prints an extra “Enter a character” followed by an
extra newline. This happens because every scanf() leaves a newline character in a buffer that is read by
the next scanf.
How to Solve the Above Problem?
We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In
fact scanf(“%d “, &x) also works (Note the extra space).
We can add a getchar() after scanf() to read an extra newline.
How to use getline() in C++ when there are blank lines in input?
In C++, if we need to read a few sentences from a stream, the generally preferred way is to use
the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided
by the user. Also, it uses <string.h> header file to be fully functional.
6. Response on exceeding valid range of data types
Explanation: We know that the computer uses 2’s complement to represent data. For example, if we
have 1 byte (We can use char and use %d as a format specifier to view it as a decimal), we can
represent -128 to 127. If we add 1 to 127 we will get -128. That’s because 127 is 01111111 in binary.
And if we add 1 into 01111111 we will get 10000000. 10000000 is -128 in 2’s complement form. The
same will happen if we use unsigned integers. 255 is 11111111 when we add 1 to 11111111 we will get
100000000. But we are using only the first 8 bits, so that’s 0. Hence we get 0 after adding 1 in 255.
7. C++ Preprocessors
Preprocessors are programs that process our source code before compilation. There are a number of
steps involved between writing a program and executing a program in C / C++. Let us have a look at
these steps before we actually start learning about Preprocessors.
You can see the intermediate steps in the above diagram. The source code written by programmers is
first stored in a file, let the name be “program.c“. This file is then processed by preprocessors and an
expanded source code file is generated named “program.i”. This expanded file is compiled by the
compiler and an object code file is generated named “program.obj”. Finally, the linker links this object
code file to the object code of the library functions to generate the executable file “program.exe”.
Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source
code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol
indicates that whatever statement starts with a ‘#’ will go to the preprocessor program to get executed.
Examples of some preprocessor directives are: #include, #define, #ifndef etc. Remember that
the # symbol only provides a path to the preprocessor, and a command such as include is processed by
the preprocessor program. For example, #include will include extra code in your program. We can place
these preprocessor directives anywhere in our program.
There are 4 Main Types of Preprocessor Directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
Let us now learn about each of these directives in detail.
1. Macros
Macros are pieces of code in a program that is given some name. Whenever this name is encountered by
the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used
to define a macro.
Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a semi-
colon to end.
2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program. There
are two types of files that can be included by the user in the program:
Header files or Standard files: These files contain definitions of pre-defined functions like printf(),
scanf(), etc. These files must be included to work with these functions. Different functions are declared in
different header files. For example, standard I/O functions are in the ‘iostream’ file whereas functions that
perform string operations are in the ‘string’ file.
Syntax:
#include< file_name >
where file_name is the name of the file to be included. The ‘<‘ and ‘>’ brackets tell the compiler to look for
the file in the standard directory.
User-defined files: When a program becomes very large, it is a good practice to divide it into smaller
files and include them whenever needed. These types of files are user-defined files. These files can be
included as:
#include"filename"
3. Conditional Compilation
Conditional Compilation directives are a type of directive that helps to compile a specific portion of the
program or to skip the compilation of some specific part of the program based on some conditions. This
can be done with the help of the two preprocessing commands ‘ifdef‘ and ‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute normally,
but if it is not defined, the compiler will simply skip this block of statements.
4. Other Directives
Apart from the above directives, there are two more directives that are not commonly used. These are:
#undef Directive: The #undef directive is used to undefine an existing macro. This directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT”
statement will evaluate as false.
#pragma Directive: This directive is a special purpose directive and is used to turn on or off some
features. This type of directives are compiler-specific, i.e., they vary from compiler to compiler. Some of
the #pragma directives are discussed below:
#pragma startup and #pragma exit: These directives help us to specify the functions that are
needed to run before program startup (before the control passes to main()) and just before
program exit (just before the control returns from main()).
#pragma warn Directive: This directive is used to hide the warning message which is displayed during
compilation. We can hide the warnings as shown below:
#pragma warn -rvl: This directive hides those warnings which are raised when a function that
is supposed to return a value does not return a value.
#pragma warn -par: This directive hides those warnings which are raised when a function
does not use the parameters passed to it.
#pragma warn -rch: This directive hides those warnings which are raised when a code is
unreachable. For example, any code written after the return statement in a function is
unreachable.
8. Operators in C++(Practice)
Operators are the foundation of any programming language. We can define operators as symbols that
help us to perform specific mathematical and logical computations on operands. In other words, we can
say that an operator operates the operands.
C/C++ has many built-in operators and can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
1. Arithmetic Operators:
These operators are used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *,
/, %,++,–). Arithmetic operators are of two types:
a) Unary Operators: Operators that operate or work with a single operand are unary operators. For
example: Increment(++) and Decrement(–) Operators
int val = 5;
++val; // 6
b) Binary Operators: Operators that operate or work with two operands are binary operators. For
example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators:
These are used for the comparison of the values of two operands. For example, checking if one operand
is equal to the other operand or not, whether an operand is greater than the other operand or not, etc.
Some of the relational operators are (==, >= , <= )(See this article for more reference).
int a = 3;
int b = 5;
a < b;
// operator to check if a is smaller than b
3. Logical Operators:
Logical Operators are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. The result of the operation of a logical operator is a
Boolean value either true or false.
For example, the logical AND represented as ‘&&’ operator in C or C++ returns true when both the
conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b returns true
when both a and b are true (i.e. non-zero)(See this article for more reference).
(4 != 5) && (4 < 5); // true
4. Bitwise Operators:
The Bitwise 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.
For example, the bitwise AND represented as & operator in C or C++ takes two numbers as operands
and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. (See this article
for more reference).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators:
Assignment 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.
Different types of assignment operators are shown below:
a. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to
the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
b. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of
the variable on left to the value on the right and then assigns the result to the variable on the left.
For example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c. “-=”: This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on
the right from the current value of the variable on left and then assigns the result to the variable on the
left.
For example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d. “*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator first multiplies the current
value of the variable on left to the value on the right and then assigns the result to the variable on the
left.
For example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e. “/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator first divides the current value
of the variable on left by the value on the right and then assigns the result to the variable on the left.
For example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators:
Apart from the above operators, there are some other operators available in C or C++ used to perform
some specific tasks. Some of them are discussed here:
a. sizeof operator:
sizeof is much used in the C/C++ programming language.
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable.(See this article
for reference)
b. Comma Operator:
The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
The comma operator has the lowest precedence of any C operator.
Comma acts as both operator and separator. (See this article for reference)
c. Conditional Operator :
The conditional operator is of the form Expression1? Expression2: Expression3.
Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then
we will execute and return the result of Expression2 otherwise if the condition(Expression1)
is false then we will execute and return the result of Expression3.
We may replace the use of if..else statements with conditional operators. (See this article for
reference)
d. dot (.) and arrow (->) Operators:
Member operators are used to reference individual members of classes, structures, and
unions.
The dot operator is applied to the actual object. (See this article for reference)
The arrow operator is used with a pointer to an object. (See this article for reference)
e. Cast Operator:
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
A cast is a special operator that forces one data type to be converted into another.
The most general cast supported by most of the C++ compilers is as follows − [ (type)
expression ]. (See this article for reference)
f. &,* Operator:
Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable var.
(See this article for reference
Below is the implementation of the above-mentioned operators:
C++
// Operators in C++
#include<iostream>
using namespace std;
int main(){
int a=10, b=5;
// Arithmetic operators
cout<<"Following are the Arithmetic operators in C++"<<endl;
cout<<"The value of a + b is "<<a+b<<endl;
cout<<"The value of a - b is "<<a-b<<endl;
cout<<"The value of a * b is "<<a*b<<endl;
cout<<"The value of a / b is "<<a/b<<endl;
cout<<"The value of a % b is "<<a%b<<endl;
cout<<"The value of a++ is "<<a++<<endl; // First print (a) and then
increment it by 1
cout<<"The value of a-- is "<<a--<<endl; // First print (a+1) and then
decrease it by 1
cout<<"The value of ++a is "<<++a<<endl; // Increment (a) by (a+1)
and then print
cout<<"The value of --a is "<<--a<<endl; // Decrement (a+1) by (a)
and then print
cout<<endl;
// Assignment Operators --> used to assign values to variables
// int a =3, b=9;
// char d='d';
// Comparison operators
// Output of all these comparison operators will be (1) if it is true and
(0) if it is false
cout<<"Following are the comparison operators in C++"<<endl;
cout<<"The value of a == b is "<<(a==b)<<endl;
cout<<"The value of a != b is "<<(a!=b)<<endl;
cout<<"The value of a >= b is "<<(a>=b)<<endl;
cout<<"The value of a <= b is "<<(a<=b)<<endl;
cout<<"The value of a > b is "<<(a>b)<<endl;
cout<<"The value of a < b is "<<(a<b)<<endl;
cout<<endl;
// Logical operators
cout<<"Following are the logical operators in C++"<<endl;
cout<<"The value of this logical and operator ((a==b) && (a<b))
is:"<<((a==b) && (a<b))<<endl;
cout<<"The value of this logical or operator ((a==b) || (a<b))
is:"<<((a==b) || (a<b))<<endl;
cout<<"The value of this logical not operator (!(a==b)) is:"<<(!
(a==b))<<endl;
return 0;
}
// This code is contributed by Suruchi Kumari
Output
Following are the Arithmetic operators in C++
The value of a + b is 15
The value of a - b is 5
The value of a * b is 50
The value of a / b is 2
The value of a % b is 0
The value of a++ is 10
The value of a-- is 11
The value of ++a is 11
The value of --a is 10
Following are the comparison operators in C++
The value of a == b is 0
The value of a != b is 1
The value of a >= b is 1
The value of a <= b is 0
The value of a > b is 1
The value of a < b is 0
Following are the logical operators in C++
The value of this logical and operator ((a==b) && (a<b)) is:0
The value of this logical or operator ((a==b) || (a<b)) is:0
The value of this logical not operator (!(a==b)) is:1
Operator Precedence Chart
Precedence Operator Description Associativity
* Dereference right-to-left
12 || Logical OR left-to-right
= Assignment right-to-left
Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown
below. In computer programming, a loop is a sequence of instructions that is repeated until a certain
condition is reached.
An operation is done, such as getting an item of data and changing it, and then some
condition is checked such as whether a counter has reached a prescribed number.
Counter not Reached: If the counter has not reached the desired number, the next
instruction in the sequence returns to the first instruction in the sequence and repeats it.
Counter reached: If the condition has been reached, the next instruction “falls through” to the
next sequential instruction or branches outside the loop.
There are mainly two types of loops:
1. Entry Controlled loops: In this type of 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.
S.No
. 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.
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
}
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++;
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;
}
Flow Diagram:
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);
Note: Notice the semi – colon(“;”) in the end of loop.
Flow Diagram:
What about an Infinite Loop?
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 always evaluated to be true.
Usually, this is an error.
Range-based for loop in C++
for_each loop in C++
Important Points:
Use for loop when a number of iterations are known beforehand, i.e. the number of times the
loop body is needed to be executed is known.
Use while loops, where an exact number of iterations is not known but the loop termination
condition, is known.
Use do while loop if the code needs to be executed at least once like in Menu-driven programs
10. Decision Making in C++(Practice)
Decision-making statements in programming languages decide the direction of the flow of program
execution. Decision-making statements available in C or C++ are:
1. if statement
if statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block of
statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement accepts boolean values – if
the value is true then it will execute the block of statements below it otherwise not. If we do not provide
the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement will consider the first immediately
below statement to be inside its block.
2. if..else statements
if-else in C/C++
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the C else statement. We can use the else statement with if statement to execute a block of code when
the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart:
3. nested if statements
nested-if in C/C++
A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an
if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if
statements, i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Flowchart
4. if-else-if ladder
if-else-if ladder in C/C++
Here, a user can decide among multiple options. The C if statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement associated with that if is executed,
and the rest of the C else-if ladder is bypassed. If none of the conditions are true, then the final else
statement will be executed.
Syntax:
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
5. switch statements
6. Jump Statements:
These statements are used in C orC++ for the unconditional flow of control throughout the functions in a
program. They support four types of jump statements:
1. break
This loop control statement is used to terminate the loop. As soon as the break statement is encountered
from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first
statement after the loop.
Syntax:
break;
Basically, break statements are used in situations when we are not sure about the actual number of
iterations for the loop or we want to terminate the loop based on some condition.
2. continue
1. This loop control statement is just like the break statement. The continue statement is opposite
to that of the break statement, instead of terminating the loop, it forces to execute the next
iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped and the next iteration of the loop will begin.
Syntax:
continue;
1.
3. goto
1. The goto statement in C/C++ also referred to as unconditional jump statement can be used to
jump from one point to another within a function.
Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
1. In the above syntax, the first line tells the compiler to go to or jump to the statement marked as
a label. Here label is a user-defined identifier that indicates the target statement. The
statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also
appear before the ‘goto label;’ statement in the above syntax.
4. return
7. The return in C or C++ returns the flow of the execution to the function from where it is called.
This statement does not mandatorily need any conditional statements. As soon as the statement
is executed, the flow of the program stops immediately and return the control from where it was
called. The return statement may or may not return anything for a void function, but for a non-void
function, a return value is must be returned.
Syntax:
return[expression];
11. Execute both if and else simultaneously
Write a C/C++ program that executes both if-else block statements simultaneously.
Syntax of if-else statement in C/C++ language is:
if (Boolean expression)
{
// Statement will execute only
// if Boolean expression is true
}
else
{
// Statement will execute only if
// the Boolean expression is false
}
Hence we can conclude that only one of the block of if-else statement will execute according to the
condition of Boolean expression.
But we can change our code so that both the statements inside the if block and the else block gets
executed, for the same condition.
The trick is to use goto statement which provides an unconditional jump from the ‘goto’ to a labeled
statement in the same function.
NOTE – Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. As a programmer, we should avoid the use of goto statement in C/C++.
12. How to compile 32-bit program on 64-bit gcc in C and C++
Now in order to compile with 32-bit gcc, just add a flag -m32 in the command line of compiling the ‘C’
language program. For instance, to compile a file of geek.c through Linux terminal, you must write the
following command with -m32 flag.
Command: gcc -m32 geek.c -o geek
If you get an error as follows:
fatal error: bits/predefs.h: No such file or directory
Then it indicates that a standard library of gcc is been missing. In that case you must install gcc-
multlib by using the following command:
For C language:
sudo apt-get install gcc-multilib
For C++ language:
sudo apt-get install g++-multilib
After that you will be able to compile a 32-bit binary on a 64-bit system.
13. Switch statement in C++(Practice)
Switch case statement evaluates a given expression and based on the evaluated value(matching a
certain condition), it executes the statements associated with it. Basically, it is used to perform different
actions based on different conditions(cases).
Switch case statements follow a selection-control mechanism and allow a value to change
control of execution.
They are a substitute for long if statements that compare a variable to several integral values.
The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
In C++, the switch statement is used for executing one condition from multiple conditions. It is similar to
an if-else-if ladder.
Switch statement consists of conditional based cases and a default case.
In a switch statement, the “case value” can be of “char” and “int” type.
Following are some of the rules while using the switch statement:
1. There can be one or N numbers of cases.
2. The values in the case must be unique.
3. Each statement of the case can have a break statement. It is optional.
Syntax:
switch(expression)
{
case value1: statement_1; break;
}
Some important keywords:
1) Break: This keyword is used to stop the execution inside a switch block. It helps to terminate the
switch block and break out of it.
2) Default: This keyword is used to specify the set of statements to execute if there is no case match.
Note: Sometimes when default is not placed at the end of switch case program, we should use break
statement with the default case.
Important Points About Switch Case Statements:
1) The expression provided in the switch should result in a constant value otherwise it would not be
valid. Some valid expressions for switch case will be,
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)
// Variable expression are allowed provided
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)
2) Duplicate case values are not allowed.
3) The default statement is optional. Even if the switch case statement do not have a default
statement,
it would run without any problem.
4) The break statement is used inside the switch to terminate a statement sequence. When a break
statement is reached, the switch terminates, and the flow of control jumps to the next line following the
switch statement.
5) The break statement is optional. If omitted, execution will continue on into the next case. The flow of
control will fall through to subsequent cases until a break is reached.
6) Nesting of switch statements is allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes the program more
complex and less readable.
7) Switch statements are limited to integer values and characters only in the check condition.
Flowchart:
Types of Functions
Library Function
Library functions are also called “builtin Functions“. These functions are a part of a compiler package
that is already defined and consists of a special function with special and different meanings. Builtin
Function gives us an edge as we can directly use them without defining them whereas in the user-defined
function we have to declare and define a function before using them.
For Example: sqrt(), setw(), strcat(), etc.
Parameter Passing to Functions
The parameters passed to function are called actual parameters. For example, in the program below, 5
and 10 are actual parameters.
The parameters received by the function are called formal parameters. For example, in the above
program x and y are formal parameters.
Output
x = 20
Functions Using Pointers
The function fun() expects a pointer ptr to an integer (or an address of an integer). It modifies the value at
the address ptr. The dereference operator * is used to access the value at an address. In the statement
‘*ptr = 30’, the 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.
C++
Output
x = 30
Points to Remember About Functions in C++
1. Most C++ program has a function called main() that is called by the 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 the return statement in the body of the
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:
C++
3. 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.
Main Function
The main function is a special function. Every C++ program must contain a function named main. 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 Functions
1. Without parameters:
CPP
// Without Parameters
int main() { ... return 0; }
2. With parameters:
CPP
// 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 by a
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.
15. Arrays in C/C++(Practice)
Array
1. It is a group of variables of similar data types referred to by a single element.
2. Its elements are stored in a contiguous memory location.
3. The size of the array should be mentioned while declaring it.
4. Array elements are always counted from zero (0) onward.
5. Array elements can be accessed using the position of the element in the array.
6. The array can have one or more dimensions.
An array in C/C++ or be it in any programming language is a collection of similar data items stored at
contiguous memory locations and elements can be accessed randomly using indices of an array. They
can be used to store the collection of primitive data types such as int, float, double, char, etc of any
particular type. To add to it, an array in C/C++ can store derived data types such as structures, pointers
etc. Given below is the picture representation of an array.
Note: In the above image int a[3]={[0…1]=3}; this kind of declaration has been obsolete since GCC 2.5
Advantages of an Array in C/C++:
1. Random access of elements using the array index.
2. Use of fewer lines of code as it creates a single array of multiple elements.
3. Easy access to all the elements.
4. Traversal through the array becomes easy using a single loop.
5. Sorting becomes easy as it can be accomplished by writing fewer lines of code.
Disadvantages of an Array in C/C++:
1. Allows a fixed number of elements to be entered which is decided at the time of declaration.
Unlike a linked list, an array in C is not dynamic.
2. Insertion and deletion of elements can be costly since the elements are needed to be
managed in accordance with the new memory allocation.
Facts about Array in C/C++:
Accessing Array Elements:
Array elements are accessed by using an integer index. Array index starts with 0 and goes till
the size of the array minus 1.
The name of the array is also a pointer to the first element of the array.
When strings are declared as character arrays, they are stored like other types of arrays in C. For
example, if str[] is an auto variable then string is stored in stack segment, if it’s a global or static variable
then stored in data segment, etc.
Strings using character pointers
Using character pointer strings can be stored in two ways:
1) Read only string in a shared segment.
When a string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read-only
block (generally in data segment) that is shared among functions.
C
In the above line “GfG” is stored in a shared read-only location, but pointer str is stored in a read-write
memory. You can change str to point something else but cannot change value at present str. So this kind
of string should only be used when we don’t want to modify string at a later stage in the program.
2) Dynamically allocated in heap segment.
Strings are stored like other dynamically allocated things in C and can be shared among functions.
C
char *str;
int size = 4; /*one extra for ‘\0’*/
str = (char *)malloc(sizeof(char)*size);
*(str+0) = 'G';
*(str+1) = 'f';
*(str+2) = 'G';
*(str+3) = '\0';
*(*nums) nums[0][0] 16
*(*nums + 1) nums[0][1] 18
*(*nums + 2) nums[0][2] 20
*(*(nums + 1) +
1) nums[1][1] 26
*(*(nums + 1) +
2) nums[1][2] 27
18. References in C++
When a variable is declared as a reference, it becomes an alternative name for an existing variable. A
variable can be declared as a reference by putting ‘&’ in the declaration.
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << '\n';
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << '\n';
return 0;
}
Output:
x = 20
ref = 30
Applications :
1. Modify the passed parameters in a function: If a function receives a reference to a variable, it can
modify the value of the variable. For example, the following program variables are swapped using
references.
CPP
#include <iostream>
using namespace std;
void swap(int& first, int& second)
{
int temp = first;
first = second;
second = temp;
}
int main()
{
int a = 2, b = 3;
swap(a, b);
cout << a << " " << b;
return 0;
}
Output:
32
2. Avoiding a copy of large structures: Imagine a function that has to receive a large object. If we
pass it without reference, a new copy of it is created which causes wastage of CPU time and memory.
We can use references to avoid this.
CPP
struct Student {
string name;
string address;
int rollNo;
}
// If we remove & in below function, a new
// copy of the student object is created.
// We use const to avoid accidental updates
// in the function as the purpose of the function
// is to print s only.
void print(const Student &s)
{
cout << s.name << " " << s.address << " " << s.rollNo
<< '\n';
}
3. In For Each Loop to modify all objects: We can use references in for each loop to modify all
elements.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> vect{ 10, 20, 30, 40 };
// We can modify elements if we
// use reference
for (int& x : vect) {
x = x + 5;
}
// Printing elements
for (int x : vect) {
cout << x << " ";
}
cout << '\n';
return 0;
}
4. For Each Loop to avoid the copy of objects: We can use references in each loop to avoid a copy
of individual objects when objects are large.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<string> vect{ "geeksforgeeks practice",
"geeksforgeeks write",
"geeksforgeeks ide" };
// We avoid copy of the whole string
// object by using reference.
for (const auto& x : vect) {
cout << x << '\n';
}
return 0;
}
References vs Pointers:
Both references and pointers can be used to change the local variables of one function inside another
function. Both of them can also be used to save copying of big objects when passed as arguments to
functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the
following differences between references and pointers.
1. A pointer can be declared as void but a reference can never be void For example
int a = 10;
void* aa = &a; // it is valid
void& ar = a; // it is not valid
2. The pointer variable has n-levels/multiple levels of indirection i.e. single-pointer, double-pointer, triple-
pointer. Whereas, the reference variable has only one/single level of indirection. The following code
reveals the mentioned points:
3. Reference variable cannot be updated.
4. Reference variable is an internal pointer.
5. Declaration of a Reference variable is preceded with the ‘&’ symbol ( but do not read it as “address
of”).
C++
#include <iostream>
using namespace std;
int main()
{
int i = 10; // simple or ordinary variable.
int* p = &i; // single pointer
int** pt = &p; // double pointer
int*** ptr = &pt; // triple pointer
// All the above pointers differ in the value they store
// or point to.
cout << "i = " << i << "\t"
<< "p = " << p << "\t"
<< "pt = " << pt << "\t"
<< "ptr = " << ptr << '\n';
int a = 5; // simple or ordinary variable
int& S = a;
int& S0 = S;
int& S1 = S0;
cout << "a = " << a << "\t"
<< "S = " << S << "\t"
<< "S0 = " << S0 << "\t"
<< "S1 = " << S1 << '\n';
// All the above references do not differ in their
// values as they all refer to the same variable.
}
class person
{
char name[20];
int id;
public:
void getdetails(){}
};
int main()
{
person p1; // p1 is a object
}
Object take up space in memory and have an associated address like a record in pascal or structure or
union in C.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data. Objects can interact without having to know
details of each other’s data or code, it is sufficient to know the type of message accepted and type of
response returned by the objects.
Encapsulation: In normal terms, Encapsulation is defined as wrapping up of data and information under a
single unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data and
the functions that manipulate them.
Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section etc. The finance section handles all the financial
transactions and keeps records of all the data related to finance. Similarly, the sales section handles all
the sales-related activities and keeps records of all the sales. Now there may arise a situation when for
some reason an official from the finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of the sales section. He will first have to contact
some other officer in the sales section and then request him to give the particular data. This is what
encapsulation is. Here the data of the sales section and the employees that can manipulate them are
wrapped under a single name “sales section”.
Encapsulation also leads to data abstraction or hiding. As using encapsulation also hides the data. In the
above example, the data of any of the section like sales, finance or accounts are hidden from any other
section.
Abstraction: Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding the details. Data
abstraction refers to providing only essential information about the data to the outside world, hiding the
background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators
will increase the speed of the car or applying brakes will stop the car but he does not know about how on
pressing accelerator the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.
Abstraction using Classes: We can implement Abstraction in C++ using classes. The class
helps us to group data members and member functions using available access specifiers. A
Class can decide which data member will be visible to the outside world and which is not.
Abstraction in Header files: One more type of abstraction in C++ can be header files. For
example, consider the pow() method present in math.h header file. Whenever we need to
calculate the power of a number, we simply call the function pow() present in the math.h
header file and pass the numbers as arguments without knowing the underlying algorithm
according to which the function is actually calculating the power of numbers.
Polymorphism: The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the same time is a father, a
husband, an employee. So the same person posses different behaviour in different situations. This is
called polymorphism.
An operation may exhibit different behaviours in different instances. The behaviour depends upon the
types of data used in the operation.
C++ supports operator overloading and function overloading.
Operator Overloading: The process of making an operator to exhibit different behaviours in
different instances is known as operator overloading.
Function Overloading: Function overloading is using a single function name to perform
different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Inheritance: The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived
Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or
Super class.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Dynamic Binding: In dynamic binding, the code to be executed in response to function call is
decided at runtime. C++ has virtual functions to support this.
Message Passing: Objects communicate with one another by sending and receiving information
to each other. A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function and the information to be
sent.
C vs C++
4. void * in C vs C++
C++ vs Java
In C, we could use the function freopen() to redirect an existing FILE pointer to another stream. The
prototype for freopen() is given as
FILE * freopen ( const char * filename, const char * mode, FILE * stream );
While this method is still supported in C++, this article discusses another way to redirect I/O streams.
C++ being an object-oriented programming language, gives us the ability to not only define our own
streams but also redirect standard streams. Thus, in C++, a stream is an object whose behavior is
defined by a class. Thus, anything that behaves like a stream is also a stream.
Streams Objects in C++ are mainly of three types :
istream : Stream object of this type can only perform input operations from the stream
All these classes, as well as file stream classes, derived from the classes: ios and streambuf. Thus,
filestream and IO stream objects behave similarly.
All stream objects also have an associated data member of class streambuf. Simply put, streambuf object
is the buffer for the stream. When we read data from a stream, we don’t read it directly from the source,
but instead, we read it from the buffer which is linked to the source. Similarly, output operations are first
performed on the buffer, and then the buffer is flushed (written to the physical device) when needed.
C++ allows us to set the stream buffer for any stream, So the task of redirecting the stream simply
reduces to changing the stream buffer associated with the stream. Thus, to redirect a Stream A to
Stream B we need to do:-
CPP
#include <iostream>
#include <string>
int main()
fstream file;
file.open("cout.txt", ios::out);
string line;
cout.rdbuf(stream_buffer_file);
cout.rdbuf(stream_buffer_cout);
file.close();
return 0;
Output:
Note:
The above steps can be condensed into a single step
What is a buffer?
A temporary storage area is called a buffer. All standard input and output devices contain an input and
output buffer. In standard C/C++, streams are buffered. For example, in the case of standard input, when
we press the key on the keyboard, it isn’t sent to your program, instead of that it is send to the buffer by
the operating system, till the time is allotted to that program.
C
#include<stdio.h>
int main()
scanf("%s", str);
ch = getchar();
printf("%s\n", str);
printf("%c", ch);
return 0;
Input:
GeeksforGeeks
a
Output:
GeeksforGeeks
In the case of C++
C++
// outputs
#include<iostream>
#include<vector>
int main()
int a;
char ch[80];
cin >> a;
cin.getline(ch,80);
// Prints 4
return 0;
Input:
GeeksforGeeks
Output:
In both the above codes, the output is not printed as desired. The reason for this is an occupied Buffer.
The “\n” character goes remains there in buffer and is read as the next input.
In the case of C :
1. Using “ while ((getchar()) != ‘\n’); ” : Typing “while ((getchar()) != ‘\n’);” reads the buffer characters till
the end and discards them(including newline) and using it after the “scanf()” statement clears the input
buffer and allows the input in the desired container.
C
#include<stdio.h>
int main()
{
scanf("%s", str);
ch = getchar();
printf("%s\n", str);
printf("%c", ch);
return 0;
Input:
GeeksforGeeks
a
Output:
GeeksforGeeks
2. Using “ fflush(stdin) ”: Typing “fflush(stdin)” after “scanf()” statement, also clears the input buffer but
generally it’s use is avoided and is termed to be “undefined” for input stream as per the C++11 standards.
C++
// "cin.ignore(numeric_limits
// <streamsize>::max(),'\n');"
#include<iostream>
// for <streamsize>
#include<ios>
// for numeric_limits
#include<limits>
int main()
int a;
char str[80];
cin >> a;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cin.getline(str, 80);
// Prints 4
return 0;
Input:
GeeksforGeeks
Output:
GeeksforGeeks
2. Using “ cin.sync() ”: Typing “cin.sync()” after the “cin” statement discards all that is left in the buffer.
Though “cin.sync()” does not work in all implementations (According to C++11 and above standards).
C++
#include<iostream>
#include<ios>
#include<limits>
int main()
int a;
char str[80];
cin >> a;
cin.sync();
cin.getline(str, 80);
// Prints 4
return 0;
Input:
GeeksforGeeks
Output:
3. Using “ cin >> ws ”: Typing “cin>>ws” after “cin” statement tells the compiler to ignore buffer and also
to discard all the whitespaces before the actual content of string or character array.
C++
#include<iostream>
#include<vector>
int main()
int a;
string s;
// Enter input from user -
cin >> a;
getline(cin, s);
return 0;
Input:
GeeksforGeeks
Output:
GeeksforGeeks
3. Basic Input/Output(Practice)
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.
#include <iostream>
using namespace std;
int main()
{
char sample[] = "GeeksforGeeks";
cout << sample << " - A computer science portal for geeks";
return 0;
}
Output:
GeeksforGeeks - A computer science portal for geeks
In the above program, the insertion operator(<<) inserts the value of the string variable sample followed
by the string “A computer science portal for geeks” in the standard output stream cout which is then
displayed on the screen.
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.
C++
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
return 0;
}
Input :
18
Output:
Enter your age:
Your age is: 18
The above program asks the user to input the age. The object cin is connected to the input device. The
age entered by the user is extracted from cin using the extraction operator(>>) and the extracted data is
then stored in the variable age present on the right side of the extraction operator.
Un-buffered standard error stream (cerr): The C++ cerr is the standard error stream 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.
The main difference between cerr and cout comes when you would like to redirect output
using “cout” that gets redirected to file if you use “cerr” the error doesn’t get stored in file.(This
is what un-buffered means ..It cant store the message)
C++
#include <iostream>
using namespace std;
int main()
{
cerr << "An error occurred";
return 0;
}
Output:
An error occurred
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.
C++
#include <iostream>
using namespace std;
int main()
{
clog << "An error occurred";
return 0;
}
Output:
An error occurred
endl and \n both seem to do the same thing but there is a subtle difference between them.
cout << endl inserts a new line and flushes the stream(output buffer), whereas cout << “\n” just inserts
a new line.
Therefore, cout << endl; can be said equivalent to cout << ‘\n’ << flush;
endl \n
It is a manipulator. It is a character.
It is a keyword and would not specify any It can be stored in a string and will still convey its
meaning when stored in a string. specific meaning of line break.
We cannot write ‘endl’ in between double We can write ‘\n’ in between double quotations like
quotations. cout<<“\n”;
endl \n
It keeps flushing the queue in the output buffer It flushes the output buffer only once at the end of
throughout the process. the program
Note: cout << “\n” looks performance wise better but in real cout << endl is much better in C++; As it
doesn’t occupies any memory and also if flushing of stream is required.
Example 1:
We can use endl in C++ but not in C. So endl runs well in C++ but if we use C, it runs error.
C++
C
#include <iostream>
int main() {
cout << "GFG!"<<endl; //We can use endl in C++ and it doesn't
occupy any memory
return 0;
Output:
GFG!
GFG!
Example 2:
C++
C
#include <iostream>
int main() {
return 0;
Output:
GFG!
GFG!
scanf() is a library function in C. It reads standard input from stdin. fgets() is a library function in C. It
reads a line from the specified stream and stores it into the string pointed to by the string variable. It only
terminates when either:
end-of-file is reached
n-1 characters are read
the newline character is read
1) Consider a below simple program in C. The program reads an integer using scanf(), then reads a
string using fgets(),
Input
10
test
C
#include <stdio.h>
int main()
int x;
char str[100];
scanf("%d", &x);
return 0;
Output
x = 10, str =
Explanation: The problem with the above code is scanf() reads an integer and leaves a newline
character in the buffer. So fgets() only reads newline and the string “test” is ignored by the program.
Input:
C
#include <stdio.h>
int main()
char c;
printf("Press q to quit\n");
do {
printf("Enter a character\n");
scanf("%c", &c);
printf("%c\n", c);
return 0;
Output
Press q to quit
Enter a character
Enter a character
Enter a character
Enter a character
Enter a character
Explanation: We can notice that the above program prints an extra “Enter a character” followed by an
extra newline. This happens because every scanf() leaves a newline character in a buffer that is read by
the next scanf.
Input:
10
test
C
#include <stdio.h>
int main()
int x;
char str[100];
scanf("%d\n", &x);
return 0;
Output
Input:
C
#include <stdio.h>
// Driver Code
int main()
char c;
printf("Press q to quit\n");
do {
printf("Enter a character\n");
scanf("%c\n", &c);
printf("%c\n", c);
return 0;
Output: Press q to quit
Enter a character
Enter a character
Enter a character
6. How to use getline() in C++ when there are blank lines in input?
In C++, if we need to read a few sentences from a stream, the generally preferred way is to use
the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided
by the user. Also, it uses <string.h> header file to be fully functional.
Here is a sample program in c++ that reads four sentences and displays them with “: newline” at the end
CPP
#include <cstring>
#include <iostream>
using namespace std;
int main()
string str;
int t = 4;
while (t--) {
getline(cin, str);
}
return 0;
Sample Input :
This
is
Geeks
for
This : newline
is : newline
Geeks : newline
for : newline
The above input and output look good, there may be problems when the input has blank lines in
between.
Sample Input :
This
is
Geeks
for
Output:
This : newline
: newline
is : newline
: newline
It doesn’t print the last 3 lines. The reason is that getline() reads till enter is encountered even if no
characters are read. So even if there is nothing in the third line, getline() considers it as a single line.
Further, observe the problem in the second line. The code can be modified to exclude such blank lines.
Modified code:
CPP
#include <cstring>
#include <iostream>
int main()
string str;
int t = 4;
while (t--) {
getline(cin, str);
while (str.length() == 0)
getline(cin, str);
return 0;
Input:
This
is
Geeks
for
Output:
This : newline
is : newline
Geeks : newline
for : newline
In C language, scanf() function is used to read formatted input from stdin. It returns the whole number of
characters written in it otherwise, returns a negative value.
Syntax:
Many of us know the traditional uses of scanf. Well, here are some of the lesser-known facts
Example:
C
// C program to demonstrate that
// in scanf()
#include <stdio.h>
int main()
int a;
return 0;
Now, assume we don’t know what the preceding characters are but we surely know that the last value is
an integer. How can we scan the last value as an integer?
The below solution works only if the input string has no spaces. For example,
Input
"blablabla 25"
C
#include <stdio.h>
int main()
int a;
return 0;
}
Output
Explanation: The %*s in scanf is used to ignore some input as required. In this case, it ignores the input
until the next space or newline. Similarly, if you write %*d it will ignore integers until the next space or
newline.
C
#include <stdio.h>
int main()
int a;
scanf("%d", &a);
return 0;
Input
Output
a=2
The above fact may not seem like a useful trick at the first glance. In order to understand its usage, let us
first see fscanf().
fscanf Function in C
Tired of all the clumsy syntax to read from files? well, fscanf comes to the rescue. This function is used to
read the formatted input from the given stream in the C language.
Syntax:
fscanf reads from a file pointed by the FILE pointer (ptr), instead of reading from the input stream.
Return Value: It returns zero, if unsuccessful. Otherwise, it returns The input string, if successful.
abc 12 hyderbad
bef 25 delhi
cce 65 bangalore
Now, we want to read only the city field of the above text file, ignoring all the other fields. A combination
of fscanf and the trick mentioned above does this with ease
C
#include <stdio.h>
// Driver Code
int main()
return 0;
}
format
char buf[100];
printf("%s\n", buf);
return 0;
Output
CITY
hyderabad
delhi
bangalore
n1 n2 n3
1 5 6
2 10 11
3 15 16
4 20 21
To read all values of n1, n2 & n3 of the bin, we are using fscanf()
C
#include <stdio.h>
#include <stdlib.h>
struct threeNum{
};
int main(){
int n;
exit(1);
}
}
fclose(fptr);
return 0;
Output
scanf() fscanf()
Its syntax is -:
Its syntax is -:
fscanf(FILE *stream, const char
2. scanf(const char *format, …) *format, …)
It requires Format specifiers to take input of a particular
3. type. It reads the stream in the form of byte
C++
Output:
To stop enter any character
Enter Your Input 1 2 3 s
Total number of inputs entered: 3
Time Complexity: O(count)
Auxiliary Space: O(1)
#define macro can be used for this task. This macro is defined inside the function.
Although, #define can be used without declaring it in the function, in that case always the printf() will be
changed. The function needs to be called first to change the output of printf() in main().
Consider the following program. Change the program so that the output of printf() is always 10.
C
// in main()
#include <stdio.h>
void fun()
// 10
// Driver Code
int main()
{
int i = 10;
fun();
i = 20;
printf("%d", i);
return 0;
It is not allowed to change main(). Only fun() can be changed. Now, consider the following program using
Macro Arguments,
C
#include <stdio.h>
void fun()
// Driver Code
int main()
int i = 10;
fun();
i = 20;
printf("%d", i);
return 0;
}
Output
10
Time Complexity: O(1)
Since the dawn of computers, Hollywood has greatly demonstrated a Hacker or a Programmer as
someone sitting on a computer typing random keys on computer which ultimately compiles to a Falling
matrix like simulation. Here, we will try to implement a similar falling matrix simulation on the console
using C++.
The idea here is to print random characters over a defined width, where the two successive characters
may or may not have certain amount of gap defined randomly. A certain amount of delay between
printing successive lines has to be implemented in order to have a ‘falling effect’.
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
$ falling.o
A buffer flush is the transfer of computer data from a temporary storage area to the computer’s
permanent memory. For instance, if we make any changes in a file, the changes we see on one
computer screen are stored temporarily in a buffer.
Usually, a temporary file comes into existence when we open any word document and is automatically
destroyed when we close our main file. Thus when we save our work, the changes that we’ve made to
our document since the last time we saved it are flushed from the buffer to permanent storage on the
hard disk.
In C++, we can explicitly be flushed to force the buffer to be written. Generally, the std::endl function
works the same by inserting a new-line character and flushes the stream. stdout/cout is line-
buffered that is the output doesn’t get sent to the OS until you write a newline or explicitly flush the
buffer. For instance,
C++
// performance.
std::cout << a << " + " << b << " = " << std::endl;
C++
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
this_thread::sleep_for(chrono::seconds(1));
}
return 0;
C++
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
this_thread::sleep_for(chrono::seconds(1));
}
return 0;
Note:
1. You can’t run the program on an online compiler to see the difference, since they give output only
when it terminates. Hence you need to run all the above programs in an offline compiler like GCC
or clang.
2. Reading cin flushes cout so we don’t need an explicit flush to do this.
kbhit() functionality is basically stand for the Keyboard Hit. This function is deals with keyboard pressing
kbhit() is present in conio.h and used to determine if a key has been pressed or not. To use kbhit function
in your program you should include the header file “conio.h”. If a key has been pressed then it returns a
non zero value otherwise returns zero.
CPP
#include <iostream.h>
#include <conio.h>
int main()
while (!kbhit())
printf("Press a key\n");
return 0;
Output:
Note : kbhit() is not a standard library function and should be avoided. Program to fetch the pressed
key using kbhit
CPP
// kbhit()
#include <iostream>
#include <conio.h>
int main()
{
char ch;
while (1) {
if ( kbhit() ) {
ch = getch();
break;
}
}
return 0;
Output:
C
#include <stdio.h>
#include <conio.h>
main()
{
char ch;
while (1) {
if (kbhit) {
ch = getch();
// when esc button is pressed, then it will exit from loop
break;
}
}
Output :
Output:
Operators
1. Operators in C++
Operators are the foundation of any programming language. We can define operators as symbols that
help us to perform specific mathematical and logical computations on operands. In other words, we can
say that an operator operates the operands. For example, ‘+’ is an operator used for addition, as shown
below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The addition
operator tells the compiler to add both of the operands ‘a’ and ‘b’.
The functionality of the C/C++ programming language is incomplete without the use of operators.
C/C++ has many built-in operators and can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
The above operators have been discussed in detail:
1. Arithmetic Operators:
These operators are used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *,
/, %,++,–). Arithmetic operators are of two types:
a) Unary Operators: Operators that operate or work with a single operand are unary operators. For
example: Increment(++) and Decrement(–) Operators
int val = 5;
++val; // 6
b) Binary Operators: Operators that operate or work with two operands are binary operators. For
example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators:
These are used for the comparison of the values of two operands. For example, checking if one operand
is equal to the other operand or not, whether an operand is greater than the other operand or not, etc.
Some of the relational operators are (==, >= , <= )(See this article for more reference).
int a = 3;
int b = 5;
a < b;
// operator to check if a is smaller than b
3. Logical Operators:
Logical Operators are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. The result of the operation of a logical operator is a
Boolean value either true or false.
For example, the logical AND represented as ‘&&’ operator in C or C++ returns true when both the
conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b returns true
when both a and b are true (i.e. non-zero)(See this article for more reference).
4. Bitwise Operators:
The Bitwise 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.
For example, the bitwise AND represented as & operator in C or C++ takes two numbers as operands
and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. (See this article
for more reference).
5. Assignment Operators:
Assignment 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.
a = 10;
b = 20;
ch = 'y';
b. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of
the variable on left to the value on the right and then assigns the result to the variable on the left.
For example:
(a += b) can be written as (a = a + b)
c. “-=”: This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on
the right from the current value of the variable on left and then assigns the result to the variable on the
left.
For example:
(a -= b) can be written as (a = a - b)
d. “*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator first multiplies the current
value of the variable on left to the value on the right and then assigns the result to the variable on the
left.
For example:
(a *= b) can be written as (a = a * b)
e. “/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator first divides the current value
of the variable on left by the value on the right and then assigns the result to the variable on the left.
For example:
(a /= b) can be written as (a = a / b)
6. Other Operators:
Apart from the above operators, there are some other operators available in C or C++ used to perform
some specific tasks. Some of them are discussed here:
a. sizeof operator:
b. Comma Operator:
The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value (and
type).
The comma operator has the lowest precedence of any C operator.
Comma acts as both operator and separator. (See this article for reference)
c. Conditional Operator :
Member operators are used to reference individual members of classes, structures, and unions.
The dot operator is applied to the actual object. (See this article for reference)
The arrow operator is used with a pointer to an object. (See this article for reference)
e. Cast Operator:
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
A cast is a special operator that forces one data type to be converted into another.
The most general cast supported by most of the C++ compilers is as follows − [ (type)
expression ]. (See this article for reference)
f. &,* Operator:
Pointer operator & returns the address of a variable. For example &a; will give the actual address
of the variable.
Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable var.
(See this article for reference
C++
// Operators in C++
#include<iostream>
int main(){
cout<<endl;
cout<<endl;
return 0;
}
Output
The value of a + b is 15
The value of a - b is 5
The value of a * b is 50
The value of a / b is 2
The value of a % b is 0
The value of a == b is 0
The value of a != b is 1
The value of this logical and operator ((a==b) && (a<b)) is:0
The below table describes the precedence order and associativity of operators in C / C++. The
precedence of the operator decreases from top to bottom.
Precedence Operator Description Associativity
* Dereference right-to-left
12 || Logical OR left-to-right
= Assignment right-to-left
Unary operators: are operators that act upon a single operand to produce a new value.
1. unary minus(-)
2. increment(++)
3. decrement(- -)
4. NOT(!)
5. Addressof operator(&)
6. sizeof()
1. unary minus: The minus operator changes the sign of its argument. A positive number becomes
negative, and a negative number becomes positive.
int a = 10;
unary minus is different from the subtraction operator, as subtraction requires two operands.
Below is the implementation of unary minus (-) operator:
C++
#include <iostream>
int main()
return 0;
Output
2. increment: It is used to increment the value of the variable by 1. The increment can be done in two
ways:
2.1 prefix increment: In this method, the operator precedes the operand (e.g., ++a). The value of the
operand will be altered before it is used.
int a = 1;
int b = ++a; // b = 2
2.2 postfix increment: In this method, the operator follows the operand (e.g., a++). The value operand
will be altered after it is used.
int a = 1;
int b = a++; // b = 1
int c = a; // c = 2
3. decrement: It is used to decrement the value of the variable by 1. The decrement can be done in two
ways:
3.1 prefix decrement: In this method, the operator precedes the operand (e.g., – -a). The value of the
operand will be altered before it is used.
int a = 1;
int b = --a; // b = 0
3.2 postfix decrement: In this method, the operator follows the operand (e.g., a- -). The value of the
operand will be altered after it is used.
int a = 1;
int b = a--; // b = 1
int c = a; // c = 0
4. NOT(!): It is used to reverse the logical state of its operand. If a condition is true, then the Logical NOT
operator will make it false.
C++
#include <iostream>
int main()
int a = 10;
int b = 5;
if (!(a > b))
else
return 0;
Output
a is greater than b
5. Addressof operator(&): It gives an address of a variable. It is used to return the memory address of a
variable. These addresses returned by the address-of operator are known as pointers because they
“point” to the variable in memory.
int a;
int *ptr;
C++
// operator
#include <iostream>
int main()
{
int a;
int* ptr;
ptr = &a;
return 0;
Output
0x7ffddcf0c8ec
6. sizeof(): This operator returns the size of its operand, in bytes. The sizeof() operator always precedes
its operand. The operand is an expression, or it may be a cast.
Below is the implementation of sizeof() operator:
C++
#include <iostream>
int main()
float n = 0;
return 1;
}
Output
size of n: 4
Given 4 integers a, b, y, and x, where x can assume the values of either 0 or 1 only. The following
question is asked:
If 'x' is 0,
Note: – You are not allowed to use any conditional operator (including the ternary operator) or any
arithmetic operator (+, -, *, /).
Examples :
Input : a = 5 , b = 10, x = 1
Output : y = 10
Input : a = 5, b = 10 , x = 0
Output : y = 5
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Solution 1:
An Idea is to simply store both ‘a’ and ‘b’ in an array at 0th and 1st index respectively. Then store value
to ‘y’ by taking ‘x’ as an index.
C++
Java
Python3
C#
PHP
Javascript
// to value of x
#include <iostream>
// to value of x
int y;
int arr[2];
arr[0] = a;
arr[1] = b;
y = arr[x];
return y;
// Driver code
int main()
int a = 5;
int b = 10;
int x = 0;
return 0;
Output
Solution 2:
C++
Java
Python3
C#
Javascript
// to value of x
#include <iostream>
// Driver Code
int main()
int a = 5;
int b = 10;
int x = 1;
int y;
if (x & 1)
y = b;
else
y = a;
return 0;
Output
C
Output
11 10
10 10
12 11 11
Explanation: Usually, the compilers read parameters of printf() from right to left. So, ‘a++’ will be
executed first as it is the last parameter of the first printf() statement. It will print 10. Although, now the
value has been increased by 1, so the second last argument, i.e., will print 11. Similarly, the other
statements will also get executed.
Note: In pre-increment, i.e., ++a, it will increase the value by 1 before printing, and in post-increment,
i.e., a++, it prints the value at first, and then the value is incremented by 1.
Therefore, it is not recommended not to do two or more than two pre or post-increment operators in the
same statement. This means that there’s absolutely no temporal ordering in this process. The arguments
can be evaluated in any order, and the process of their evaluation can be intertwined in any way.
Given three integers a, b and c where c can be either 0 or 1. Without using any arithmetic, relational and
conditional operators set the value of a variable x based on below rules –
If c = 0
x=a
Else // Note c is binary
x = b.
Examples:
Input: a = 5, b = 10, c = 0;
Output: x = 5
Input: a = 5, b = 10, c = 1;
Output: x = 10
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Solution 1: Using arithmetic operators
If we are allowed to use arithmetic operators, we can easily calculate x by using any one of below
expressions –
x = ((1 - c) * a) + (c * b)
OR
x = (a + b) - (!c * b) - (c * a);
OR
x = (a * !c) | (b * c);
#include <iostream>
using namespace std;
int calculate(int a, int b, int c)
{
return ((1 - c) * a) + (c * b);
}
int main()
{
int a = 5, b = 10, c = 0;
int x = calculate(a, b, c);
cout << x << endl;
return 0;
}
Output:
5
Solution 2: Without using arithmetic operators
The idea is to construct an array of size 2 such that index 0 of the array stores value of variable ‘a’ and
index 1 value of variable b. Now we return value at index 0 or at index 1 of the array based on value of
variable c.
#include <iostream>
using namespace std;
int calculate(int a, int b, int c)
{
int arr[] = {a, b};
return *(arr + c);
}
int main()
{
int a = 5, b = 10, c = 1;
int x = calculate(a, b, c);
cout << x << endl;
return 0;
}
Output:
10
Scope resolution operator is for accessing static or class members and this pointer is for accessing
object members when there is a local variable with the same name.
CPP
// class members
#include <iostream>
class Test {
int a;
public:
Test() { a = 1; }
};
// Driver Code
int main()
Test obj;
int k = 3;
obj.func(k);
return 0;
Output
Explanation: The output for the above program is 3 since the “a” passed as an argument to
the func shadows the “a” of the class .i.e 1
Then how to output the class’s ‘a’. This is where this pointer comes in handy. A statement like cout
<<this->a instead of cout << a can simply output the value 1 as this pointer points to the object from
where func is called.
CPP
#include <iostream>
class Test {
int a;
public:
Test() { a = 1; }
};
// Driver code
int main()
{
Test obj;
int k = 3;
obj.func(k);
return 0;
Output
We cannot use the scope resolution operator in the above example to print the object’s member ‘a’
because the scope resolution operator can only be used for a static data member (or class members). If
we use the scope resolution operator in the above program we get compiler error and if we use this
pointer in the below program, then also we get a compiler error.
CPP
#include <iostream>
class Test {
static int a;
public:
};
// like this
int Test::a = 1;
// Driver code
int main()
Test obj;
int k = 3;
obj.func(k);
return 0;
Output
In C++, pre-increment (or pre-decrement) can be used as l-value, but post-increment (or post-decrement)
can not be used as l-value.
For example, following program prints a = 20 (++a is used as l-value)
l-value is simply nothing but the memory location, which has an address.
CPP
#include <cstdio>
int main()
{
int a = 10;
printf("\n");
--a = 10;
return 0;
Output:
a = 20
a = 10
The above program works whereas the following program fails in compilation with error “non-lvalue in
assignment” (a++ is used as l-value)
CPP
#include <cstdio>
int main()
int a = 10;
return 0;
}
Error:
It is because ++a returns an lvalue, which is basically a reference to the variable to which we can further
assign — just like an ordinary variable. It could also be assigned to a reference as follows:
Whereas if you recall how a++ works, it doesn’t immediately increment the value it holds. For clarity, you
can think of it as getting incremented in the next statement. So what basically happens is that, a++
returns an rvalue, which is basically just a value like the value of an expression that is not stored. You
can think of a++ = 20; as follows after being processed:
int a = 10;
10 = 20; // Invalid
// Value of a is incremented
a = a + 1;
That should help to understand why a++ = 20; won’t work. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer.
Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory
allocated on Stack (Refer to Memory Layout C Programs for details).
One use of dynamically allocated memory is to allocate memory of variable size, which is not
possible with compiler allocated memory except for variable-length arrays.
The most important use is the flexibility provided to programmers. We are free to allocate and
deallocate memory whenever we need it and whenever we don’t need it anymore. There are
many cases where this flexibility helps. Examples of such cases are Linked List, Tree, etc.
For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and deallocated.
For dynamically allocated memory like “int *p = new int[10]”, it is the programmer’s responsibility to
deallocate memory when no longer needed. If the programmer doesn’t deallocate memory, it causes
a memory leak (memory is not deallocated until the program terminates).
How is memory allocated/deallocated in C++?
C uses the malloc() and calloc() function to allocate memory dynamically at run time and uses a free()
function to free dynamically allocated memory. C++ supports these functions and also has two
operators new and delete, that perform the task of allocating and freeing the memory in a better and
easier way.
new operator
The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is
available, a new operator initializes the memory and returns the address of the newly allocated and
initialized memory to the pointer variable.
Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including
array or any user-defined data type including structure and class.
Example:
int *p = NULL;
p = new int;
OR
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 :
Example:
Allocate a block of memory: new operator is also used to allocate a block(an array) of memory of
type data-type.
Example:
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.
if (!p)
delete operator
Since it is the programmer’s responsibility to deallocate dynamically allocated memory, programmers are
provided delete operator in C++ language.
Syntax:
Here, pointer-variable is the pointer that points to the data object created by new.
Examples:
delete p;
delete q;
To free the dynamically allocated array pointed by pointer-variable, use the following form of delete:
// pointed by pointer-variable
delete[] pointer-variable;
Example:
// pointed by p.
delete[] p;
CPP
#include <iostream>
int main ()
int* p = NULL;
if (!p)
cout << "allocation of memory failed\n";
else
{
*p = 29;
}
int n = 5;
if (!q)
else
{
q[i] = i+1;
}
delete p;
delete r;
delete[] q;
return 0;
Output:
Value of p: 29
Value of r: 75.25
9. CHAR_BIT in C
CHAR_BIT : It is the number of bits in char. These days, almost all architectures use 8 bits per byte (But
it is not the case always, some older machines used to have 7-bit byte). It can be found in Let us see an
application of it. Suppose we wish to print byte by byte representation of an integer.
Examples :
Input : 4
Output : 00000000 00000000 00000000 00000100
Input : 12
Output : 00000000 00000000 00000000 00001100
CPP
Output :
00000000 00000000 00000000 00001100
Time Complexity : O(32)
Auxiliary Space : O(32)
#include <iostream>
using namespace std;
class student
{
private:
int roll;
public:
// constructor
student(int r):roll(r) {}
// A const function that changes roll with the help of const_cast
void fun() const
{
( const_cast <student*> (this) )->roll = 5;
}
int getRoll() { return roll; }
};
int main(void)
{
student s(3);
cout << "Old roll number: " << s.getRoll() << endl;
s.fun();
cout << "New roll number: " << s.getRoll() << endl;
return 0;
}
Output:
Old roll number: 3
New roll number: 5
2) const_cast can be used to pass const data to a function that doesn’t receive const. For example, in the
following program fun() receives a normal pointer, but a pointer to a const can be passed with the help of
const_cast.
#include <iostream>
using namespace std;
int fun(int* ptr)
{
return (*ptr + 10);
}
int main(void)
{
const int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast <int *>(ptr);
cout << fun(ptr1);
return 0;
}
Output:
20
3) It is undefined behavior to modify a value which is initially declared as const. Consider the following
program. The output of the program is undefined. The variable ‘val’ is a const variable and the call
‘fun(ptr1)’ tries to modify ‘val’ using const_cast.
#include <iostream>
using namespace std;
int fun(int* ptr)
{
*ptr = *ptr + 10;
return (*ptr);
}
int main(void)
{
const int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast <int *>(ptr);
fun(ptr1);
cout << val;
return 0;
}
Output:
Undefined Behavior
It it fine to modify a value which is not initially declared as const. For example, in the above program, if
we remove const from declaration of val, the program will produce 20 as output.
#include <iostream>
using namespace std;
int fun(int* ptr)
{
*ptr = *ptr + 10;
return (*ptr);
}
int main(void)
{
int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast <int *>(ptr);
fun(ptr1);
cout << val;
return 0;
}
4) const_cast is considered safer than simple type casting. It’safer in the sense that the casting won’t
happen if the type of cast is not same as original object. For example, the following program fails in
compilation because ‘int *’ is being typecasted to ‘char *’
#include <iostream>
using namespace std;
int main(void)
{
int a1 = 40;
const int* b1 = &a1;
char* c1 = const_cast <char *> (b1); // compiler error
*c1 = 'A';
return 0;
}
output:
prog.cpp: In function ‘int main()’:
prog.cpp:8: error: invalid const_cast from type 'const int*' to type 'char*'
5) const_cast can also be used to cast away volatile attribute. For example, in the following program, the
typeid of b1 is PVKi (pointer to a volatile and constant integer) and typeid of c1 is Pi (Pointer to integer)
#include <iostream>
#include <typeinfo>
using namespace std;
int main(void)
{
int a1 = 40;
const volatile int* b1 = &a1;
cout << "typeid of b1 " << typeid(b1).name() << '\n';
int* c1 = const_cast <int *> (b1);
cout << "typeid of c1 " << typeid(c1).name() << '\n';
return 0;
}
Output:
typeid of b1 PVKi
typeid of c1 Pi
Exercise
Predict the output of following programs. If there are compilation errors, then fix them.
Question 1
#include <iostream>
using namespace std;
int main(void)
{
int a1 = 40;
const int* b1 = &a1;
char* c1 = (char *)(b1);
*c1 = 'A';
return 0;
}
Question 2
#include <iostream>
using namespace std;
class student
{
private:
const int roll;
public:
// constructor
student(int r):roll(r) {}
// A const function that changes roll with the help of const_cast
void fun() const
{
( const_cast <student*> (this) )->roll = 5;
}
int getRoll() { return roll; }
};
int main(void)
{
student s(3);
cout << "Old roll number: " << s.getRoll() << endl;
s.fun();
cout << "New roll number: " << s.getRoll() << endl;
return 0;
}
1. Arrays in C/C++
Array
An array in C/C++ or be it in any programming language is a collection of similar data items stored at
contiguous memory locations and elements can be accessed randomly using indices of an array. They
can be used to store the collection of primitive data types such as int, float, double, char, etc of any
particular type. To add to it, an array in C/C++ can store derived data types such as structures, pointers
etc. Given below is the picture representation of an array.
Why do we need arrays?
We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to
store a large number of instances, it becomes difficult to manage them with normal variables. The idea of
an array is to represent many instances in one variable.
Advantages:-
Disadvantages:-
Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its size at
runtime.
There are various ways in which we can declare an array. It can be done by specifying its type and size,
initializing it or both.
C++
C
#include <iostream>
int main()
int arr1[10];
int n = 10;
int arr2[n];
return 0;
C++
C
#include <iostream>
int main()
return 0;
C++
C
#include <iostream>
int main()
{
// Array declaration by specifying size and initializing
// elements
// 0. above is same as "int arr[] = {10, 20, 30, 40, 0, 0}"
return 0;
1. Allows a fixed number of elements to be entered which is decided at the time of declaration.
Unlike a linked list, an array in C is not dynamic.
2. Insertion and deletion of elements can be costly since the elements are needed to be managed in
accordance with the new memory allocation.
C
C++
#include <stdio.h>
int main()
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3] = arr[0];
return 0;
Output
5 2 -10 5
C
C++
// is not checked in C.
#include <stdio.h>
int main()
int arr[2];
return 0;
Output
211343841 4195777
In C, it is not a compiler error to initialise an array with more elements than the specified size. For
example, the below program compiles fine and shows just a Warning.
C
#include <stdio.h>
int main()
{
return 0;
Warnings:
Note: The program won’t compile in C++. If we save the above program as a .cpp, the program
generates compiler error “error: too many initializers for ‘int [2]'”.
C
C++
// contiguous locations
#include <stdio.h>
int main()
int arr[5], i;
sizeof(int));
return 0;
Output
C++
C
#include<bits/stdc++.h>
int main()
int arr[6]={11,12,13,14,15,16};
// Way 1
for(int i=0;i<6;i++)
cout<<arr[i]<<" ";
cout<<endl;
// Way 2
for(int i=0;i<6;i++)
cout<<i[arr]<<" ";
cout<<endl;
return 0;
}
Output
11 12 13 14 15 16
By Other Method:
11 12 13 14 15 16
Array vs Pointers
Arrays and pointers are two different things (we can check by applying sizeof). The confusion happens
because the array name indicates the address of the first element and arrays are always passed as
pointers (even if we use a square bracket). Please see the Difference between pointer and array in C? for
more details.
What is a vector in C++?
A vector in C++ is a class in STL that represents an array. The advantages of vectors over normal arrays
are,
We do not need pass size as an extra parameter when we declare a vector i.e, Vectors support
dynamic sizes (we do not have to specify size of a vector initially). We can also resize a vector.
Vectors have many in-built functions like removing an element, etc.
2. Array of Strings
In C++, a string is usually just an array of (or a reference/points to) characters that ends with the NULL
character ‘\0‘. A string is a 1-dimensional array of characters and an array of strings is a 2-dimensional
array of characters.
Using Pointers
Using 2-D Array
Using the String Class
Using the Vector Class
Using the Array Class
1. Using Pointers
Pointers are the symbolic representation of an address. In simple words, a pointer is something that
stores the address of a variable in it. In this method, an array of string literals is created by an array of
pointers in which the character or string pointer points to the very first value of the created array and will
always point to it until it is traversed.
Example:
CPP
#include <iostream>
#include <stdio.h>
int main()
return 0;
Output:
Blue
Red
Orange
Yellow
The number of strings is fixed, but needn’t be. The 4 may be omitted, and the compiler will
compute the correct size.
These strings are constants and their contents cannot be changed. Because string literals
(literally, the quoted strings) exist in a read-only area of memory, we must specify “const” here to
prevent unwanted accesses that may crash the program.
2. Using a 2D array
A 2-D array is the simplest form of a multidimensional array in which it stores the data in a tabular form.
This method is useful when the length of all strings is known and a particular memory footprint is desired.
Space for strings will be allocated in a single block
Example:
CPP
// 2D character array
#include <iostream>
int main()
char colour[4][10]
return 0;
Output:
Blue
Red
Orange
Yellow
Both the number of strings and the size of strings are fixed. The 4, again, may be left out, and the
appropriate size will be computed by the compiler. The second dimension, however, must be
given (in this case, 10), so that the compiler can choose an appropriate memory layout.
Each string can be modified but will take up the full space given by the second dimension. Each
will be laid out next to each other in memory, and can’t change size.
Sometimes, control over the memory footprint is desirable, and this will allocate a region of
memory with a fixed, regular layout.
The STL string or string class may be used to create an array of mutable strings. In this method, the size
of the string is not fixed, and the strings can be changed which somehow makes it dynamic in nature
nevertheless std::string can be used to create a string array using in-built functions.
Example:
CPP
// array of strings.
#include <iostream>
#include <string>
int main()
std::string colour[4]
}
Output:
Blue
Red
Orange
Yellow
The array is of fixed size, but needn’t be. Again, the 4 here may be omitted, and the compiler will
determine the appropriate size of the array. The strings are also mutable, allowing them to be changed.
A vector is a dynamic array that doubles its size whenever a new character is added that exceeds its
limit. The STL container vector can be used to dynamically allocate an array that can vary in size.
This is only usable in C++, as C does not have classes. Note that the initializer-list syntax here requires a
compiler that supports the 2011 C++ standard, and though it is quite likely your compiler does, it is
something to be aware of.
CPP
#include <iostream>
#include <string>
#include <vector>
int main()
// syntax
"Orange" };
colour.push_back("Yellow");
Output:
Blue
Red
Orange
Yellow
Vectors are dynamic arrays, and allow you to add and remove items at any time.
Any type or class may be used in vectors, but a given vector can only hold one type.
An array is a homogeneous mixture of data that is stored continuously in the memory space. The
STL container array can be used to allocate a fixed-size array. It may be used very similarly to a vector,
but the size is always fixed.
Example:
C++
#include <array>
#include <iostream>
#include <string>
int main()
"Orange", "Yellow" };
return 0;
Output
Blue
Red
Orange
Yellow
These are by no means the only ways to make a collection of strings. C++ offers
several container classes, each of which has various tradeoffs and features, and all of them exist to fill
requirements that you will have in your projects. Explore and have fun!
Conclusion: Out of all the methods, Vector seems to be the best way for creating an array of Strings in
C++.
A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular
form. Data in multidimensional arrays are stored in row-major order.
data_type array_name[size1][size2]....[sizeN];
Examples:
Two-Dimensional Array
Two – dimensional array is the simplest form of a multidimensional array. We can see a two –
dimensional array as an array of one-dimensional array for easier understanding.
data_type array_name[x][y];
We can declare a two-dimensional integer array say ‘x’ of size 10,20 as:
int x[10][20];
Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and ‘j’ is
the column number.
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number
ranges from 0 to (x-1) and the column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3
rows and 3 columns is shown below:
Initializing Two – Dimensional Arrays: There are various ways in which a Two-Dimensional array can
be initialized.
First Method:
Second Method:
Third Method:
int x[3][4];
This type of initialization makes use of nested braces. Each set of inner braces represents one row. In
the above example, there is a total of three rows so there are three sets of inner braces.
Example:
int x[2][1];
The above example represents the element present in the third row and second column.
Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for row index 2 row
number is 2+1 = 3. To output all the elements of a Two-Dimensional array we can use nested for loops.
We will require two ‘for‘ loops. One to traverse the rows and another to traverse columns.
Example:
CPP
C
// Two-Dimensional array
#include<iostream>
int main()
{
{
}
}
return 0;
Output:
Element at x[0][0]: 0
Element at x[0][1]: 1
Element at x[1][0]: 2
Element at x[1][1]: 3
Element at x[2][0]: 4
Element at x[2][1]: 5
Three-Dimensional Array
Method 1:
Method 2(Better):
int x[2][3][4] =
};
CPP
C
// Array
#include <iostream>
int main()
int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },
{ { 6, 7 }, { 8, 9 }, { 10, 11 } } };
<< endl;
}
}
}
return 0;
Output:
Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11
In similar ways, we can create arrays with any number of dimensions. However, the complexity also
increases as the number of dimensions increases. The most used multidimensional array is the Two-
Dimensional Array.
A Literal is a constant variable whose value does not change during the lifetime of the program.
Whereas, a raw string literal is a string in which the escape characters like ‘ \n, \t, or \” ‘ of C++ are not
processed. Hence, a raw string literal that starts with R”( and ends in )”.
The syntax for Raw string Literal:
R "delimiter( raw_characters )delimiter" // delimiter is the end of logical entity
Here, delimiter is optional and it can be a character except the backslash{ / }, whitespaces{ }, and
parentheses { () }.
These raw string literals allow a series of characters by writing precisely its contents like raw character
sequence.
Example:
Ordinary String Literal
"\\\\n"
Raw String Literal
\/-- Delimiter
R"(\\n)"
/\-- Delimiter
Difference between an Ordinary String Literal and a Raw String Literal:
Ordinary String Literal Raw String Literal
It does not ignore any special meaning of character It ignores all the special characters like \n and \
and implements their special characteristic. t and treats them like normal text.
Output
Geeks.
For.
Geeks.
Geeks.\nFor.\nGeeks.\n
Given a string the task is to print all distinct sub-strings of length two in the given string. All substrings
should be printed in lexicographical order.
Examples:
Input: str = "abcab"
Output: ab-2
bc-1
ca-1
Input: str = "xyz"
Output: xy-1
yz-1
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
The idea of this article is to demonstrate map and pair in C++ STL.
We declare a map d_pairs that uses a character pair key and count as value. We iterate over the given
string from the starting index to store every consecutive pair if not present already and increment its
count in the map. After completion of the loop, we get all distinct consecutive pairs and their
corresponding occurrence count in the map container.
Please note that map is used as we need output in sorted order. We could use a unordered_map() if
output was not needed in sorted order. Time complexity of underdered_map() operations is O(1) while
that of map is O(Log n)
CPP
Output:
Distinct sub-strings with counts:
aa-1 ab-2 ac-4 as-1 ba-1 bc-1 ca-4 cd-1 dc-1 dd-1 ds-1 kl-1 la-1 sd-1 sk-1 ss-2
Converting numbers to string or vice-versa is actually a big paradigm shift in itself. In general or more
specifically in competitive programming there are many instances where we need to convert a number to
a string or string to a number. But lack of knowledge of certain essential tools binds us to do so. Some
methods to achieve this task are mentioned in this article.
There are 3 major methods to convert a number to a string, which are as follows:
In this method, a string stream declares a stream object which first inserts a number, as a stream into an
object and then uses “str()” to follow the internal conversion of a number to a string.
Example:
CPP
#include<iostream>
ostringstream str1;
// string
return 0;
Output
Time Complexity: O(n)
Auxiliary Space: O(n)
The function to_string() accepts a number(which can be any data type) and returns the number in the
desired string.
CPP
// C++ code to demonstrate "to_string()" method
#include <iostream>
// Driver Code
int main()
// to_string()
// to_string()
return 0;
Output
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar to string conversion, the ” lexical_cast() ” function remains the same, but in ‘boost lexical cast‘
time argument list modifies to “lexical_cast(numeric_var).
Example:
CPP
#include <iostream>
// Driver Code
int main()
return 0;
Output
C++
#include <iostream>
int main()
{
int n=12234;
char str[1000];
sprintf(str,"%d", n);
return 0;
Output
Time Complexity: O(n)
Auxiliary Space: O(n)
In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a
compile-time execution operator. We can find the size of an array using the sizeof() operator as shown:
Given an array (you don’t know the type of elements in the array), find the total number of elements in the
array without using the sizeof() operator?
CPP
#include <bits/stdc++.h>
// User defined sizeof macro
int main()
<< size;
return 0;
Output:
The following solution is very short when compared to the above solution. The number of elements in an
array A can be found using the expression:
CPP
// of an array by using a
// pointer hack
#include <bits/stdc++.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
return 0;
Output:
Here the pointer arithmetic does its part. We don’t need to explicitly convert each of the locations to
character pointers.
&arr – Pointer to an array of 6 elements. [See this for difference between &arr and arr]
(&arr + 1) – Address of 6 integers ahead as pointer type is a pointer to an array of 6 integers. In
simple words, (&arr + 1) is the address of integers ahead.
*(&arr + 1) – Same address as (&arr + 1), but type of pointer is “int *”.
*(&arr + 1) – arr – Since *(&arr + 1) points to the address 6 integers ahead of arr, the difference
between two is 6.
The reversing of a string is nothing but simply substituting the last element of a string to the 1st position
of the string.
CPP
// C++ program to reverse a string
// 'for' loop
#include <bits/stdc++.h>
int n = str.length();
// corners
// Driver program
int main()
reverseStr(str);
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
C++
#include <bits/stdc++.h>
int n = len-1;
int i = 0;
while(i<=n){
swap(str[i],str[n]);
n = n-1;
i = i+1;
}
// Driver program
int main()
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
C++
#include <bits/stdc++.h>
// Driver code
int main(void)
{
string s = "GeeksforGeeks";
reverse(s);
return (0);
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
C++
#include <bits/stdc++.h>
int n = len;
while(n--)
}
// Driver code
int main(void)
string s = "GeeksforGeeks";
reverse(s);
return (0);
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
2.
Recursion functions are used for iterating to different indexes of the string.
C++
// using recursion
#include <bits/stdc++.h>
if(n<=i){return;}
swap(str[i],str[n]);
reverseStr(str,n-1,i+1);
// Driver program
int main()
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
C++
#include <iostream>
{
return;
}
i++;
getreverse(str, i);
int main()
getreverse(name, 0);
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
There is a direct function in the “algorithm” header file for doing reverse that saves our time when
programming.
BidirectionalIterator end);
CPP
// reverse() function
#include <bits/stdc++.h>
int main()
reverse(str.begin(), str.end());
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
CPP
#include <bits/stdc++.h>
int main()
return 0;
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
CPP
// reversing of string
#include <bits/stdc++.h>
using namespace std;
int main()
int n = str.length();
string rev;
rev.push_back(str[i]);
return 0;
Output
skeeGrofskeeG
Complexity Analysis:
Auxiliary Space: O(1)
To get the reverse of a const string we have to first declare a ‘const string’ in a user-defined function
following which we have declared then use the following algorithm for the calling of the desired objects.
Example:
C++
// C++ program to get reverse of a const string
#include <bits/stdc++.h>
int n = strlen(str);
strcpy(rev, str);
// corners
swap(rev[i], rev[j]);
return rev;
// Driver code
int main(void)
{
printf("%s", reverseConstString(s));
return (0);
Output
skeeGrofskeeG
C++
#include <bits/stdc++.h>
int main()
string s = "GeeksforGeeks";
stack<char> st;
for (char x : s)
st.push(x);
while (!st.empty()) {
st.pop();
}
return 0;
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
Tokenizing a string denotes splitting a string with respect to some delimiter(s). There are many ways to
tokenize a string. In this article four of them are explained:
Using stringstream
A stringstream associates a string object with a stream allowing you to read from the string as if it were
a stream.
C++
#include <bits/stdc++.h>
int main()
stringstream check1(line);
string intermediate;
{
tokens.push_back(intermediate);
}
Output
GeeksForGeeks
is
must
try
Using strtok()
C++
// using strtok()
#include <stdio.h>
#include <string.h>
int main()
{
printf("%s\n", token);
}
return 0;
Output
Geeks
for
Geeks
C
#include <string.h>
#include <stdio.h>
// Driver function
int main()
char* tok;
while (tok != 0) {
}
return (0);
Output
Geeks
for
geeks
Contribute
Using strtok_r()
Just like strtok() function in C, strtok_r() does the same task of parsing a string into a sequence of
tokens. strtok_r() is a reentrant version of strtok().
C++
#include<stdio.h>
#include<string.h>
int main()
char *token;
char *rest = str;
printf("%s\n", token);
return(0);
Output
Geeks
for
Geeks
Using std::sregex_token_iterator
In this method the tokenization is done on the basis of regex matches. Better for use cases when multiple
delimiters are needed.
C++
#include <iostream>
#include <regex>
#include <string>
#include <vector>
/**
*
* @param str
* @param re
* @return std::vector<std::string>
*/
std::vector<std::string> tokenize(
str.end(), re, -1 };
tokenized.erase(
std::remove_if(tokenized.begin(),
tokenized.end(),
[](std::string const& s) {
return s.size() == 0;
}),
tokenized.end());
return tokenized;
// Driver Code
int main()
{
const std::string str = "Break string
a,spaces,and,commas";
tokenize(str, re);
return 0;
Output
Break
string
spaces
and
commas
Time Complexity: O(n * d) where n is the length of string and d is the number of delimiters.
Auxiliary Space: O(n)
The C++ getline() is a standard library function that is used to read a string or a line from an input stream.
It is a part of the <string> header. The getline() function extracts characters from the input stream and
appends it to the string object until the delimiting character is encountered. Must read the
article getline(string) in C++ for more details.
In C++, stream classes support line-oriented functions, getline() and write() to perform input and output
functions respectively.
Getline Character Array: This function reads the whole line of text that ends with a new line or until the
maximum limit is reached. getline() is the member function of istream class.
Syntax:
// (buffer, stream_size, delimiter)
Parameters:
Note: that the terminator(or delimiter) character can be any character (like ‘ ‘, ‘, ‘ or any special
character, etc.). The terminator character is read but not saved into a buffer, instead it is replaced by the
null character.
For Example:
CPP
// character array
#include <iostream>
// Driver Code
int main()
char str[20];
// in output
cin.getline(str, 20);
return 0;
Output
Explanation: In the above program, the statement cin.getline(str, 20); reads a string until it encounters
the new line character or the maximum number of characters (here 20). Try the function with different
limits and see the output.
Many of us have encountered error ‘cannot convert std::string to char[] or char* data type’.
Examples:
Output : char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
Method 1: A way to do this is to copy the contents of the string to char array. This can be done with the
help of c_str() and strcpy() function of library cstring.
The c_str() function is used to return a pointer to an array that contains a null terminated sequence of
character representing the current value of the string.
Syntax:
If there is an exception thrown then there are no changes in the string. But when we need to find or
access the individual elements then we copy it to a char array using strcpy() function. After copying it, we
can use it just like a simple array.
The length of the char array taken should not be less than the length of input string.
Implementation:
CPP
// CPP program to convert string
// to char array
#include <iostream>
#include <cstring>
// driver code
int main()
string s = "geeksforgeeks";
int n = s.length();
strcpy(char_array, s.c_str());
return 0;
Output
geeksforgeeks
Method 2:
CPP
// to char array
#include <iostream>
#include <string>
// driver code
int main()
string s("geeksforgeeks");
char p[s.length()];
int i;
p[i] = s[i];
}
return 0;
Output
geeksforgeeks
Time complexity: O(n)
Auxiliary Space: O(1)
Method 3:
This is the simplest and most efficient one. We can directly assign the address of 1st character of
the string to a pointer to char. This should be the preferred method unless your logic needs a copy of
the string.
C++14
#include <cstring>
#include <iostream>
#include <string>
// Driver Code
int main()
char* char_arr;
string str_obj("GeeksForGeeks");
char_arr = &str_obj[0];
return 0;
Output
GeeksForGeeks
Method 4:
C++14
// CPP program to convert string
// to char array
#include <iostream>
#include <cstring>
// driver code
int main()
string st = "GeeksForGeeks";
return 0;
Output
GeeksForGeeks
Output :
first string
first string
#####
string
first
Length of string is : 6
third character of string is : r
First char is : s, Last char is : g
string
string extension
string
str4 found in str6 at 0 pos
ext
extension
string nsion
strinion
These are test examples
As seen in the above code, we can get the length of the string by size() as well as length() but length() is
preferred for strings. We can concat a string to another string by += or by append(), but += is slightly
slower than append() because each time + is called a new string (creation of new buffer) is made which
is returned that is a bit overhead in case of many append operation.
Applications :
On basis of above string function some application are written below :
Output :
Floating part is : 342
string contains only digit
google%20com%20in
A dynamic array is an array that can grow, resize itself, contains a dynamic table, which is mutable in
nature, or an array list is randomly accessible, the variable-size list data structure that allows elements to
be added or removed.
Suppose we want to create a class for Graph. The class stores the adjacency matrix representation of
the graph.
Example:
CPP
class Graph
int V;
};
int main()
Output :
member 'Graph::V'.
Even if we make V static, we get the error “array bound is not an integer constant”.
C++ doesn’t allow to creation of a stack-allocated array in a class whose size is not constant. So we need
to dynamically allocate memory. Below is a simple program to show how to dynamically allocate a 2D
array in a C++ class using a class for Graph with adjacency matrix representation.
C++
#include <bits/stdc++.h>
// A Class to represent directed graph
class Graph {
bool** adj;
public:
void print();
};
Graph::Graph(int V)
this->V = V;
}
void Graph::print()
}
// Driver method
int main()
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.print();
return 0;
Output :
0110
0010
1001
0001
Note: memset() is used separately for individual rows. We can’t replace these calls with one call
because rows are allocated at different addresses and making a memset call would be disastrous.
Example:
A dynamic array is an array that can grow, resize itself, contains a dynamic table, which is mutable in
nature, or an array list is randomly accessible, the variable-size list data structure that allows elements to
be added or removed.
Suppose we want to create a class for Graph. The class stores the adjacency matrix representation of
the graph.
Example:
CPP
class Graph
int V;
int adj[V][V]; // This line doesn't work
};
int main()
Output :
member 'Graph::V'.
Even if we make V static, we get the error “array bound is not an integer constant”.
C++ doesn’t allow to creation of a stack-allocated array in a class whose size is not constant. So we need
to dynamically allocate memory. Below is a simple program to show how to dynamically allocate a 2D
array in a C++ class using a class for Graph with adjacency matrix representation.
C++
#include <bits/stdc++.h>
class Graph {
bool** adj;
public:
void print();
};
Graph::Graph(int V)
this->V = V;
}
}
void Graph::print()
}
// Driver method
int main()
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
g.print();
return 0;
}
Output :
0110
0010
1001
0001
Note: memset() is used separately for individual rows. We can’t replace these calls with one call
because rows are allocated at different addresses and making a memset call would be disastrous.
Example:
CPP
#include <iostream>
int main()
int a[10];
return 0;
Output:
40 8
The above output is for a machine where the size of an integer is 4 bytes and the size of a pointer is 8
bytes.
The cout statement inside main prints 40, and cout in findSize prints 8. The reason is, arrays are always
passed pointers in functions, i.e., findSize(int arr[]) and findSize(int *arr) mean exactly same thing.
Therefore the cout statement inside findSize() prints the size of a pointer. See this and this for details.
How to find the size of an array in function?
We can pass a ‘reference to the array’.
CPP
#include <iostream>
int main()
int a[10];
findSize(a);
return 0;
}
Output:
40 40
The above program doesn’t look good as we have a hardcoded size of the array parameter. We can do it
better using templates in C++.
CPP
#include <iostream>
int main()
int a[10];
findSize(a);
return 0;
Output:
40 40
We can make a generic function as well:
CPP
#include <iostream>
int main()
int a[10];
findSize(a);
float f[20];
findSize(f);
return 0;
Output:
40 40
80 80
Now the next step is to print the size of a dynamically allocated array. It’s your task man! I’m giving you a
hint.
CPP
#include <iostream>
#include <cstdlib>
int main()
return 0;
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list
of items from a file and we want individual items in an array.
Almost all programming languages, provide a function split a string by some delimiter.
In C:
C
// using strtok()
#include <stdio.h>
#include <string.h>
int main()
{
printf("%s\n", token);
}
return 0;
Output: Geeks
for
Geeks
Auxiliary Space: O(n)
In C++
Note: The main disadvantage of strtok() is that it only works for C style strings.
Many programmers are unaware that C++ has two additional APIs which are more elegant
Prerequisite: stringstream API
Stringstream object can be initialized using a string object, it automatically tokenizes strings on space
char. Just like “cin” stream stringstream allows you to read a string as a stream of words. Alternately, we
can also utilise getline function to tokenize string on any single character delimiter.
C++
#include <bits/stdc++.h>
void simple_tokenizer(string s)
stringstream ss(s);
string word;
}
// delimiter.
{
stringstream ss(s);
string word;
while (!ss.eof()) {
}
string b = "How$do$you$do!";
simple_tokenizer(a);
adv_tokenizer(b, '$');
return 0;
Output : How
do
you
do!
Prerequisite: find function and substr().
This method is more robust and can parse a string with any delimiter , not just spaces(though the
default behavior is to separate on spaces.) The logic is pretty simple to understand from the code below.
C++
#include <bits/stdc++.h>
do {
string a = "How$%do$%you$%do$%!";
tokenize(a, "$%");
return 0;
Output: Hi
do
you
do
If you are given that the length of the delimiter is 1, then you can simply use a temp string to split the
string. This will save the function overhead time in the case of method 2.
C++
#include <iostream>
// declaring temp string to store the curr "word" upto del
// If cur char is not del, then append it to the cur "word",
otherwise
// you have completed the word, print it, and start a new word.
if(str[i] != del){
temp += str[i];
}
else{
temp = "";
}
}
int main() {
split(str, del);
return 0;
Output
Auxiliary Space: O(n)
In Java :
In Java, split() is a method in String class.
Java
// using split()
import java.io.*;
{
System.out.println(val);
System.out.println("");
System.out.println(val);
}
Output:
Geeks
for-Geeks
Geeks
for
Geeks
In Python:
The split() method in Python returns a list of strings after breaking the given string by the specified
separator.
Python3
print(line.split())
Output:
['Geek1', 'Geek2', 'Geek3']
A stringstream associates a string object with a stream allowing you to read from the string as if it were a
stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is
extremely useful in parsing input.
Examples:
Examples:
C++
#include <iostream>
#include <sstream>
#include<string>
stringstream s(str);
string word;
int count = 0;
count++;
return count;
// Driver code
int main()
"contribution placements";
return 0;
Output
Examples:
C++
// of stringstream to count
// frequencies of words.
#include <bits/stdc++.h>
#include <iostream>
#include <sstream>
#include<string>
map<string, int>FW;
stringstream ss(st);
string Word;
FW[Word]++;
map<string, int>::iterator m;
// Driver code
int main()
printFrequency(s);
return 0;
Output
For-> 1
Geeks-> 2
Ide-> 1
strrchr() function
In C++, strrchr() is a predefined function used for string handling. cstring is the header file required for
string functions.
This function returns a pointer to the last occurrence of a character in a string.
The character whose last occurrence we want to find is passed as the second argument to the function
and the string in which we have to find the character is passed as the first argument to the function.
Syntax
char *strrchr(const char *str, int c)
Here, str is the string and c is the character to be located. It is passed as its int promotion, but it is
internally converted back to char.
Application
Given a string in C++, we need to find the last occurrence of a character, let’s say ‘a’.
Examples:
Input : string = 'This is a string'
Output :9
Input :string = 'My name is Ayush'
Output :12
Algorithm
1. Pass the given string in the strrchr() function and mention the character you need to point to.
2. The function returns a value, print the value.
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
CPP
Output:
9
C Examples :
C
Output:
String after last e is : eks
String after last m is : (null)
Practical Application: Since it returns the entire string after the last occurrence of a particular character,
it can be used to extract the suffix of a string. For e.g to know the entire leading zeroes in a
denomination when we know the first number. This example is demonstrated below.
C
Output:
The original string is : Rs 10000000
The denomination value is : 10000000
isspace() function In C++, isspace is a predefined function used for string and character
handling.cstring is the header file required for string functions and cctype is the headerfile required for
character functions. This function is used to check if the argument contains any whitespace characters.
There are many types of whitespace characters in c++ such as-
‘ ‘ – Space
‘\t’ – Horizontal tab
‘\n’ – Newline
‘\v’ – Vertical tab
‘\f’ – Feed
‘\r’ – Carriage return
Syntax :
int isspace(int x)
x : x is character to be checked
Application Given a string, we need to count the number of whitespace characters in the string using
isspace() function. Examples:
Output : 2
Output : 3
C++
C
// isspace() function
#include <iostream>
int main()
if (isspace(ch))
else
return 0;
Output :
Algorithm 1. Traverse the given string character by character upto its length, check if character is a
whitespace character. 2. If it is a whitespace character, increment the counter by 1, else traverse to the
next character. 3. Print the value of the counter.
C++
C
// isspace() function
#include <iostream>
ch = buf[0];
ch = buf[i];
if (isspace(ch))
count++;
i++;
}
return (count);
int main()
char ch;
int i = 0, count = 0;
// printing number of spaces
return 0;
Output:
CPP
#include <iostream>
#include <cstring>
#include <cctype>
int count = 0;
int c = str[i];
if (isspace(c))
count++;
}
cout << count;
// Driver Code
int main()
space(str);
return 0;
Output:
In this article, we are going to inspect three different ways of initializing strings in C++ and discuss
differences between them.
1. Using char*
Pros:
1. Only one pointer is required to refer to whole string. That shows this is memory efficient.
2. No need to declare the size of string beforehand.
CPP
#include <iostream>
int main()
return 0;
Output:
This is GeeksForGeeks
Cons:
1. This works fine in C but writing in this form is a bad idea in C++. That’s why compiler shows
warning of “deprecated conversion from string constant to ‘char*'” because in C string literals are
arrays of char but in C++ they are constant array of char. Therefore use const keyword before
char*.
1. We cannot modify the string at later stage in program. We can change str to point something else
but cannot change value present at str. Refer storage-for-strings-in-c for more detail.
CPP
#include <iostream>
int main()
// to 'char*'"
str[1] = 'o';
return 0;
1. Output:
Segmentation Fault
2. Using std::string
Syntax:
CPP
// std::string functions
#include <iostream>
int main()
string s1 = "Hello";
string s2 = "World";
s1 = s1 + s2;
s1.append("Geeks");
string s3 = "HelloWorldGeeks";
if (s1.compare(s3) == 0)
else
s1.insert(10, "For");
return 0;
Output:
HelloWorld
HelloWorldGeeks
true
Hello
HelloWorldForGeeks
Found at Position:5
HelloGeeksForGeeks
1. When dealing with lower level access like talking to the OS, but usually, if you’re passing the
string to the OS then std::string::c_str has it covered.
2. Compatibility with old C code (although std::string’s c_str() method handles most of this).
3. To conserve memory (std::string will likely have more overhead).
3. Using char[]
Syntax:
or
Pros:
CPP
// CPP program to illustrate char
#include <iostream>
int main()
str[1] = 'o';
return 0;
Output:
Hollo
Cons:
1. This is statically allocated sized array which consumes space in the stack.
2. We need to take the large size of array if we want to concatenate or manipulate with other strings
since the size of string is fixed. We can use C++ standard library cstring or string.h for that
purpose.
CPP
#include <iostream>
#include <cstring>
int main()
cout << "Before Concatenation : " << str << endl; // Hello
return 0;
1. Output:
CPP
#include <iostream>
#include <cstring>
int main()
char s2[50];
strcpy(s2, s1);
strcat(s2, s3);
else
char s5[30];
else
return 0;
Output :
Hello
HelloWorld
true
Hello
true
C++ STL offers many utilities to solve basic common life problems. Comparing values are always
necessary, but sometimes we need to compare the strings also. Therefore, lexicographical_compare()
is used to compare strings.
It is commonly used in dictionaries to arrange words alphabetically; it entails comparing elements that
have the same position in both ranges consecutively against each other until one element is not equal to
the other. The lexicographical comparison is the consequence of comparing these first non-matching
components. This function is defined in <algorithm> header.
Template:
template
while (beg1!=end1)
++beg1; ++beg2;
return (beg2!=end2);
Parameters:
Return value: Returns a boolean true, if range1 is strictly lexicographically smaller than range2 else
returns a false.
Example:
CPP
// lexicographical_compare(), implementation 1
#include <algorithm>
#include <iostream>
// Driver Code
int main()
two + 3))
"than gfg";
else
Output
Syntax 2:
lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2, Compare comp)
Template:
template
while (beg1!=end1)
{
if (beg2==end2 || *beg2<*beg1) return false;
++beg1; ++beg2;
return (beg2!=end2);
Parameters:
Return value: Returns a Boolean true, if range1 is strictly lexicographically smaller than range2 else
returns a false.
Example:
CPP
// lexicographical_compare()
#include <algorithm>
#include <iostream>
// Driver Code
int main()
// returns false as "g" has larger ASCII value than "G"
two + 3))
"than Gfg\n";
else
// lowercase
comp)) {
}
else {
cout << "geeksforgeeks is not lexicographically "
"less ";
}
Output
Application: Comparing strings can be generally used in dictionary, where we need to place words in
lexicographical order. An example of this can be to find the word which occurs 1st in the dictionary
among a given set of words.
CPP
// lexicographical_compare()
#include <bits/stdc++.h>
// Driver Code
int main()
if (lexicographical_compare(
min + strlen(min)))
strcpy(min, list[i]);
Output
Syntax 2:
For all strings, an index greater than or equal to length() as value is invalid.
If the caller ensures that the index is valid, she can use operator [], which is faster.
CPP
#include <iostream>
// Driver code
int main()
{
string str("GeeksForGeeks");
atDemo(str);
return 0;
Output:
Application
std::string::at can be used for extracting characters from string. Here is the simple code for the same.
CPP
#include <iostream>
char ch;
int l = str.length();
ch = str.at(i);
// Driver code
int main()
string str("GeeksForGeeks");
extractChar(str);
return 0;
Output:
GeeksForGeeks
In C++, std::substr() is a predefined function used for string handling. string.h is the header file required
for string functions. The substring function is used for handling string operations like strcat(), append(),
etc. It generates a new string with its value initialized to a copy of a sub-string of this object.
This function takes two values pos and len as an argument and returns a newly constructed string object
with its value initialized to a copy of a sub-string of this object. Copying of string starts from pos and is
done till pos+len means [pos, pos+len).
Important points:
Syntax:
Parameters:
Return value:
Example:
CPP
#include <string.h>
#include <iostream>
int main()
string s1 = "Geeks";
return 0;
Output
String is: ks
Time complexity: O(n)
Auxiliary Space: O(n)
Applications:
In this, a string and a character are given and you have to print the sub-string followed by the given
character.
Extract everything after the “:” in the string “dog:cat“.
Example:
C++
#include <string.h>
#include <iostream>
int main()
string s = "dog:cat";
return 0;
Output
String is: cat
Time complexity: O(n)
Auxiliary Space: O(n)
In this, a string and a character are given and you have to print the sub-string followed by the given
character.
Extract everything before the “:” in the string “dog:cat“.
Example:
CPP
#include <string.h>
#include <iostream>
int main()
string s = "dog:cat";
return 0;
}
Output
Time complexity: O(n)
Auxiliary Space: O(n)
Given a string as an input. We need to write a program that will print all non-empty substrings of that
given string.
Example:
C++
#include <bits/stdc++.h>
string s = "abcd";
subString(s, s.length());
return 0;
Output
ab
abc
abcd
bc
bcd
cd
Auxiliary Space: O(1)
Given an integer represented as a string, we need to get the sum of all possible substrings of this string.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
// integer digit
int n = num.length();
int sumofdigit[n];
sumofdigit[0] = toDigit(num[0]);
res += sumofdigit[i];
}
return res;
int main()
return 0;
Output
1670
Time Complexity: O(n)
Auxiliary Space: O(n)
Given an integer represented as a string, we need to get the maximum of all possible substrings of the
given string which is representing a number.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> v;
int x=stoi(sub);
v.push_back(x);
}
}
cout<<*max_element(v.begin(),v.end())<<endl;
int main()
string s = "823";
subString(s, s.length());
return 0;
Output :
823
Explanation: all substrings are {8,82,823,2,23,3} and the maximum value substring is 823.
Time complexity: O(n^3)
Auxiliary space: O(n!)
Example:
C++
#include <bits/stdc++.h>
vector<int> v;
int x=stoi(sub);
v.push_back(x);
}
}
cout<<*min_element(v.begin(),v.end())<<endl;
int main()
string s = "4572";
subString(s, s.length());
return 0;
}
Output:
Time complexity: O(N^3)
Auxiliary space: O(N!)
1. std::stol(): This function converts the string, provided as an argument in the function call, to
long int. It parses str interpreting its content as an integral number of the specified base, which
is returned as a value of type long int.
Syntax:
long int stol (const string& str, size_t* idx = 0, int base = 10)
Parameters: The function accepts three parameters which are described as below:
str: It specifies a string object with the representation of an integral number.
idx : It specifies a Pointer to an object of type size_t, whose value is set by the
function to position of the next character in str after the numerical value. The
parameter can also be a null pointer, in which case it is not used.
base : It specifies the numerical base to determine the number system in which the
characters are interpreted. If the base is 0, the base to be used is determined by
the format in the sequence. The default value is 10.
Return Value: The function returns the converted integral number as a value of type long int.
Output:
dec_num = 9876543210
hex_num = 16777215
binary_num = 127
2. std::stoll(): This function converts a string, provided as an argument in the function call, to
long long int. It parses str interpreting its content as an integral number of the specified base,
which is returned as a value of type long long int.
Syntax:
long long int stoll (const string& str, size_t* idx = 0, int base = 10)
Parameters: The function accepts three parameters which are described as below:
str: This parameter specifies the String object with the representation of an integral
number.
idx: This parameter specifies the Pointer to an object of type size_t, whose value is
set by the function to a position of the next character in str after the numerical
value. This parameter can also be a null pointer, in that case, it is not used.
base:This parameter specifies the Numerical base to determine the number system
in which the characters are interpreted. If the base is 0, the base used by it is
determined by the format in the sequence. The default base is 10.
Return Value: The function returns the converted integral number as a value of type long long
int.
Output:
dec_num = 9876543210
hex_num = 16777215
binary_num = 127
Errors and Exceptions: If no conversion could be performed, an invalid_argument exception is thrown.
If the value read is out of the range of representable values by a long int, either an invalid_argument or
an out_of_range exception is thrown.
// CPP code for illustration of stoll()
// function when invalid_argument
// exception is thrown.
#include <bits/stdc++.h>
using namespace std;
int main() {
// An invalid input string that has no
// integer part.
string invalid_num = "abcf$#@de";
// stoll() throws invalid_argument exception
// when conversion process fails.
try{
cout << stoll(invalid_num) << "\n";
}
// catch invalid_argument exception.
catch(const std::invalid_argument){
cerr << "Invalid argument" << "\n";
}
return 0;
}
Output:
Runtime Errors:
Invalid argument
Template :
OutputIterator result);
Parameters :
first1, last1
all the elements between first1 and last1, including the element
first2, last2
result
comp
Return Type :
CPP
// std :: set_symmetric_difference
// Driver code
int main()
std::vector<int> v(10);
return 0;
Output:
5 15 25 30 40 50
Template :
Parameters :
comp
Return Type :
CPP
// std :: set_symmetric_difference
// Custom function
{
return a < b;
// Driver code
int main()
std::vector<int> v(10);
return 0;
Output:
5 15 25 30 40 50
Possible Application: It is used to find the elements that are present in one container and not in another
container.
1. It is used to find the list of students that are not taking both classes. Students of both classes are
present in lists.
CPP
// std :: set_symmetric_difference
#include <bits/stdc++.h>
int main()
}
}
std::vector<string> result(10);
std::vector<string>::iterator it;
cout << "\n\nList of students that are not taking both classes :";
}
return 0;
OUTPUT :
Students attending second class are : Samir Junaid Manoj Pankaj Arpit
List of students that are not taking both classes :Junaid Pankaj Arpit Pranav Rajesh
2. It can also be used to find the numbers from both lists that are not present in both lists.
In C++, strchr() is a predefined function used for finding the occurrence of a character in a string. It is
present in cstring header file.
Syntax:
Note that c is passed as its int promotion, but it is internally treated as char.
Application
Given a string in c++, we need to find the first occurrence of a character, let’s say ‘a’.
Examples:
Algorithm:
1. Pass the given string in the strchr() function and mention the character you need to point.
2. The function returns a value, and print the value.
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
CPP
// in a given string.
#include <iostream>
#include <cstring>
int main()
return 0;
Output
strchr() function can also be used to check the presence of a character in a string. The input consists of
a character we want to check, if it exists in the string.
Example: Let’s check if the characters A and z are present in the string – “My name is Ayush”
Algorithm
1. Pass the given string in the strchr() function with the character as the second parameter and check if
the value returned is not null
2. If the function returns a NULL value, this means that the string does not contain the character, so, print
the required statement.
3. Else if the function does not returns a NULL value, this means that the string contains the character,
so, print the required statement.
CPP
#include <iostream>
#include <cstring>
// Driver code
int main()
else
else
return 0;
Output
A is present in string
strchr() function can be used to find absolute directory path for Linux: (Contributed
by Ekta_nehwal )
Examples:
Input : /home/test/sample
Output : /home/test
Algorithm:
1. Find the position of last “/” in the directory path by using strrchr.
2. Replace the occurrence with the NULL character.
Below is the implementation of the above algorithm, basically we are finding the position of / and then
changing it to \0(null).
C
#include <string.h>
#include<stdio.h>
int main()
char string[]={"/home/test/sample"};
int len;
char* pos;
len = strlen(string);
pos = strrchr(string,'/') ;
printf("%s\n",string);
*pos='\0';
printf("%s\n",string);
return 0;
Output
/home/test/sample
/home/test
strcat()
The strcat() function will append a copy of the source string to the end of destination string. The strcat()
function takes two arguments:
1) dest
2) src
It will append copy of the source string in the destination string. The terminating character at the end
of dest is replaced by the first character of src .
Return value: The strcat() function returns dest, the pointer to the destination string.
CPP
// strcat
#include <cstring>
#include <iostream>
int main()
{
char dest[50] = "This is an";
strcat(dest, src);
return 0;
Output:
This is an example
strncat()
The strncat() function in C++ appends the given number of character from one string to the end of
another string.The strncat() function will take these three arguments:
1) Dest
2) Src
3) Count
This will append the given number of characters from src string to the end of dest string. The
terminating character at the end of dest string will be replaced by the first character of src string .
Return value: The strncat() function returns dest, the pointer to the destination string.
CPP
// strncat
#include <cstring>
#include <iostream>
int main()
{
char dest[25] = "This is an example";
return 0;
Output:
It is recommended by many of the programmers that strncat() is safe as compared to strcat() because
strcat() does not check for the size of the copied data, and copies until it gets to a null terminator, it might
cause a buffer overflow while strncat() check for the size of the copied data, and will copy only ‘n’ bytes.
CPP
#include <stdio.h>
#include <string.h>
int main()
strcat(dest1, src);
return 0;
Output:
In C/C++, strncat() is a predefined function used for string handling. string.h is the header file required
for string functions.
This function appends not more than n characters from the string pointed to by src to the end of the string
pointed to by dest plus a terminating Null-character. The initial character of the string(src) overwrites the
Null-character present at the end of a string(dest). Thus, the length of the string(dest) becomes
strlen(dest)+n. But, if the length of the string(src) is less than n, only the content up to the terminating
null-character is copied and the length of the string(dest) becomes strlen(src) + strlen(dest).
The behavior is undefined if –
Syntax:
Return Value: The strncat() function shall return the pointer to the string(dest).
Application
Given two strings src and dest in C++, we need to append ‘n’ character from src to dest, let’s say n=5.
Examples:
dest = "abcd"
Output: "abcdefghi"
Program:
C++
C
#include <iostream>
int main()
return 0;
Output:
#include <cstring>
#include <iostream>
int main()
strcat(dest1, src);
return 0;
Output:
29. Strpbrk() in C
This function finds the first character in the string s1 that matches any character specified in s2 (It
excludes terminating null-characters).
Syntax :
char *strpbrk(const char *s1, const char *s2)
Parameters :
s1 : string to be scanned.
s2 : string containing the characters to match.
Return Value :
It returns a pointer to the character in s1 that
matches one of the characters in s2, else returns NULL.
Output:
Character not found
First matching character: e
Practical Application
This function can be used in game of lottery where the person having string with letter
coming first in victory wins, i.e. this can be used at any place where first person wins.
Output:
Better luck next time
Congrats u have won
strcoll() is a built-in library function and is declared in <string.h> header file. This function compares the
string pointed to by str1 with the one pointed by str2.The strcoll() function performs the comparison
based on the rules of the current locale’s LC_COLLATE category. Syntax:
Parameters: Function strcoll() takes two strings as parameters and returns an integer value.
Value Meaning
C++
C
#include <iostream>
#include <cstring>
int main()
char str1[13];
char str2[13];
int ret;
strcpy(str1, "GEEKSFORGEEKS");
strcpy(str2, "geeksforgeeks");
} else {
}
return 0;
C++
C
#include <iostream>
#include <cstring>
int main()
char str1[13];
char str2[13];
int ret;
strcpy(str1, "geeksforgeeks");
strcpy(str2, "GEEKSFORGEEKS");
} else {
return 0;
1. Output:
C++
C
#include <iostream>
#include <cstring>
int main()
char str1[13];
char str2[13];
int ret;
strcpy(str1, "GEEKSFORGEEKS");
strcpy(str2, "GEEKSFORGEEKS");
} else {
}
return 0;
Output:
strcpy() function
The strcpy() function is used to copy the source string to destination string. If the buffer size of
dest string is more than src string, then copy the src string to dest string with terminating NULL
character. But if dest buffer is less than src then it will copy the content without terminating NULL
character. The strings may not overlap, and the destination string must be large enough to
receive the copy.
Syntax:
Parameters: This function accepts two parameters as mentioned above and described below:
C++
C
// C++ Program to illustrate the
#include <iostream>
#include <cstring>
int main()
char dest[14];
strcpy(dest, src);
return 0;
Output:
C++
C
#include <iostream>
#include <cstring>
int main()
char dest[2];
strcpy(dest, src);
return 0;
Output:
strncpy() function
The strncpy() function is similar to strcpy() function, except that at most n bytes of src are
copied. If there is no NULL character among the first n character of src, the string placed in dest
will not be NULL-terminated. If the length of src is less than n, strncpy() writes an additional
NULL characters to dest to ensure that a total of n characters are written. Syntax:
Parameters: This function accepts three parameters as mentioned above and described below:
Example:
C++
C
#include <iostream>
#include <cstring>
int main()
char dest[14];
return 0;
Output:
Problem with strncpy(): If there is no null character among the first n character of src, the
string placed in dest will not be null-terminated. So strncpy() does not guarantee that the
destination string will be NULL terminated. The strlen() non-terminated string can cause segfault.
In other words, a non-terminated string in C/C++ is a time-bomb just waiting to destroy code.
C++
C
#include <iostream>
#include <cstring>
int main()
char dest[8];
cout << "Length of destination string: " << len << endl;
return 0;
Now, the next question is, any function that guarantees the destination string will be NULL-
terminated and no chance of buffer overrun? So, the answer of above question is “YES”, there
are several function in “stdio.h” library which guarantee the above condition will be satisfied.
snprintf
strlcpy
Both functions guarantee that the destination string will be NULL terminated.Similarly, snprintf()
function, strlcpy function copied at most dest_size-1 characters (dest_size is the size of the
destination string buffer) from src to dst, truncating src if necessary. The result is always null-
terminated. The function returns strlen(src). Buffer overflow can be checked as follows:
return -1;
Functions
1. Functions in C++
A function is a set of statements that take inputs, do some specific computation, and produce
output. The idea is to put some commonly or repeatedly done tasks together and make
a function so that instead of writing the same code again and again for different inputs, we can
call the function.
In simple terms, a function is a block of code that only runs when it is called.
Syntax:
Syntax of Function
Example:
C++
#include <iostream>
if (x > y)
return x;
else
return y;
// returns integer
int main()
return 0;
}
Output
m is 20
Functions make code modular. Consider a big file having many lines of code. It becomes
really simple to read and use the code if the code is divided into functions.
Function Declaration
A function declaration tells the compiler about the number of parameters function takes data-
types of parameters, and returns the type of function. Putting parameter names in the function
declaration is optional in the function declaration, but it is necessary to put them in the definition.
Below are an example of function declarations. (parameter names are not there in the below
declarations)
Function Declaration
Example:
C++
Types of Functions
Types of Function in C++
User Defined functions are user/customer-defined blocks of code specially customized to reduce
the complexity of big programs. They are also commonly known as “tailor-made functions”
which are built only to satisfy the condition in which the user is facing issues meanwhile reducing
the complexity of the whole program.
Library Function
Library functions are also called “builtin Functions“. These functions are a part of a compiler
package that is already defined and consists of a special function with special and different
meanings. Builtin Function gives us an edge as we can directly use them without defining them
whereas in the user-defined function we have to declare and define a function before using
them.
For Example: sqrt(), setw(), strcat(), etc.
The parameters passed to function are called actual parameters. For example, in the program
below, 5 and 10 are actual parameters.
The parameters received by the function are called formal parameters. For example, in the
above program x and y are formal parameters.
1. Pass by Value: In this parameter passing method, values of actual parameters are
copied to the 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 the
actual parameters of the caller.
2. Pass by Reference: Both actual and formal parameters refer to the same locations, so
any changes made inside the function are actually reflected in the actual parameters of
the caller.
Function Definition
Pass by reference is used where the value of x is not modified using the function fun().
C++
#include <iostream>
void fun(int x)
// definition of
// function
x = 30;
int main()
int x = 20;
fun(x);
return 0;
Output
x = 20
C++
#include <iostream>
int main()
int x = 20;
fun(&x);
return 0;
Output
x = 30
A copy of value is passed to the function An address of value is passed to the function
Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected
outside the function also
Actual and formal arguments will be created Actual and formal arguments will be created
in in
different memory location same memory location
1. Most C++ program has a function called main() that is called by the 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 the return
statement in the body of the 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:
C++
3. 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.
Main Function
The main function is a special function. Every C++ program must contain a function named
main. It serves as the entry point for the program. The computer will start running the code from
the beginning of the main function.
1. Without parameters:
CPP
// Without Parameters
CPP
// With Parameters
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 by a 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.
C++ Recursion
When function is called within the same function, it is known as recursion in C++. The function
which calls the same function, is known as recursive function.
A function that calls itself, and doesn’t perform any task after function call, is known as tail
recursion. In tail recursion, we generally call the same function with return statement.
Syntax:
C++
recursionfunction(){
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.
C++
C++
#include <iostream>
using namespace std;
int main()
min = arr[i];
}
}
cout << "Minimum element is: " << min << "\n";
Output
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload:
methods,
constructors and
indexed properties
Function overloading
Operator overloading
Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++. In function
overloading, the function is redefined by using either different types of arguments or a different
number of arguments. It is only through these differences compiler can differentiate between the
functions.
The advantage of Function overloading is that it increases the readability of the program
because you don’t need to use different names for the same action.
Example: changing number of arguments of add() method
C++
// vary
#include <iostream>
class Cal {
public:
{
return a + b + c;
}
};
int main(void)
{
Cal C; // class object declaration.
return 0;
Output
30
55
C++
// arguments.
#include <iostream>
int main()
return 0;
Output
r1 is : 42
r2 is : 0.6
When the compiler is unable to decide which function is to be invoked among the overloaded
function, this situation is known as function overloading.
When the compiler shows the ambiguity error, the compiler does not run the program.
Causes of Function Overloading:
Type Conversion.
Type Conversion:-
C++
#include <iostream>
void fun(int);
void fun(float);
void fun(int i)
}
void fun(float j)
int main()
fun(12);
fun(1.2);
return 0;
The above example shows an error “call of overloaded ‘fun(double)’ is ambiguous“. The fun(10)
will call the first function. The fun(1.2) calls the second function according to our prediction. But,
this does not refer to any function as in C++, all the floating point constants are treated as
double not as a float. If we replace float to double, the program works. Therefore, this is a type
conversion from float to double.
Function with Default Arguments:-
C++
#include <iostream>
void fun(int);
void fun(int i)
int main()
fun(12);
return 0;
The above example shows an error “call of overloaded ‘fun(int)’ is ambiguous“. The fun(int a, int
b=9) can be called in two ways: first is by calling the function with one argument, i.e., fun(12)
and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is
invoked with one argument. Therefore, the compiler could not be able to select among fun(int i)
and fun(int a,int b=9).
Function with Pass By Reference:-
C++
#include <iostream>
void fun(int);
void fun(int&);
int main()
int a = 10;
return 0;
}
void fun(int& b)
The above example shows an error “call of overloaded ‘fun(int&)’ is ambiguous“. The first
function takes one integer argument and the second function takes a reference parameter as an
argument. In this case, the compiler does not know which function is needed by the user as
there is no syntactical difference between the fun(int) and fun(int &).
2. Default Arguments
4. Inline Functions
8. Functors
3. Opaque Pointer
4. References
7. Smart Pointers
8. ‘this’ pointer
15. nullptr
2. malloc() vs new
4. Std::get_temporary_buffer in C++
4. Access Modifiers
5. Inheritance
6. Polymorphism
7. Encapsulation
8. Data Abstraction
9. Structure vs class
1. Constructors
2. Copy Constructor
3. Destructors
Function Overloading
1. Function Overloading
1. Operator Overloading
5. Conversion Operators
Virtual Functions
5. Virtual Destructor
6. Virtual Constructor
Exception Handling
2. Stack Unwinding
Namespace
Algorithms
1. Introduction to STL
2. Sorting
3. Searching
Containers:
1. Pair (Practice)
2. Vector (Practice)
Sorting 2D Vector in C++ | Set 3 (By number of columns) ,(Sort in descending order by first
and second)
Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)
Sorting 2D Vector in C++ | Set 1 (By row and column) , (Sort by first and second)
8. Queue (Practice)
13. Stack (Practice)
18. Set (Practice)
40. Multiset
41. Map (Practice)
Multimap
CPP-Math
More:
2. Strand sort
6. Template Specialization
Inheritance
What all is inherited from parent class in C++?
What happens when more restrictive access is given to a derived class method in C++?
C++ Library
10. Chrono
36. Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())
39. Merge operations using STL in C++ (merge, includes, set_union, set_intersection,
set_difference, ..)
42. numeric header in C++ STL | Set 1 (accumulate() and partial_sum()) , Set 2 (adjacent_difference(),
inner_product() and iota())
45. Tuples
C++ Advanced
4. Copy-and-Swap Idiom
6. Lambda expression
3. searching in fork()
5. Cin-Cout vs Scanf-Printf
Puzzles
9. Print a number 100 times without using loop, recursion and macro expansion in C++
17. How to swap two variables in one line in C/C++, Python and Java?
Interview Questions
Quick Links: