Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
445 views

Empty File

This document provides an overview of the basics of C++ programming, including setting up a development environment, writing a simple "Hello World" program, and explaining key elements of that program. It then discusses various C++ concepts like data types, variables, and the differences between local, instance, and static variables. The key points are: 1. It describes how to install Code::Blocks IDE on Windows and write a basic "Hello World" program to print text to the screen. 2. It explains each line of the "Hello World" program, covering concepts like comments, headers, namespaces, main functions, and input/output streams. 3. It discusses C++ variable types like local, instance

Uploaded by

Loser To Winner
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
445 views

Empty File

This document provides an overview of the basics of C++ programming, including setting up a development environment, writing a simple "Hello World" program, and explaining key elements of that program. It then discusses various C++ concepts like data types, variables, and the differences between local, instance, and static variables. The key points are: 1. It describes how to install Code::Blocks IDE on Windows and write a basic "Hello World" program to print text to the screen. 2. It explains each line of the "Hello World" program, covering concepts like comments, headers, namespaces, main functions, and input/output streams. 3. It discusses C++ variable types like local, instance

Uploaded by

Loser To Winner
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 311

C++ PROGRAMMING LANGUAGE

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)

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


  
// Header file for input output functions
#include <iostream>
using namespace std;
  
// Main() function: where the execution of program begins
int main()
{
    // prints hello world
    cout << "Hello World";
  
    return 0;
}

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.

// C++ program to show that scope resolution operator :: is used


// to define a function outside a class
#include<iostream> 
using namespace std;
  
class A 
{
public: 
  
   // Only declaration
   void fun();
};
  
// Definition outside class using ::
void A::fun()
{
   cout << "fun() called";
}
  
int main()
{
   A a;
   a.fun();
   return 0;
}

3) To access a class’s static variables.

// C++ program to show that :: can be used to access static


// members when there is a local variable with same name
#include<iostream>
using namespace std;
   
class Test
{
    static int x;  
public:
    static int y;   
  
    // Local parameter 'a' hides class member
    // 'a', but we can access it using ::
    void func(int x)  
    { 
       // We can access class's static variable
       // even if there is a local variable
       cout << "Value of static x is " << Test::x;
  
       cout << "\nValue of local x is " << x;  
    }
};
   
// In C++, static members must be explicitly defined 
// like this
int Test::x = 1;
int Test::y = 2;
   
int main()
{
    Test obj;
    int x = 3 ;
    obj.func(x);
   
    cout << "\nTest::y = " << Test::y;
  
    return 0;
}

Output:
Value of static x is 1
Value of local x is 3
Test::y = 2;

4) In case of multiple Inheritance:


If same variable name exists in two ancestor classes, we can use scope resolution operator to
distinguish.

// Use of scope resolution operator in multiple inheritance.


#include<iostream>
using namespace std;
  
class A
{
protected:
    int x;
public:
    A() { x = 10; }
};
  
class B
{
protected:
    int x;
public:
    B() { x = 20; }
};
  
class C: public A, public B
{
public:
   void fun()
   {
      cout << "A's x is " << A::x;
      cout << "\nB's x is " << B::x;
   }
};
  
int main()
{
    C c;
    c.fun();
    return 0;
}

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

// Use of scope resolution operator for namespace.


#include<iostream>
  
  
int main(){
    std::cout << "Hello" << std::endl;
  
}

Here, cout and endl belong to the std namespace.


6) Refer to a class inside another class:
If a class exists inside another class we can use the nesting class to refer the nested class using the
scope resolution operator

// Use of scope resolution class inside another class.


#include<iostream>
using namespace std;
  
class outside
{
public:
      int x;
      class inside
      {
      public:
            int x;
            static int y; 
            int foo();
  
      };
};
int outside::inside::y = 5; 
  
int main(){
    outside A;
    outside::inside B;
  
}

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

Data types in C++ are mainly divided into three types: 


1. Primitive Data Types: These data types are built-in or predefined data types and can be used directly
by the user to declare variables. example: int, char, float, bool, etc. Primitive data types available in C++
are: 
 Integer
The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and
range from -2147483648 to 2147483647.  
 Character
Character data type is used for storing characters. The keyword used for the character data type is char.
Characters typically require 1 byte of memory space and range from -128 to 127 or 0 to 255.  
 Boolean
Boolean data type is used for storing Boolean or logical values. A Boolean variable can store
either true  or false. The keyword used for the Boolean data type is bool. 
 Floating Point
Floating Point data type is used for storing single-precision floating-point values or decimal values. The
keyword used for the floating-point data type is float. Float variables typically require 4 bytes of memory
space. 
 Double Floating Point
Double Floating Point data type is used for storing double-precision floating-point values or decimal
values. The keyword used for the double floating-point data type is double. Double variables typically
require 8 bytes of memory space.
 Valueless or Void
Void means without any value. void data type represents a valueless entity. A void data type is used for
those function which does not return a value. 
 Wide Character
Wide character data type is also a character data type but this data type has a size greater than the
normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4 bytes long.
Note: sizeof operator — sizeof operator is used to find the number of bytes occupied by a variable/data
type in computer memory
Datatype Modifiers
As the name suggests, datatype modifiers are used with the built-in data types to modify the length of
data that a particular data type can hold. 
Data type modifiers available in C++ are: 
 Signed
 Unsigned
 Short
 Long
The below table summarizes the modified size and range of built-in datatypes when combined with the
type modifiers:
Data Type Size (in bytes) Range

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

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

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

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

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

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

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

signed char 1 -128 to 127

unsigned char 1 0 to 255

Float 4  

Double 8  

long double 12  
Data Type Size (in bytes) Range

wchar_t 2 or 4 1 wide character

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.

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


1. iostream: iostream stands for standard input-output stream. This header file contains
definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods declared in these files
are used for manipulating streams. This file contains definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is used to handle
the data being read from a file as input or data being written into the file as output.
The two instances cout in C++ and cin in C++ of iostream class are used very often for printing outputs
and taking inputs respectively. These two are the most basic methods of taking input and printing output
in C++. To use cin and cout in C++ one must include the header file iostream in the program.
This article mainly discusses the objects defined in the header file iostream like the cin and cout.  
 Standard output stream (cout): Usually the standard output device is the display screen.
The C++ cout statement is the instance of the ostream class. It is used to produce output on
the standard output device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout) using the insertion
operator(<<).
 standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin
statement is the instance of the class istream and is used to read input from the standard input
device which is usually a keyboard. 
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.
 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)
 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.
endl vs \n in C++
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; 
Some other differences between endl and \n are:  
endl  \n 

It is a manipulator.  It is a character.

It doesn’t occupy any memory.  It occupies 1 byte memory as 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 is only supported by C++.  It is supported in both C and C++.

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

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

[] Brackets (array subscript) left-to-right

. Member selection via object name left-to-right

-> Member selection via a pointer left-to-right

1 a++/a– Postfix increment/decrement (a is a variable) left-to-right

2 ++a/–a Prefix increment/decrement (a is a variable) right-to-left

+/- Unary plus/minus right-to-left

!~ Logical negation/bitwise complement right-to-left

(type) Cast (convert value to temporary value of type) right-to-left


Precedence Operator Description Associativity

* Dereference right-to-left

& Address (of operand) right-to-left

sizeof Determine size in bytes on this implementation right-to-left

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

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

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

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

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

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

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

= Assignment right-to-left

+= , -= Addition/subtraction assignment right-to-left

*= , /= Multiplication/division assignment right-to-left

%= , &= Modulus/bitwise AND assignment right-to-left

^= , |= Bitwise exclusive/inclusive OR assignment right-to-left

14 <>= Bitwise shift left/right assignment right-to-left

15 , expression separator left-to-right


9. Loops (Practice)
In programming, sometimes there is a need to perform some operation more than once or (say) n
number of times. Loops come into use when we need to repeatedly execute a block of statements. 

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.

3. do-while – firstly, execute the body then condition check

 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;

case value2: statement_2; break;


.....
......
......
case value_n: statement_n; break;
default: default statement;

}
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: 

14. Functions in C++(Practice)


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:
Why Do We Need Functions?
 Functions help us in reducing code redundancy. If functionality is performed at multiple
places in software, then rather than writing the same code, again and again, we create a
function and call it everywhere. This also helps in maintenance as we have to change at one
place if we make future changes to the functionality.
 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.
 Functions provide abstraction. For example, we can use library functions without worrying
about their internal work.
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) 

Types of Functions

Types of Function in C++


User Defined Function
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.
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. 

There are two most popular ways to pass 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++

// C++ Program to demonstrate function definition


#include <iostream>
using namespace std;
 
void fun(int x)
{
    // definition of
    // function
    x = 30;
}
 
int main()
{
    int x = 20;
    fun(x);
    cout << "x = " << x;
    return 0;
}

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

// C++ Program to demonstrate working of


// function using pointers
#include <iostream>
using namespace std;
 
void fun(int* ptr) { *ptr = 30; }
 
int main()
{
    int x = 20;
    fun(&x);
    cout << "x = " << x;
 
    return 0;
}

Output
x = 30
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++

void function name(int a)


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

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.
 

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:-
 Code Optimization:  we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.
 
Disadvantages:-
 Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its size at
runtime. 
 
Array declaration in C/C++: 

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.
 

No Index Out of bound Checking: 


There is no index out of bounds checking in C/C++, for example, the following program compiles fine but
may produce unexpected output when run.  
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.
16. Strings in C++(Practice)
In C++ we can store string by one of the two ways –
1. C style strings
In C, a string can be referred to either using a character pointer or as a character array. 
Strings as character arrays  
C

char str[4] = "GfG"; /*One extra for string terminator*/


/*    OR    */
char str[4] = {‘G’, ‘f’, ‘G’, '\0'}; /* '\0' is string terminator */

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

char *str  =  "GfG";  

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';  

2. string class (discussed in this post)


In this post, the second method is discussed. string class is part of C++ library that supports a lot much
functionality over C style strings.
C++ string class internally uses char array to store character but all memory management, allocation,
and null termination is handled by string class itself that is why it is easy to use. The length of the C++
string can be changed at runtime because of dynamic allocation of memory similar to vectors. As string
class is a container class, we can iterate over all its characters using an iterator similar to other
containers like vector, set and maps, but generally, we use a simple for loop for iterating over the
characters and index them using the [] operator.
17. Pointers in C++(Practice)
Pointers store address of variables or a memory location. 
 
// General syntax
datatype *var_name;
// An example pointer "ptr" that holds
// address of an integer variable or holds
// address of a memory whose value(s) can
// be accessed as integer values through "ptr"
int *ptr;
Using a Pointer:
To use pointers in C, we must understand below two operators. 
 
 To access address of a variable to a pointer, we use the unary operator & (ampersand) that
returns the address of that variable. For example &x gives us address of variable x. 
One more operator is unary * (Asterisk) which is used for two things : 
 To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a *
before its name. 
To access the value stored in the address we use the unary operator (*) that returns the value of the
variable located at the address specified by its operand. This is also called Dereferencing.
Below is pictorial representation of above program:

Pointer Expressions and Pointer Arithmetic 


A limited set of arithmetic operations can be performed on pointers. A pointer may be: 
 
 incremented ( ++ )
 decremented ( — )
 an integer may be added to a pointer ( + or += )
 an integer may be subtracted from a pointer ( – or -= )
Pointer arithmetic is meaningless unless performed on an array. 
Note : Pointers contain addresses. Adding two addresses makes no sense, because there is no idea
what it would point to. Subtracting two addresses lets you compute the offset between these two
addresses.
 

Array Name as Pointers 


An array name acts like a pointer constant. The value of this pointer constant is the address of the first
element. 
For example, if we have an array named val then val and &val[0] can be used interchangeably. 
Pointers and Multidimensional Arrays 
Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration 
 
int nums[2][3] = { {16, 18, 20}, {25, 26, 27} };
In general, nums[i][j] is equivalent to *(*(nums+i)+j)
 
Pointer Notation Array Notation Value

*(*nums) nums[0][0] 16

*(*nums + 1) nums[0][1] 18

*(*nums + 2) nums[0][2] 20

*(*(nums + 1)) nums[1][0] 25

*(*(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.
}

 References are less powerful than pointers


1) Once a reference is created, it cannot be later made to reference another object; it cannot
be reset. This is often done with pointers. 
2) References cannot be NULL. Pointers are often made NULL to indicate that they are not
pointing to any valid thing. 
3) A reference must be initialized when declared. There is no such restriction with pointers.
Due to the above limitations, references in C++ cannot be used for implementing data
structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and
can be used to implement all data structures. References being more powerful in Java is the
main reason Java doesn’t need pointers.
 
 References are safer and easier to use: 
1) Safer: Since references must be initialized, wild references like wild pointers are unlikely to
exist. It is still possible to have references that don’t refer to a valid location (See questions 5
and 6 in the below exercise) 
2) Easier to use: References don’t need a dereferencing operator to access the value. They
can be used like normal variables. ‘&’ operator is needed only at the time of declaration. Also,
members of an object reference can be accessed with dot operator (‘.’), unlike pointers where
arrow operator (->) is needed to access members.
 
 Together with the above reasons, there are few places like the copy constructor argument
where pointer cannot be used. Reference must be used to pass the argument in the copy
constructor. Similarly, references must be used for overloading some operators like ++.
19. Introduction to OOP in C++
Object-oriented programming – As the name suggests uses objects in programming. Object-oriented
programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in
programming. The main aim of OOP is to bind together the data and the functions that operate on them
so that no other part of the code can access this data except that function.
Characteristics of an Object Oriented Programming language
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.
 A Class is a user-defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions define
the properties and behaviour of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc and
member functions can apply brakes, increase speed etc.
We can say that a Class in C++ is a blue-print representing a group of objects which shares some
common properties and behaviours.
Object: An Object is an identifiable entity with some characteristics and behaviour. An Object is an
instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.

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

1. C program that won’t compile in C++

2. Undefined Behaviour in C and C++

3. Name Mangling and extern “C” in C++

4. void * in C vs C++

5. Program that produces different results


in C and C++

6. Type difference of character literals in C vs C++

7. Difference between Structures in C and C++

C++ vs Java

1. Inheritance in C++ vs Java

2. static keyword in C++ vs Java

3. default virtual behavior in C++ vs Java

4. Exception Handling in C++ vs Java

5. Foreach in C++ vs Java

6. Templates in C++ vs Generics in Java

7. Floating Point Operations & Associativity in C, C++ and Java

8. Similarities between Java and C++


Input and output

1. I/O Redirection in C++

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

For Example, to redirect the stdout to say a textfile, we could write :

freopen ("text_file.txt", "w", stdout);

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

 ostream : These objects can only be used for output operations.

 iostream : Can be used for both input and output operations

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

1. Get the stream buffer of A and store it somewhere

2. Set the stream buffer of A to the stream buffer of B

3. If needed to reset the stream buffer of A to its previous stream buffer

We can use the function ios::rdbuf() to perform below two operations. 

1) stream_object.rdbuf(): Returns pointer to the stream buffer of stream_object

2) stream_object.rdbuf(streambuf * p): Sets the stream buffer to the object pointed by p

Here is an example program below to show the steps 

 CPP

// Cpp program to redirect cout to a file


#include <fstream>

#include <iostream>

#include <string>

using namespace std;

int main()

    fstream file;

    file.open("cout.txt", ios::out);

    string line;

    // Backup streambuffers of  cout

    streambuf* stream_buffer_cout = cout.rdbuf();

    streambuf* stream_buffer_cin = cin.rdbuf();

    // Get the streambuffer of the file

    streambuf* stream_buffer_file = file.rdbuf();

    // Redirect cout to file

    cout.rdbuf(stream_buffer_file);

    cout << "This line written to file" << endl;

    // Redirect cout back to screen

    cout.rdbuf(stream_buffer_cout);

    cout << "This line is written to screen" << endl;


 

    file.close();

    return 0;

Output: 

This line is written to screen

Contents of file cout.txt:

This line written to file

Time Complexity: O(1)

Space Complexity: O(1)

Note: 
The above steps can be condensed into a single step 

auto cout_buf = cout.rdbuf(file.rdbuf())

// sets couts streambuffer and returns the old

streambuffer back to cout_buf

2. Clearing The Input Buffer

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.

How does it affect Programming? 


On various occasions, you may need to clear the unwanted buffer so as to get the next input in the
desired container and not in the buffer of the previous variable. For example, in the case of C after
encountering “scanf()”, if we need to input a character array or character, and in the case of C++, after
encountering the “cin” statement, we require to input a character array or a string, we require to clear the
input buffer or else the desired input is occupied by a buffer of the previous variable, not by the desired
container. On pressing “Enter” (carriage return) on the output screen after the first input, as the buffer of
the previous variable was the space for a new container(as we didn’t clear it), the program skips the
following input of the container.

In the case of C Programming 

 C

// C Code to explain why not


// clearing the input buffer

// causes undesired outputs

#include<stdio.h>

int main()

    char str[80], ch;

     

    // Scan input from user -

    // GeeksforGeeks for example

    scanf("%s", str);

     

    // Scan character from user-

    // 'a' for example

    ch = getchar();

     

    // Printing character array,

    // prints “GeeksforGeeks”)

    printf("%s\n", str);

     

    // This does not print

    // character 'a'

    printf("%c", ch);

     

    return 0;

Input: 

GeeksforGeeks

a
Output: 

GeeksforGeeks

Time Complexity: O(1) 

In the case of C++ 

 C++

// C++ Code to explain why

// not clearing the input

// buffer causes undesired

// outputs

#include<iostream>

#include<vector>

using namespace std;

int main()

    int a;

    char ch[80];

     

    // Enter input from user

    // - 4 for example

    cin >> a;

     

    // Get input from user -

    // "GeeksforGeeks" for example

    cin.getline(ch,80);

     

    // Prints 4

    cout << a << endl;


     

    // Printing string : This does

    // not print string

    cout << ch << endl;

     

    return 0;

Input: 

GeeksforGeeks

Output: 

Time Complexity: O(1)

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.

How can it be resolved?

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

// C Code to explain why adding

// "while ( (getchar()) != '\n');"

// after "scanf()" statement

// flushes the input buffer

#include<stdio.h>

int main()
{

    char str[80], ch;

     

    // scan input from user -

    // GeeksforGeeks for example

    scanf("%s", str);

     

    // flushes the standard input

    // (clears the input buffer)

    while ((getchar()) != '\n');

     

    // scan character from user -

    // 'a' for example

    ch = getchar();

     

    // Printing character array,

    // prints “GeeksforGeeks”)

    printf("%s\n", str);

     

    // Printing character a: It

    // will print 'a' this time

    printf("%c", ch);

    return 0;

Input: 

GeeksforGeeks

a
Output: 

GeeksforGeeks

Time Complexity: O(n), where n is the size of the string. 

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.

In the case of C++ :  

1. Using “ cin.ignore(numeric_limits::max(),’\n’); ” :- Typing “cin.ignore(numeric_limits::max(),’\n’);”


after the “cin” statement discards everything in the input stream including the newline. 

 C++

// C++ Code to explain how

// "cin.ignore(numeric_limits

// <streamsize>::max(),'\n');"

// discards the input buffer

#include<iostream>

// for <streamsize>

#include<ios>    

// for numeric_limits

#include<limits>

using namespace std;

int main()

    int a;

    char str[80];

     

    // Enter input from user


    // - 4 for example

    cin >> a;

     

    // discards the input buffer

    cin.ignore(numeric_limits<streamsize>::max(),'\n');

     

    // Get input from user -

    // GeeksforGeeks for example

    cin.getline(str, 80);

     

    // Prints 4

    cout << a << endl;

     

    // Printing string : This

    // will print string now

    cout << str << endl;

    return 0;

Input: 

GeeksforGeeks

Output: 

GeeksforGeeks

Time Complexity: O(1) 

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

// C++ Code to explain how " cin.sync();"

// discards the input buffer

#include<iostream>

#include<ios>    

#include<limits>

using namespace std;

int main()

    int a;

    char str[80];

     

    // Enter input from user

    // - 4 for example

    cin >> a;

     

    // Discards the input buffer

    cin.sync();

     

    // Get input from user -

    // GeeksforGeeks for example

    cin.getline(str, 80);

     

    // Prints 4

    cout << a << endl;

     

    // Printing string - this


    // will print string now

    cout << str << endl;

    return 0;

Input: 

GeeksforGeeks

Output: 

Time Complexity: O(1) 

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

// C++ Code to explain how "cin >> ws"

// discards the input buffer along with

// initial white spaces of string

#include<iostream>

#include<vector>

using namespace std;

int main()

    int a;

    string s;

     
    // Enter input from user -

    // 4 for example

    cin >> a;

     

    // Discards the input buffer and

    // initial white spaces of string

    cin >> ws;

     

    // Get input from user -

    // GeeksforGeeks for example

    getline(cin, s);

     

    // Prints 4 and GeeksforGeeks :

    // will execute print a and s

    cout << a << endl;

    cout << s << endl;

    return 0;

Input: 

GeeksforGeeks

Output: 

GeeksforGeeks

Time Complexity: O(1) 

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.

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


1. iostream: iostream stands for standard input-output stream. This header file contains
definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods declared in these files
are used for manipulating streams. This file contains definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is used to handle
the data being read from a file as input or data being written into the file as output.
The two instances cout in C++ and cin in C++ of iostream class are used very often for printing outputs
and taking inputs respectively. These two are the most basic methods of taking input and printing output
in C++. To use cin and cout in C++ one must include the header file iostream in the program.
This article mainly discusses the objects defined in the header file iostream like the cin and cout.  
 Standard output stream (cout): Usually the standard output device is the display screen.
The C++ cout statement is the instance of the ostream class. It is used to produce output on
the standard output device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout) using the insertion
operator(<<).
 C++

#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

4. cout << endl vs cout << “\n” in C++

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; 

Some other differences between endl and \n are:  

endl  \n 

It is a manipulator.  It is a character.

It doesn’t occupy any memory.  It occupies 1 byte memory as 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 is only supported by C++.  It is supported in both C and C++.

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>

using namespace std;

int main() {

    cout << "GFG!"<<endl;  //We can use endl in C++ and it doesn't
occupy any memory

      cout << "GFG!";

    return 0;

//Code submitted by Susobhan AKhuli

Output:

GFG!

GFG!

Example 2:

We can use “\n” in both C and C++ but it occupies 1 byte memory.

 C++
 C
#include <iostream>

using namespace std;

int main() {

    cout << "GFG!"<<"\n";

      cout << "GFG!";

    return 0;

//Code submitted by Susobhan AKhuli

Output:

GFG!

GFG!

5. Problem with scanf() when there is fgets()/gets()/scanf() after it

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

// C program to demonstrate the problem when

// fgets()/gets() is used after scanf()

#include <stdio.h>
  

int main()

    int x;

    char str[100];

    scanf("%d", &x);

    fgets(str, 100, stdin);

    printf("x = %d, str = %s", x, str);

    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.

2) The similar problem occurs when scanf() is used in a loop. 

Input:

 C

// C program to demonstrate the problem when

// scanf() is used in a loop

#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);

    } while (c != 'q');

    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.

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.

The corrected programs for the above points will be,

1) scanf() when there is fgets() after it:

Input:

10

test
 C

// C program to demonstrate the problem when

// fgets()/gets() is used after scanf()

#include <stdio.h>

  

int main()

    int x;

    char str[100];

    scanf("%d\n", &x);

    fgets(str, 100, stdin);

    printf("x = %d, str = %s", x, str);

    return 0;

Output

x = 10, str = test

2) When scanf() is used in a loop: 

Input:

 C

// C program to demonstrate the problem when

// scanf() is used in a loop

#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);

    } while (c != 'q');

    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

// A simple C++ program to show working of getline

#include <cstring>

#include <iostream>
using namespace std;

int main()

    string str;

    int t = 4;

    while (t--) {

        // Read a line from standard input in str

        getline(cin, str);

        cout << str << " : newline" << endl;

    }

    return 0;

Sample Input :

This

is

Geeks

for

As the expected output is:

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

// A simple C++ program that uses getline to read

// input with blank lines

#include <cstring>

#include <iostream>

using namespace std;

int main()

    string str;

    int t = 4;

    while (t--) {

        getline(cin, str);

        // Keep reading a new line while there is

        // a blank line

        while (str.length() == 0)

            getline(cin, str);

        cout << str << " : newline" << endl;


    }

    return 0;

Input:

This

is

Geeks

for

Output:

This : newline

is : newline

Geeks : newline

for : newline

7. scanf() and fscanf() in C – Simple Yet Poweful

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:

int scanf(const char *characters_set)

Many of us know the traditional uses of scanf. Well, here are some of the lesser-known facts

How to read only a part of the input that we need? 


For example, consider some input stream that contains only characters followed by an integer or a float.
And we need to scan only that integer or float. 

Example:

Input: "this is the value 100", 

Output: value read is 100

Input : "this is the value 21.2", 

Output : value read is 21.2

 C
// C program to demonstrate that

// we can ignore some string

// in scanf()

#include <stdio.h>

int main()

    int a;

    scanf("This is the value %d", &a);

    printf("Input value read : a = %d", a);

    return 0;

// Input  : This is the value 100

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

// C program to demonstrate use of *s

#include <stdio.h>

int main()

    int a;

    scanf("%*s %d", &a);

    printf("Input value read : a=%d", a);

    return 0;

}
Output

Input Value read : 25

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. 

General use of scanf( ):

 C

// C program to demonstrate general use of scanf()

#include <stdio.h>

int main()

    int a;

    scanf("%d", &a);

    printf("a = %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:

int fscanf(FILE *ptr, const char *format, ...)

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.

Example 1: Consider the following text file abc.txt 


NAME AGE CITY

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

// C Program to demonstrate fscanf

#include <stdio.h>

// Driver Code

int main()

    FILE* ptr = fopen("abc.txt", "r");

    if (ptr == NULL) {

        printf("no such file.");

        return 0;

    }

    /* Assuming that abc.txt has content in below

       format

       NAME    AGE   CITY

       abc     12    hyderabad

       bef     25    delhi

       cce     65    bangalore */

    char buf[100];

    while (fscanf(ptr, "%*s %*s %s ", buf) == 1)

        printf("%s\n", buf);
 

    return 0;

Output

CITY

hyderabad

delhi

bangalore

Example 2: Consider the following binary file program.bin

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 n1, n2, n3;

};

int main(){

    int n;

    struct threeNum num;


    FILE *fptr;

    if ((fptr = fopen("program.bin","rb")) == NULL){

        printf("Error! opening file");

         // Program exits if the file pointer returns NULL.

         exit(1);

         }

     for(n = 1; n < 5; ++n){

         fread(&num, sizeof(struct threeNum), 1, fptr);

         printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);

     }

     fclose(fptr);

     return 0;

//Code submitted by Susobhan Akhuli

Output

n1: 1 n2: 5 n3: 6

n1: 2 n2: 10 n3: 11

n1: 3 n2: 15 n3: 16

n1: 4 n2: 20 n3: 21

Let us see the differences in a tabular form -:

  scanf() fscanf()

This function is used to read input


1. It is used to read standard input. from a file

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

It takes three parameters that are -:

Whitespace character , Non-whitespace


4. character,Format specifiers

8. Using return value of cin to take unknown number of inputs in C++

Consider a problem where we need to take an unknown number of integer inputs. 


A typical solution is to run a loop and stop when a user enters a particular value. How to do it if we are
not allowed to use if-else, switch-case, and conditional statements?
The idea is to use the fact that ‘cin >> input’ is false if the non-numeric value is given. Note that the
above approach holds true only when the input value’s data type is int (integer). 
Important Point: cin is an object of std::istream. In C++11 and later, std::istream has a conversion
function explicit bool() const;, meaning that there is a valid conversion from std::istream to bool, but only
where explicitly requested. An if or while counts as explicitly requesting conversion to bool.
[Source StackOVerflow] 
Before C++ 11, std::istream had a conversion to operator void*() const;

 C++

// C++ program to take unknown number


// of integers from user.
#include <iostream>
using namespace std;
int main()
{
    int input;
    int count = 0;
    cout << "To stop enter anything except integer";
    cout << "\nEnter Your Input::";
 
    // cin returns false when anything
    // is entered except integer
    while (cin >> input)
        count++;
     
    cout << "\nTotal number of inputs entered: "
         << count;
    return 0;
}
 
//This code is updated by Susobhan Akhuli

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)

9. How to change the output of printf() in main() ?

To change the output of printf() in main(), we can use Macro Arguments.

#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

// C Program to demonstrate changing the output of printf()

// in main()

#include <stdio.h>

void fun()

    // Add something here so that the printf in main prints

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

// C Program to demonstrate the use of macro arguments to

// change the output of printf()

#include <stdio.h>

void fun()

#define printf(x, y) printf(x, 10);

// Driver Code

int main()

    int i = 10;

    fun();

    i = 20;

    printf("%d", i);

    return 0;

}
Output

10

Time Complexity: O(1)

Auxiliary Space: O(1)

10. Implementation of a Falling Matrix

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.

// C++ program for implementation of falling matrix.


#include<iostream>
#include<string>
#include<thread>
#include<cstdlib>
#include<ctime>
#include<chrono>
  
// Width of the matrix line
const int width = 70;
  
// Defines the number of flips in Boolean Array 'switches'
const int flipsPerLine =5;
  
// Delay between two successive line print
const int sleepTime = 100;
  
using namespace std;
  
int main()
{
    int i=0, x=0;
  
    // srand initialized with time function
    // to get distinct rand values at runtime
    srand(time(NULL));
  
    // Used to decide whether to print
    // the character in that particular iteration
    bool switches[width] = {0};
  
    // Set of characters to print from
    const string ch = "1234567890qwertyuiopasdfghjkl"
                      "zxcvbnm,./';[]!@#$%^&*()-=_+";
    const int l = ch.size();
  
    // Green font over black console, duh!
    system("Color 0A");
  
    // Indefinite Loop
    while (true)
    {
        // Loop over the width
        // Increment by 2 gives better effect
        for (i=0;i<width;i+=2)
        {
            // Print character if switches[i] is 1
            // Else print a blank character
            if (switches[i])
                cout << ch[rand() % l] << " ";
            else
                cout<<"  ";
        }
  
        // Flip the defined amount of Boolean values
        // after each line
        for (i=0; i!=flipsPerLine; ++i)
        {
            x = rand() % width;
            switches[x] = !switches[x];
        }
  
         // New Line
        cout << endl;
  
        // Using sleep_for function to delay,
        // chrono milliseconds function to convert to milliseconds
        this_thread::sleep_for(chrono::milliseconds(sleepTime));
    }
    return 0;
}

This prints the amazing Falling-Matrix simulation on the console.


Note :
 This program would not run using Run on IDE button because system is disabled.
 If you get compiler error while compiling this program. Compile it using below command on
GCC.
 $ g++ -std=c++11 abc.cpp -o falling.o

$ falling.o

11. What does buffer flush means in C++ ?

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

// Causes only one write to underlying file

// instead of 5, which is much better for

// performance.

std::cout << a << " + " << b << " = " << std::endl;

But there is certain disadvantage something like, 

 C++

// Below is C++ program

#include <iostream>

#include <thread>

#include <chrono>

using namespace std;

int main()

  for (int i = 1; i <= 5; ++i)

  {

      cout << i << " ";

      this_thread::sleep_for(chrono::seconds(1));

  }

  cout << endl;

  return 0;

The above program will output 1 2 3 4 5 at once.


Therefore in such cases, an additional “flush” function is used to ensure that the output gets displayed
according to our requirements. For instance, 

 C++

// C++ program to demonstrate the

// use of flush function

#include <iostream>

#include <thread>

#include <chrono>

using namespace std;

int main()

   for (int i = 1; i <= 5; ++i)

   {

      cout << i << " " << flush;

      this_thread::sleep_for(chrono::seconds(1));

   }

   return 0;

The above program will print the

numbers(1 2 3 4 5) one by one rather than once.

The reason is flush function flushed the output

to the file/terminal instantly.

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.

12. kbhit in C language

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

// C++ program to demonstrate use of kbhit()

#include <iostream.h>

#include <conio.h>

int main()

    while (!kbhit())

        printf("Press a key\n");

    return 0;

Output:

"Press a key" will keep printing on the

console until the user presses a key on the keyboard.

Note : kbhit() is not a standard library function and should be avoided. Program to fetch the pressed
key using kbhit 

 CPP

// C++ program to fetch key pressed using

// kbhit()

#include <iostream>

#include <conio.h>

using namespace std;

int main()

{
    char ch;

    while (1) {

        if ( kbhit() ) {

            // Stores the pressed key in ch

            ch = getch();

            // Terminates the loop

            // when escape is pressed

            if (int(ch) == 27)

                break;

            cout << "\nKey pressed= " << ch;

        }

    }

    return 0;

Output:

Prints all the keys that will be pressed on

the keyboard until the user presses Escape key

 C

#include <stdio.h>

// include conio.h file for kbhit function

#include <conio.h>

main()
{

    // declare variable

    char ch;

    printf("Enter key ESC to exit \n");

    // define infinite loop for taking keys

    while (1) {

        if (kbhit) {

            // fetch typed character into ch

            ch = getch();

            if ((int)ch == 27)

                // when esc button is pressed, then it will exit from loop

                break;

            printf("You have entered : %c\n", ch);

        }

    }

Output :

Enter key ESC to exit

You have entered : i

You have entered : P

You have entered : S

You have entered : w

You have entered : 7

You have entered : /

You have entered : *

You have entered : +

13. Code to generate the map of India


Given an obfuscated code that generates the map of India, explain its working. The following code when
executed generates the map of India.
#include "stdio.h"
int main()
ding Posts
int a, b, c;
for (b-c-18; a="Hello! Welcome to Geeks ForGeeks.\
TFy!QJu ROo TNn (ROO) SLq SLq ULO+
UHS UJq TNn*RPn/QPbEWS_JSWQAIJO^\
NBELPEHBFHT}TnALVIBLOFAKHFOUFETp\
HCSTHAUFAgcEAelclcn^r^r\\tZvYXXy\
T|S~Pn SPM SOn TNn ULOGULO#ULO-W\
er menu
et
Hq!WFs XDt!" [b+++21]; )
ents 850
dot menu
gs
for (; a-- &gt; 64; )
putchar (++C == 'Z' ? c = c/ 9:33^b&amp;1);
ar Ads Widget
ub menu
et
return 0;
se menu
}
The above code is a typical example of obfuscated code i.e. code that is difficult for humans to
understand.
How does it work?
Basically, the string is a run-length encoding of the map of India. Alternating characters in the string store
how many times to draw space, and how many times to draw an exclamation mark consecutively.  Here is
an analysis of the different elements of this program –
The encoded string
"Hello!Welcome to GeeksForGeeks."
"TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq
TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBL"
"OFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm SOn TNn ULo0ULo#ULo-WHq!WFs
XDt!";
Notice [b+++21] at the end of the encoded string. As b+++21 is equivalent to (b++ + 21) which will
evaluate to 31 (10 + 21), the first 31 characters of this string are ignored and do not contribute to
anything. The remaining encoded string contains instructions for drawing the map. The individual
characters determine how many spaces or exclamation marks to draw consecutively.
Outer for loop: This loop goes over the characters in the string. Each iteration increases the value of b
by one and assigns the next character in the string to a.
Inner for loop: This loop draws individual characters, and a new line whenever it reaches the end of the
line. Consider this putchar statement 

putchar(++c=='Z' ? c = c/9 : 33^b&1);


As ‘Z’ represents the number 90 in ASCII, 90/9 will give us 10 which is a newline character. Decimal 33 is
ASCII for ‘!’. Toggling the low-order bit of 33 gives you 32, which is ASCII for a space. This causes! to be
printed if b is odd, and a blank space to be printed if b is even. 
Below is a less obfuscated version of the above code:
 C++
 C
 Java
 Python3
 C#
 PHP

// C++ program to print map of India


#include <iostream>
using namespace std;
 
int main()
{
    int a = 10, b = 0, c = 10;
 
    // The encoded string after removing first 31 characters
    // Its individual characters determine how many spaces
    // or exclamation marks to draw consecutively.
    char* str = "TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs
UJq "
                "TNn*RPn/
QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBL"
                "OFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|
S~Pn SPm "
                "SOn TNn ULo0ULo#ULo-WHq!WFs XDt!";
 
    while (a != 0)
    {
        // read each character of encoded string
        a = str[b++];
        while (a-- > 64)
        {
            if (++c == 90) // 'Z' is 90 in ascii
            {
                // reset c to 10 when the end of line is reached
                c = 10;        // '\n' is 10 in ascii
 
                // print newline
                putchar('\n'); // or putchar(c);
            }
            else
            {
                // draw the appropriate character
                // depending on whether b is even or odd
                if (b % 2 == 0)
                    putchar('!');
                else
                    putchar(' ');
            }
        }
    }
 
    return 0;
}
 
// This code is contributed by SHUBHAMSINGH10.

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 != 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

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

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

[] Brackets (array subscript) left-to-right

. Member selection via object name left-to-right

-> Member selection via a pointer left-to-right

1 a++/a– Postfix increment/decrement (a is a variable) left-to-right

++a/–a Prefix increment/decrement (a is a variable) right-to-left

+/- Unary plus/minus right-to-left

!~ Logical negation/bitwise complement right-to-left

(type) Cast (convert value to temporary value of type) right-to-left

* Dereference right-to-left

& Address (of operand) right-to-left

2 sizeof Determine size in bytes on this implementation right-to-left

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

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

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

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

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

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

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right


Precedence Operator Description Associativity

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

= Assignment right-to-left

+= , -= Addition/subtraction assignment right-to-left

*= , /= Multiplication/division assignment right-to-left

%= , &= Modulus/bitwise AND assignment right-to-left

^= , |= Bitwise exclusive/inclusive OR assignment right-to-left

14 <>= Bitwise shift left/right assignment right-to-left

15 , expression separator left-to-right

2. Unary operators in C/C++

Unary operators: are operators that act upon a single operand to produce a new value.

Types of unary operators:

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;

int b = -a; // b = -10

unary minus is different from the subtraction operator, as subtraction requires two operands.
Below is the implementation of unary minus (-) operator:

 C++

// C++ program to demonstrate the use of 'unary minus'


// operator

#include <iostream>

using namespace std;

int main()

    int positiveInteger = 100;

    int negativeInteger = -positiveInteger;

    cout << "Positive Integer: " << positiveInteger << endl;

    cout << "Negative Integer: " << negativeInteger << endl;

    return 0;

// This code is contributed by sarajadhav12052009

Output

Positive Integer: 100

Negative Integer: -100

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.

If x is true, then !x is false

If x is false, then !x is true

Below is the implementation of the NOT (!) operator:

 C++

// C++ program to demonstrate the use of '!(NOT) operator'

#include <iostream>

using namespace std;

int main()

    int a = 10;

    int b = 5;

 
    if (!(a > b))

        cout << "b is greater than a" << endl;

    else

        cout << "a is greater than b" << endl;

    return 0;

// This code is contributed by sarajadhav12052009

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.

& gives an address on variable n

int a;

int *ptr;

ptr = &a; // address of a is copied to the location ptr.

Below is the implementation of Addressof operator(&):

 C++

// C++ program to demonstrate the use of 'address-of(&)'

// operator

#include <iostream>

using namespace std;

int main()
{

    int a;

    int* ptr;

    ptr = &a;

    cout << ptr;

    return 0;

// This code is contributed by sarajadhav12052009

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>

using namespace std;

int main()

    float n = 0;

    cout << "size of n: " << sizeof(n);

    return 1;

}
Output

size of n: 4

3. Conditionally assign a value without


using conditional and arithmetic operators

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,

Assign value 'a' to variable 'y'

Else (If 'x' is 1)

Assign value 'b' to variable 'y'.

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

Asked in: Google Interview 

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.

Below is the implementation of the above approach:

 C++
 Java
 Python3
 C#
 PHP
 Javascript

// C/C++ program to assign value to y according

// to value of x

 
#include <iostream>

using namespace std;

// Function to assign value to y according

// to value of x

int assignValue(int a, int b, int x)

    int y;

    int arr[2];

    // Store both values in an array

    // value 'a' at 0th index

    arr[0] = a;

    // Value 'b' at 1th index

    arr[1] = b;

    // Assign value to 'y' taking 'x' as index

    y = arr[x];

    return y;

// Driver code

int main()

    int a = 5;
    int b = 10;

    int x = 0;

    cout << "Value assigned to 'y' is "

         << assignValue(a, b, x);

    return 0;

Output

Value assigned to 'y' is 5

Solution 2: 

Using bitwise AND operator.

 C++
 Java
 Python3
 C#
 Javascript

// C/C++ program to assign value to y according

// to value of x

#include <iostream>

using namespace std;

// Driver Code

int main()

    int a = 5;

    int b = 10;

    int x = 1;
    int y;

    if (x & 1)

        y = b;

    else

        y = a;

    cout << "Value assigned to 'y' is " << y << endl;

    return 0;

Output

Value assigned to 'y' is 10

4. Execution of printf with ++ operators

Consider the following statement in C and predict its output.


printf("%d %d %d", i, ++i, i++);
This statement invokes undefined behavior by referencing both ‘i’ and ‘i++’ in the argument list. It is not
defined in which order the arguments are evaluated. Different compilers may choose different orders. A
single compiler can also choose different orders at different times.
For example, below three printf() statements may also cause undefined behavior:

 C

// C Program to demonstrate the three printf() statements


// that cause undefined behavior
#include <stdio.h>
  
// Driver Code
int main()
{
    volatile int a = 10;
    printf("%d %d\n", a, a++);
  
    a = 10;
    printf("%d %d\n", a++, a);
  
    a = 10;
    printf("%d %d %d\n", a, a++, ++a);
    return 0;
}

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.

5. Set a variable without using


Arithmetic, Relational or Conditional Operator

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

6. Scope Resolution Operator vs this pointer

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.

Consider below C++ program:  

 CPP

// C++ program to show that local parameters hide

// class members

#include <iostream>

using namespace std;

  

class Test {

    int a;

  

public:

    Test() { a = 1; }

  

    // Local parameter 'a' hides class member 'a'

    void func(int a) { cout << a; }

};

  

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

// C++ program to show use of this to access member when

// there is a local variable with same name

#include <iostream>

using namespace std;

class Test {

    int a;

  

public:

    Test() { a = 1; }

  

    // Local parameter 'a' hides object's member

    // 'a', but we can access it using this.

    void func(int a) { cout << this->a; }

};

  

// Driver code

int main()
{

    Test obj;

    int k = 3;

    obj.func(k);

    return 0;

Output

How about Scope Resolution Operator ? 

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

// C++ program to show that scope resolution operator can be

// used to access static members when there is a local

// variable with same name

#include <iostream>

using namespace std;

  

class Test {

    static int a;

  

public:

    // Local parameter 'a' hides class member

    // 'a', but we can access it using ::

    void func(int a) { cout << Test::a; }

};
  

// In C++, static members must be explicitly defined

// like this

int Test::a = 1;

  

// Driver code

int main()

    Test obj;

    int k = 3;

    obj.func(k);

    return 0;

Output

7. Pre-increment (or pre-decrement)

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

// CPP program to illustrate

// Pre-increment (or pre-decrement)

#include <cstdio>

int main()

{
    int a = 10;

    ++a = 20; // works

    printf("a = %d", a);

    printf("\n");

    --a = 10;

    printf("a = %d", a);

    return 0;

Output:

a = 20

a = 10

Time Complexity: O(1)

The above program works whereas the following program fails in compilation with error “non-lvalue in
assignment” (a++ is used as l-value) 

 CPP

// CPP program to illustrate

// Post-increment (or post-decrement)

#include <cstdio>

int main()

    int a = 10;

    a++ = 20; // error

    printf("a = %d", a);

    return 0;

}
Error:

prog.cpp: In function 'int main()':

prog.cpp:6:5: error: lvalue required as left operand of assignment

a++ = 20; // error

How ++a is Different From a++ as lvalue?

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:

int &ref = ++a; // valid

int &ref = a++; // invalid

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;

// On compilation, a++ is replaced by the value of a which is an rvalue:

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

8. new and delete operator in C++

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

What are applications? 

 One use of dynamically allocated memory is to allocate memory of variable size, which is not
possible with compiler allocated memory except 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.

How is it different from memory allocated to normal variables? 

For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and deallocated.
For dynamically allocated memory like “int *p = new int[10]”, it is 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. 

Syntax to use new operator

pointer-variable = new data-type;

Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including
array or any user-defined data type including structure and class. 
Example: 

// Pointer initialized with NULL

// Then request memory for the variable

int *p = NULL;

p = new int;

OR

// Combine declaration of pointer

// and their assignment

int *p = new int;

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

pointer-variable = new data-type(value);

Example:

int *p = new int(25);


float *q = new float(75.25);

// Custom data type


struct cust
{
    int p;
    cust(int q) : p(q) {}
};

// Works fine, doesn’t require constructor


cust* var1 = new cust;    
        OR
    
// Works fine, doesn’t require constructor
cust* var1 = new cust();        

// Notice error if you comment this line


cust* var = new cust(25)        

Allocate a block of memory: new operator is also used to allocate a block(an array) of memory of
type data-type. 

pointer-variable = new data-type[size];

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

Example:

int *p = new int[10]

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

Normal Array Declaration vs Using new 


There is a difference between declaring a normal array and allocating a block of memory using new. The
most important difference is, that normal arrays are deallocated by the compiler (If the array is local, then
deallocated when the function returns or completes). However, dynamically allocated arrays always
remain there until either they are deallocated by the programmer or the program terminates.
What if enough memory is not available during runtime? 
If enough memory is not available in the heap to allocate, the new request indicates failure by throwing
an exception of type std::bad_alloc, unless “nothrow” is used with the new operator, in which case it
returns a NULL pointer (scroll to section “Exception handling of new operator” in this article). Therefore, it
may be a good idea to check for the pointer variable produced by the new before using its program. 

int *p = new(nothrow) int;

if (!p)

cout << "Memory allocation failed\n";

delete operator
Since it is the programmer’s responsibility to deallocate dynamically allocated memory, programmers are
provided delete operator in C++ language. 
Syntax: 

// Release memory pointed by pointer-variable


delete pointer-variable;

Here, pointer-variable is the pointer that points to the data object created by new. 
Examples: 

delete p;

delete q;

To free the dynamically allocated array pointed by pointer-variable, use the following form of delete: 

// Release block of memory

// pointed by pointer-variable

delete[] pointer-variable;

Example:

// It will free the entire array

// pointed by p.

delete[] p;

 CPP

// C++ program to illustrate dynamic allocation

// and deallocation of memory using new and delete

#include <iostream>

using namespace std;

int main ()

    // Pointer initialization to null

    int* p = NULL;

    // Request memory for the variable

    // using new operator

    p = new(nothrow) int;

    if (!p)
        cout << "allocation of memory failed\n";

    else

    {

        // Store value at allocated address

        *p = 29;

        cout << "Value of p: " << *p << endl;

    }

    // Request block of memory

    // using new operator

    float *r = new float(75.25);

    cout << "Value of r: " << *r << endl;

    // Request block of memory of size n

    int n = 5;

    int *q = new(nothrow) int[n];

    if (!q)

        cout << "allocation of memory failed\n";

    else

    {

        for (int i = 0; i < n; i++)

            q[i] = i+1;

        cout << "Value store in block of memory: ";

        for (int i = 0; i < n; i++)


            cout << q[i] << " ";

    }

    // freed the allocated memory

    delete p;

    delete r;

    // freed the block of allocated memory

    delete[] q;

    return 0;

Output: 

Value of p: 29

Value of r: 75.25

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

Time Complexity: O(n), where n is the given memory size. 

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

// CPP program to print byte by byte presentation


#include <bits/stdc++.h>
using namespace std;
 
// function in which number and initially 0 is passed
void printInBinary(int num)
{
    int n = CHAR_BIT*sizeof(num);
    stack<bool> s;
    for (int i=1; i<=n; i++)
    {
        s.push(num%2);
        num = num/2;
    }    
    for (int i=1; i<=n; i++)
    {
        cout << s.top();
        s.pop();
         
        // Put a space after every byte.
        if (i % CHAR_BIT == 0)
        cout << " ";
    }
}
 
int main()
{
    int num = 12;
    printInBinary(num);
    return 0;
}

Output :
00000000 00000000 00000000 00001100
Time Complexity : O(32)
Auxiliary Space : O(32)

10. Casting operators| Set 1 (const_cast)

C++ supports following 4 types of casting operators:


1. const_cast
2. static_cast
3. dynamic_cast
4. reinterpret_cast
1. const_cast
const_cast is used to cast away the constness of variables. Following are some interesting facts about
const_cast.
1) const_cast can be used to change non-const class members inside a const member function.
Consider the following code snippet. Inside const member function fun(), ‘this’ is treated by the compiler
as ‘const student* const this’, i.e. ‘this’ is a constant pointer to a constant object, thus compiler doesn’t
allow to change the data members through ‘this’ pointer. const_cast changes the type of ‘this’ pointer to
‘student* const this’.

#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;
}

Arrays and Strings

1. Arrays in C/C++

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

 Code Optimization:  we can retrieve or sort the data efficiently.


 Random access: We can get any data located at an index position.
 

Disadvantages:-

 Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its size at
runtime. 
 

Array declaration in C/C++: 


 
Note: In the above image int a[3]={[0…1]=3}; this kind of declaration has been obsolete since GCC 2.5

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.

Array declaration by specifying the size 

 C++
 C

#include <iostream>

using namespace std;

  

int main()

    // array declaration by specifying size

    int arr1[10];

    

    // With recent C/C++ versions, we can also

    // declare an array of user specified size

    int n = 10;

    int arr2[n];
      

    return 0;

  

// This code is contributed by sarajadhav12052009

Array declaration by initializing elements

 C++
 C

// Array declaration by initializing elements

#include <iostream>

using namespace std; 

int main()

    int arr[] = { 10, 20, 30, 40};

    return 0; 

// Compiler creates an array of size 4.

// above is same as  "int arr[4] = {10, 20, 30, 40}"

Array declaration by specifying the size and initializing elements

 C++
 C

#include <iostream>

using namespace std;

  

int main() 

{
    // Array declaration by specifying size and initializing

    // elements

    int arr[6] = { 10, 20, 30, 40 };

  

    // Compiler creates an array of size 6, initializes first

    // 4 elements as specified by user and rest two elements as

    // 0. above is same as  "int arr[] = {10, 20, 30, 40, 0, 0}"

      

    return 0;

  

// This code is contributed by sarajadhav12052009

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

 C
 C++

#include <stdio.h>

  

int main()

    int arr[5];

    arr[0] = 5;

    arr[2] = -10;

    arr[3 / 2] = 2; // this is same as arr[1] = 2

    arr[3] = arr[0];

  

    printf("%d %d %d %d", arr[0], 

           arr[1], arr[2], arr[3]);

  

    return 0;

Output
5 2 -10 5

No Index Out of bound Checking: 


There is no index out of bounds checking in C/C++, for example, the following program compiles fine but
may produce unexpected output when run.  

 C
 C++

// This C program compiles fine

// as index out of bound

// is not checked in C.

  

#include <stdio.h>

  

int main()

    int arr[2];

  

    printf("%d ", arr[3]);

    printf("%d ", 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()

{
  

    // Array declaration by initializing it 

    // with more elements than specified size.

    int arr[2] = { 10, 20, 30, 40, 50 };

  

    return 0;

Warnings: 

prog.c: In function 'main':

prog.c:7:25: warning: excess elements in array initializer

int arr[2] = { 10, 20, 30, 40, 50 };

prog.c:7:25: note: (near initialization for 'arr')

prog.c:7:29: warning: excess elements in array initializer

int arr[2] = { 10, 20, 30, 40, 50 };

prog.c:7:29: note: (near initialization for 'arr')

prog.c:7:33: warning: excess elements in array initializer

int arr[2] = { 10, 20, 30, 40, 50 };

prog.c:7:33: note: (near initialization for 'arr')

 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]'”. 
 

The elements are stored at contiguous memory locations 


Example: 

 C
 C++

// C program to demonstrate that


// array elements are stored

// contiguous locations

  

#include <stdio.h>

int main()

    // an array of 10 integers.  

    // If arr[0] is stored at

    // address x, then arr[1] is

    // stored at x + sizeof(int)

    // arr[2] is stored at x + 

    // sizeof(int) + sizeof(int)

    // and so on.

    int arr[5], i;

  

    printf("Size of integer in this compiler is %lu\n",

           sizeof(int));

  

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

        // The use of '&' before a variable name, yields

        // address of variable.

        printf("Address arr[%d] is %p\n", i, &arr[i]);

  

    return 0;

Output

Size of integer in this compiler is 4


Address arr[0] is 0x7fff7a02db20

Address arr[1] is 0x7fff7a02db24

Address arr[2] is 0x7fff7a02db28

Address arr[3] is 0x7fff7a02db2c

Address arr[4] is 0x7fff7a02db30

Another way to traverse the array

 C++
 C

#include<bits/stdc++.h>

using namespace std;

  

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

    cout<<"By Other Method:"<<endl;

    for(int i=0;i<6;i++)   

        cout<<i[arr]<<" ";

    

    cout<<endl;

  

    return 0;

}
  

// Contributed by Akshay Pawar ( Username - akshaypawar4)

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. 

Below are the 5 different ways to create an Array of Strings in C++:

 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

// C++ program to demonstrate array of strings using

// pointers character array

#include <iostream>

#include <stdio.h>

int main()

    // Initialize array of pointer

    const char* colour[4]

        = { "Blue", "Red", "Orange", "Yellow" };

    // Printing Strings stored in 2D array

    for (int i = 0; i < 4; i++)

        std::cout << colour[i] << "\n";

    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

// C++ program to demonstrate array of strings using

// 2D character array

#include <iostream>

int main()

    // Initialize 2D array

    char colour[4][10]

        = { "Blue", "Red", "Orange", "Yellow" };

    // Printing Strings stored in 2D array

    for (int i = 0; i < 4; i++)

        std::cout << colour[i] << "\n";

    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.

3. Using the String class

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

// C++ program to demonstrate array of strings using

// array of strings.

#include <iostream>

#include <string>

int main()

    // Initialize String Array

    std::string colour[4]

        = { "Blue", "Red", "Orange", "Yellow" };

    // Print Strings

    for (int i = 0; i < 4; i++)

        std::cout << colour[i] << "\n";

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

4. Using the vector class

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

// C++ program to demonstrate array of strings using vector

#include <iostream>

#include <string>

#include <vector>

int main()

    // Declaring Vector of String type

    // Values can be added here using initializer-list

    // syntax

    std::vector<std::string> colour{ "Blue", "Red",

                                     "Orange" };

    // Strings can be added at any time with push_back

    colour.push_back("Yellow");
 

    // Print Strings stored in Vector

    for (int i = 0; i < colour.size(); i++)

        std::cout << colour[i] << "\n";

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.

5. Using the Array Class

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

// C++ program to demonstrate array of string

// using STL array

#include <array>

#include <iostream>

#include <string>

int main()

    // Initialize array


    std::array<std::string, 4> colour{ "Blue", "Red",

                                       "Orange", "Yellow" };

    // Printing Strings stored in array

    for (int i = 0; i < 4; i++)

        std::cout << colour[i] << "\n";

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

3. Multidimensional arrays in C/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.

The  general form of declaring N-dimensional arrays is:  

data_type array_name[size1][size2]....[sizeN];

 data_type: Type of data to be stored in the array.


 array_name: Name of the array
 size1, size2,… ,sizeN: Sizes of the dimension

Examples: 

Two dimensional array: int two_d[10][20];

Three dimensional array: int three_d[10][20][30];

Size of Multidimensional Arrays:


The total number of elements that can be stored in a multidimensional array can be calculated by
multiplying the size of all the dimensions. 
For example: 

 The array int x[10][20] can store total (10*20) = 200 elements. 


 Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

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. 

The basic form of declaring a two-dimensional array of size x, y: 


Syntax: 

data_type array_name[x][y];

 Here, data_type is the type of data to be stored.

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: 

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}


The above array has 3 rows and 4 columns. The elements in the braces from left to right are stored in the
table also from left to right. The elements will be filled in the array in order, the first 4 elements from the
left in the first row, the next 4 elements in the second row, and so on.

Second Method: 

int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};

Third Method:

int x[3][4];

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

for(int j = 0; j < 4; j++){

cin >> x[i][j];

Fourth Method(Dynamic Allocation):

int** x = new int*[3];

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

x[i] = new int[4];

for(int j = 0; j < 4; j++){

cin >> x[i][j];

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.

Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are accessed


using the row indexes and column indexes. 

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

// C++ Program to print the elements of a

// Two-Dimensional array

#include<iostream>

using namespace std;

  

int main()

    // an array with 3 rows and 2 columns.

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

  

    // output each array element's value

    for (int i = 0; i < 3; i++)

    {

        for (int j = 0; j < 2; j++)

        {

            cout << "Element at x[" << i

                 << "][" << j << "]: ";

            cout << x[i][j]<<endl;

        }

    }

  
    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

Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is the same as that of


Two-dimensional arrays. The difference is as the number of dimensions increases so the number of
nested braces will also increase. 

Method 1: 

int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

11, 12, 13, 14, 15, 16, 17, 18, 19,

20, 21, 22, 23};

Method 2(Better):  
int x[2][3][4] =

{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },

{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }

};

Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional Arrays


is also similar to that of Two-Dimensional Arrays. The difference is we have to use three loops instead of
two loops for one additional dimension in Three-dimensional Arrays. 

 CPP
 C

// C++ program to print elements of Three-Dimensional

// Array

#include <iostream>

using namespace std;

  

int main()

    // initializing the 3-dimensional array

    int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },

                       { { 6, 7 }, { 8, 9 }, { 10, 11 } } };

  

    // output each element's value

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

        for (int j = 0; j < 3; ++j) {

            for (int k = 0; k < 2; ++k) {

                cout << "Element at x[" << i << "][" << j

                     << "][" << k << "] = " << x[i][j][k]

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

4. Raw string literal

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 needs a defined line{ parentheses ()} to start


It does not need anything to be defined. with the prefix R.

It allows/includes nested character


It does not allow/include nested characters. implementation.

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.

Example of Raw String Literal:


 CPP

// C++ program to demonstrate working of raw string literal


#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // A Normal string
    string string1 = "Geeks.\nFor.\nGeeks.\n";
 
    // A Raw string
    string string2 = R"(Geeks.\nFor.\nGeeks.\n)";
 
    cout << string1 << endl;
 
    cout << string2 << endl;
 
    return 0;
}

Output
Geeks.
For.
Geeks.
Geeks.\nFor.\nGeeks.\n

5. Counts of distinct consecutive sub-string


of length two

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

// C++ STL based program to print all distinct


// substrings of size 2 and their counts.
#include<bits/stdc++.h>
using namespace std;
 
void printDistinctSubStrs(string str)
{
    // Create a map to store unique substrings of
    // size 2
    map<pair<char,char>, int> dPairs;
 
    // Count occurrences of all pairs
    for (int i=0; i<str.size()-1; i++)
        dPairs[make_pair(str[i], str[i+1])]++;
 
    // Traverse map to print sub-strings and their
    // counts.
    cout << "Distinct sub-strings with counts:\n";
    for (auto it=dPairs.begin(); it!=dPairs.end(); it++)
        cout << it->first.first << it->first.second
             << "-" << it->second << " ";
}
 
// Driver code
int main()
{
    string str = "abcacdcacabacaassddssklac";
    printDistinctSubStrs(str);
    return 0;
}

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

6. Converting string to number and vice-versa

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.

Converting Number to String in C++

There are  3 major methods to convert a number to a string, which are as follows:

 Using string Stream 


 Using to_string()
 Using boost lexical cast

Method 1: Using string streams

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

// C++ code to demonstrate string stream method

// to convert number to string.

#include<iostream>

#include <sstream>  // for string streams

#include <string>  // for string

using namespace std;


int main()

    int num = 2016;

    // declaring output string stream

    ostringstream str1;

    // Sending a number as a stream into output

    // string

    str1 << num;

    // the str() converts number into string

    string geek = str1.str();

    // Displaying the string

    cout << "The newly formed string from number is : ";

    cout << geek << endl;

    return 0;

Output

The newly formed string from number is : 2016

Time Complexity: O(n)

Auxiliary Space: O(n)

Method 2: Using to_string()

 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

// to convert number to string.

#include <iostream>

#include <string> // for string and to_string()

using namespace std;

// Driver Code

int main()

    // Declaring integer

    int i_val = 20;

    // Declaring float

    float f_val = 30.50;

    // Conversion of int into string using

    // to_string()

    string stri = to_string(i_val);

    // Conversion of float into string using

    // to_string()

    string strf = to_string(f_val);

    // Displaying the converted strings

    cout << "The integer in string is : ";

    cout << stri << endl;

    cout << "The float in string is : ";

    cout << strf << endl;


 

    return 0;

Output

The integer in string is : 20

The float in string is : 30.500000

Time Complexity: O(n)

Auxiliary Space: O(n)

Method 3: Using boost lexical cast

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

// C++ code to demonstrate "lexical_cast()" method

// to convert number to string.

#include <boost/lexical_cast.hpp> // for lexical_cast()

#include <iostream>

#include <string> // for string

using namespace std;

// Driver Code

int main()

    // Declaring float

    float f_val = 10.5;

    // Declaring int


    int i_val = 17;

    // lexical_cast() converts a float into string

    string strf = boost::lexical_cast<string>(f_val);

    // lexical_cast() converts a int into string

    string stri = boost::lexical_cast<string>(i_val);

    // Displaying string converted numbers

    cout << "The float value in string is : ";

    cout << strf << endl;

    cout << "The int value in string is : ";

    cout << stri << endl;

    return 0;

Output

The float value in string is : 10.5

The int value in string is : 17

Method: Using the sprintf() function

 C++

#include <iostream>

using namespace std;

int main()

{
    int n=12234;

    char str[1000];

  sprintf(str,"%d", n);

  printf("the string is : %s",str);

    

    return 0;

Output

the string is : 12234

Time Complexity: O(n)

Auxiliary Space: O(n)

7. Find size of array in C/C++ without using sizeof

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:

// Finds size of arr[] and stores in 'size'

int size = sizeof(arr)/sizeof(arr[0]);

Can we do the same without using the sizeof() operator? 

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?

Approach 1: Implement our own sizeof

 CPP

// C++ program to find size of

// an array by writing our

// own sizeof operator

#include <bits/stdc++.h>

using namespace std;

  
// User defined sizeof macro

# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))

  

int main()

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

    int size = my_sizeof(arr)/my_sizeof(arr[0]);

  

    cout << "Number of elements in arr[] is "

        << size;

  

    return 0;

Output:

Number of elements in arr[] is 6

Approach 2: Using a pointer hack

 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:

int size = *(&arr + 1) - arr; // &arr returns a pointer

 CPP

// C++ program to find size 

// of an array by using a 

// pointer hack

#include <bits/stdc++.h>

using namespace std;

  

int main()
{

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

    int size = *(&arr + 1) - arr;

    cout << "Number of elements in arr[] is " << size;

    return 0;

Output:

Number of elements in arr[] is 6

How does this work? 

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.

8. How to quickly reverse a string in C++?

The reversing of a string is nothing but simply substituting the last element of a string to the 1st position
of the string.

Different Methods to Reverse a String in C++ are:

 Making our own reverse function 


 Using ‘inbuilt’ reverse function 
 Using Constructor
 Using a temp file

1. Making a Custom Reverse Function For Swapping Characters

  Using a first to last approach ‘for’  loop

 CPP
// C++ program to reverse a string

// using first to last approach

// 'for' loop

#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

void reverseStr(string& str)

    int n = str.length();

    // Swap character starting from two

    // corners

    for (int i = 0; i < n / 2; i++)

        swap(str[i], str[n - i - 1]);

// Driver program

int main()

    string str = "geeksforgeeks";

    reverseStr(str);

    cout << str;

    return 0;

Output

skeegrofskeeg

Complexity Analysis:
Time Complexity: O(N)

Auxiliary Space: O(1)

 Using a first to last Approach with while loop 

 C++

// C++ program to reverse a string

// using while loop

#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

void reverseStr(string& str)

    int len = str.length();

    int n = len-1;

    int i = 0;

    while(i<=n){

        //Using the swap method to switch values at each index

        swap(str[i],str[n]);

        n = n-1;

        i = i+1;

  }

// Driver program

int main()

    string str = "geeksforgeeks";


    reverseStr(str);

    cout << str;

    return 0;

Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(1)

  Using a Last to First Approach ‘for‘ Loop  

 C++

// C++ program to demonstrate reverse

// of a string using Last to First

// Approach 'for' Loop

#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

void reverse(string str)

    for (int i = str.length() - 1; i >= 0; i--)

        cout << str[i];

// Driver code

int main(void)
{

    string s = "GeeksforGeeks";

    reverse(s);

    return (0);

Output

skeeGrofskeeG

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(1)

 Using a Last to First Approach ‘while’ Loop

 C++

// C++ program to demonstrate reverse

// of a string using Last to First

// Approach 'while' Loop

#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

void reverse(string str)

    int len = str.length();

    int n = len;

    while(n--)

        cout << str[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.  

1. Using recursion Function with two pointer approach

Recursion functions are used for iterating to different indexes of the string.

 C++

// C++ program to reverse a string

// using recursion
#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

void reverseStr(string& str, int n, int i)

     

  if(n<=i){return;}

//  Swaping the character

  swap(str[i],str[n]);

  reverseStr(str,n-1,i+1);

// Driver program

int main()

    string str = "geeksforgeeks";

    reverseStr(str, str.length()-1, 0);

    cout << str;

    return 0;

Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(N)

2. Using one pointer approach in recursion


Below is the implementation of the code:

 C++

//C++ program to reverse a string using recursion

#include <iostream>

using namespace std;

void getreverse(string &str, int i)

    if (i > (str.length() - 1 - i))

    {

        return;

    }

    swap(str[i], str[str.length() - i - 1]);

    i++;

    getreverse(str, i);

int main()

    string name = "geeksforgeeks";

    getreverse(name, 0);

    cout << name << endl;

    return 0;

//code contributed by pragatikohli

Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)
Auxiliary Space: O(N)

3. Using the inbuilt “reverse” Function

There is a direct function in the “algorithm” header file for doing reverse that saves our time when
programming.

// Reverses elements in [begin, end]

void reverse (BidirectionalIterator begin,

BidirectionalIterator end);

 CPP

// C++ program to illustrate the

// reversing of a string using

// reverse() function

#include <bits/stdc++.h>

using namespace std;

int main()

    string str = "geeksforgeeks";

    // Reverse str[begin..end]

    reverse(str.begin(), str.end());

    cout << str;

    return 0;

Output

skeegrofskeeg

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(1)

4. Reverse a String Using the Constructor 


Passing reverse iterators to the constructor returns us a reversed string. 

 CPP

// C++ program to reverse

// string using constructor

#include <bits/stdc++.h>

using namespace std;

int main()

    string str = "GeeksforGeeks";

    // Use of reverse iterators

    string rev = string(str.rbegin(), str.rend());

    cout << rev << endl;

    return 0;

Output

skeeGrofskeeG

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(1)

5. Using a Temporary String

 CPP

// C++ program to demonstrate

// reversing of string

// using temporary string

#include <bits/stdc++.h>
using namespace std;

int main()

    string str = "GeeksforGeeks";

    int n = str.length();

   

    // Temporary string to store the reverse

    string rev;

   

    for (int i = n - 1; i >= 0; i--)

        rev.push_back(str[i]);

    cout << rev << endl;

    return 0;

Output

skeeGrofskeeG

Complexity Analysis:

Time Complexity: O(N)

Auxiliary Space: O(1)

How could we get the reverse of a const string?

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.

“const reverseConstString = function(string) { return string.split("").reverse().join("")”

Example: 

 C++
// C++ program to get reverse of a const string

#include <bits/stdc++.h>

using namespace std;

// Function to reverse string and return

// reverse string pointer of that

char* reverseConstString(char const* str)

    // find length of string

    int n = strlen(str);

    // create a dynamic pointer char array

    char* rev = new char[n + 1];

    // copy of string to ptr array

    strcpy(rev, str);

    // Swap character starting from two

    // corners

    for (int i = 0, j = n - 1; i < j; i++, j--)

        swap(rev[i], rev[j]);

    // return pointer of the reversed string

    return rev;

// Driver code

int main(void)
{

    const char* s = "GeeksforGeeks";

    printf("%s", reverseConstString(s));

    return (0);

Output

skeeGrofskeeG

Using Stack Data Structure

 C++

// C++ Program to reverse a string

#include <bits/stdc++.h>

using namespace std;

int main()

    string s = "GeeksforGeeks";

    stack<char> st;

    for (char x : s)

        st.push(x);

    while (!st.empty()) {

        cout << st.top();

        st.pop();

    }

    return 0;

Output

skeeGrofskeeG

Complexity Analysis:
Time Complexity: O(N)

Auxiliary Space: O(N)

9. Tokenizing a string in C++

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.

Below is the C++ implementation : 

 C++

// Tokenizing a string using stringstream

#include <bits/stdc++.h>

using namespace std;

int main()

     

    string line = "GeeksForGeeks is a must try";

     

    // Vector of string to save tokens

    vector <string> tokens;

     

    // stringstream class check1

    stringstream check1(line);

     

    string intermediate;

     

    // Tokenizing w.r.t. space ' '


    while(getline(check1, intermediate, ' '))

    {

        tokens.push_back(intermediate);

    }

     

    // Printing the token vector

    for(int i = 0; i < tokens.size(); i++)

        cout << tokens[i] << '\n';

Output

GeeksForGeeks

is

must

try

Using strtok()

// Splits str[] according to given delimiters.

// and returns next token. It needs to be called

// in a loop to get all tokens. It returns NULL

// when there are no more tokens.

char * strtok(char str[], const char *delims);

Below is the C++ implementation : 

 C++

// C/C++ program for splitting a string

// using strtok()

#include <stdio.h>
#include <string.h>

int main()

    char str[] = "Geeks-for-Geeks";

    // Returns first token

    char *token = strtok(str, "-");

    // Keep printing tokens while one of the

    // delimiters present in str[].

    while (token != NULL)

    {

        printf("%s\n", token);

        token = strtok(NULL, "-");

    }

    return 0;

Output

Geeks

for

Geeks

Another Example of strtok() :

 C

// C code to demonstrate working of


// strtok

#include <string.h>

#include <stdio.h>

// Driver function

int main()

 // Declaration of string

    char gfg[100] = " Geeks - for - geeks - Contribute";

    // Declaration of delimiter

    const char s[4] = "-";

    char* tok;

    // Use of strtok

    // get first token

    tok = strtok(gfg, s);

    // Checks for delimiter

    while (tok != 0) {

        printf(" %s\n", tok);

        // Use of strtok

        // go through other tokens

        tok = strtok(0, s);

    }

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

There are two ways we can call strtok_r() 

// The third argument saveptr is a pointer to a char *

// variable that is used internally by strtok_r() in

// order to maintain context between successive calls

// that parse the same string.

char *strtok_r(char *str, const char *delim, char **saveptr);

Below is a simple C++ program to show the use of strtok_r() : 

 C++

// C/C++ program to demonstrate working of strtok_r()

// by splitting string based on space character.

#include<stdio.h>

#include<string.h>

int main()

    char str[] = "Geeks for Geeks";

    char *token;
    char *rest = str;

    while ((token = strtok_r(rest, " ", &rest)))

        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.

Below is a simple C++ program to show the use of std::sregex_token_iterator:

 C++

// CPP program for above approach

#include <iostream>

#include <regex>

#include <string>

#include <vector>

/**

 * @brief Tokenize the given vector

   according to the regex

 * and remove the empty tokens.

 *
 * @param str

 * @param re

 * @return std::vector<std::string>

 */

std::vector<std::string> tokenize(

                     const std::string str,

                          const std::regex re)

    std::sregex_token_iterator it{ str.begin(),

                             str.end(), re, -1 };

    std::vector<std::string> tokenized{ it, {} };

    // Additional check to remove empty strings

    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";

    const std::regex re(R"([\s|,]+)");

   

    // Function Call

    const std::vector<std::string> tokenized =

                           tokenize(str, re);

   

    for (std::string token : tokenized)

        std::cout << token << std::endl;

    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)

10. Getline() function and character array

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)

istream& getline(char*, int size, char='\n')

// The delimiter character is considered as '\n'

istream& getline(char*, int size)

Parameters:

 char*: Character pointer that points to the array.


 Size: Acts as a delimiter that defines the size of the array.

The Function Does the Following Operations: 

 Extracts character up to the delimiter. 


 Stores the characters in the buffer. 
 The maximum number of characters extracted is size – 1. 

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:

Input: Aditya Rakhecha

 CPP

// C++ program to show the getline() with

// character array

#include <iostream>

using namespace std;

  

// Driver Code

int main()

    char str[20];

    cout << "Enter Your Name::";

  

    // see the use of getline() with array

    // str also replace the above statement


    // by cin >> str and see the difference

    // in output

    cin.getline(str, 20);

  

    cout << "\nYour Name is:: " << str;

    return 0;

Output

Your Name is:: Aditya Rakhecha

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.

11. Convert string to char array in C++

Many of us have encountered error ‘cannot convert std::string to char[] or char* data type’. 

Examples: 

Input : string s = "geeksforgeeks" ;

Output : char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',

'r', 'g', 'e', 'e', 'k', 's' } ;

Input : string s = "coding" ;

Output : char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' } ;

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: 

const char* c_str() const ;

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>

using namespace std;

// driver code

int main()

    // assigning value to string s

    string s = "geeksforgeeks";

    int n = s.length();

    // declaring character array

    char char_array[n + 1];

    // copying the contents of the

    // string to char array

    strcpy(char_array, s.c_str());

    for (int i = 0; i < n; i++)

        cout << char_array[i];

    return 0;

Output
geeksforgeeks

Time complexity: O(n)


Auxiliary Space: O(1)

Method 2:

 CPP

// CPP program to convert string

// to char array

#include <iostream>

#include <string>

using namespace std;

// driver code

int main()

    // assigning value to string s

    string s("geeksforgeeks");

    // declaring character array : p

    char p[s.length()];

    int i;

    for (i = 0; i < sizeof(p); i++) {

        p[i] = s[i];

        cout << p[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

// CPP program for the above approach

#include <cstring>

#include <iostream>

#include <string>

using namespace std;

// Driver Code

int main()

    char* char_arr;

    string str_obj("GeeksForGeeks");

    char_arr = &str_obj[0];

    cout << char_arr;

    return 0;

Output

GeeksForGeeks

Time complexity: O(n)


Auxiliary Space: O(1)

Method 4:

An alternate way of Method 1 can be such, without using strcpy() function.

 C++14
// CPP program to convert string

// to char array

#include <iostream>

#include <cstring>

using namespace std;

// driver code

int main()

    // assigning value to string s

    string st = "GeeksForGeeks";

    //the c_str() function returns a const pointer

    //to null terminated contents.

    const char *str = st.c_str();

    //printing the char array

    cout << str;

    return 0;

Output

GeeksForGeeks

Time complexity: O(n)


Auxiliary Space: O(1)

12. C++ string class and its applications  , Set 2

In C++ we can store string by one of the two ways –


1. C style strings
2. string class (discussed in this post)
In this post, the second method is discussed. string class is part of C++ library that supports a lot much
functionality over C style strings.
C++ string class internally uses char array to store character but all memory management, allocation,
and null termination is handled by string class itself that is why it is easy to use. The length of the C++
string can be changed at runtime because of dynamic allocation of memory similar to vectors. As string
class is a container class, we can iterate over all its characters using an iterator similar to other
containers like vector, set and maps, but generally, we use a simple for loop for iterating over the
characters and index them using the [] operator.
C++ string class has a lot of functions to handle string easily. Most useful of them are demonstrated in
below code.

// C++ program to demonstrate various function string class


#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // various constructor of string class
  
    // initialization by raw string
    string str1("first string");
  
    // initialization by another string
    string str2(str1);
  
    // initialization by character with number of
occurrence
    string str3(5, '#');
  
    // initialization by part of another string
    string str4(str1, 6, 6); //    from 6th index
(second parameter)
                             // 6 characters (third
parameter)
  
    // initialization by part of another string :
iterator version
    string str5(str2.begin(), str2.begin() + 5);
  
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    cout << str4 << endl;
    cout << str5 << endl;
  
    //  assignment operator
    string str6 = str4;
  
    // clear function deletes all character from
string
    str4.clear();
  
    //  both size() and length() return length of
string and
    //  they work as synonyms
    int len = str6.length(); // Same as "len = str6.size();"
  
    cout << "Length of string is : " << len << endl;
  
    // a particular character can be accessed using
at /
    // [] operator
    char ch = str6.at(2); //  Same as "ch = str6[2];"
  
  
    cout << "third character of string is : " << ch << endl;
  
    //  front return first character and back returns
last character
    //  of string
  
    char ch_f = str6.front();  // Same as "ch_f = str6[0];"
    char ch_b = str6.back();   // Same as below
                               // "ch_b =
str6[str6.length() - 1];"
  
    cout << "First char is : " << ch_f << ", Last char is : "
         << ch_b << endl;
  
    // c_str returns null terminated char array
version of string
    const char* charstr = str6.c_str();
    printf("%s\n", charstr);
  
    // append add the argument string at the end
    str6.append(" extension");
    //  same as str6 += " extension"
  
    // another version of append, which appends part
of other
    // string
    str4.append(str6, 0, 6);  // at 0th position 6
character
  
    cout << str6 << endl;
    cout << str4 << endl;
  
    //  find returns index where pattern is found.
    //  If pattern is not there it returns predefined
    //  constant npos whose value is -1
  
    if (str6.find(str4) != string::npos)
        cout << "str4 found in str6 at " << str6.find(str4)
             << " pos" << endl;
    else
        cout << "str4 not found in str6" << endl;
  
    //  substr(a, b) function returns a substring of
b length
    //  starting from index a
    cout << str6.substr(7, 3) << endl;
  
    //  if second argument is not passed, string till
end is
    // taken as substring
    cout << str6.substr(7) << endl;
  
    //  erase(a, b) deletes b characters at index a
    str6.erase(7, 4);
    cout << str6 << endl;
  
    //  iterator version of erase
    str6.erase(str6.begin() + 5, str6.end() - 3);
    cout << str6 << endl;
  
    str6 = "This is a examples";
  
    //  replace(a, b, str)  replaces b characters
from a index by str
    str6.replace(2, 7, "ese are test");
  
    cout << str6 << endl;
  
    return 0;
}

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 :

// C++ program to demonstrate uses of some string function


#include <bits/stdc++.h>
using namespace std;
  
// this function returns floating point part of a number-string
string returnFloatingPart(string str)
{
    int pos = str.find(".");
    if (pos == string::npos)
        return "";
    else
        return str.substr(pos + 1);
}
  
// This function checks whether a string contains all digit or not
bool containsOnlyDigit(string str)
{
    int l = str.length();
    for (int i = 0; i < l; i++)
    {
        if (str.at(i) < '0' || str.at(i) > '9')
            return false;
    }
    //  if we reach here all character are digits
    return true;
}
  
// this function replaces all single space by %20
// Used in URLS
string replaceBlankWith20(string str)
{
    string replaceby = "%20";
    int n = 0;
  
    // loop till all space are replaced
    while ((n = str.find(" ", n)) != string::npos )
    {
        str.replace(n, 1, replaceby);
        n += replaceby.length();
    }
    return str;
}
  
// driver function to check above methods
int main()
{
    string fnum = "23.342";
    cout << "Floating part is : " << returnFloatingPart(fnum) 
         << endl;
  
    string num = "3452";
    if (containsOnlyDigit(num))
        cout << "string contains only digit" << endl;
  
    string urlex = "google com in";
    cout << replaceBlankWith20(urlex) << endl;
  
    return 0;      
}

Output :
Floating part is : 342
string contains only digit
google%20com%20in

13. How to create a dynamic 2D array inside a class in C++ ?

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

// C++ program to demonstrate class of graphs

class Graph

  int V;

  int adj[V][V];  // This line doesn't work

   

  /* Rest of the members */

};

int main()

Output :

error: invalid use of non-static data

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

// C++ program to demonstrate

// how to allocate dynamic 2D

// array in a class using a Graph

#include <bits/stdc++.h>

using namespace std;

 
// A Class to represent directed graph

class Graph {

    int V; // No. of vertices

    // adj[u][v] would be true if there is an edge

    // from u to v, else false

    bool** adj;

public:

    Graph(int V); // Constructor

    // function to add an edge to graph

    void addEdge(int u, int v) { adj[u][v] = true; }

    void print();

};

Graph::Graph(int V)

    this->V = V;

    // Create a dynamic array of pointers

    adj = new bool*[V];

    // Create a row for every pointer

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

        // Note : Rows may not be contiguous

        adj[i] = new bool[V];


 

        // Initialize all entries as false to indicate

        // that there are no edges initially

        memset(adj[i], false, V * sizeof(bool));

    }

// Utility method to print adjacency matrix

void Graph::print()

    for (int u = 0; u < V; u++) {

        for (int v = 0; v < V; v++)

            cout << adj[u][v] << " ";

        cout << endl;

    }

// Driver method

int main()

    // Create a graph given in the above diagram

    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:

// Wrong!! (Rows of matrix at different addresses)

memset(adj, false, V*V*sizeof(bool));

14. Lexicographically next permutation

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

// C++ program to demonstrate class of graphs

class Graph

  int V;
  int adj[V][V];  // This line doesn't work

   

  /* Rest of the members */

};

int main()

Output :

error: invalid use of non-static data

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

// C++ program to demonstrate

// how to allocate dynamic 2D

// array in a class using a Graph

#include <bits/stdc++.h>

using namespace std;

// A Class to represent directed graph

class Graph {

    int V; // No. of vertices

    // adj[u][v] would be true if there is an edge


    // from u to v, else false

    bool** adj;

public:

    Graph(int V); // Constructor

    // function to add an edge to graph

    void addEdge(int u, int v) { adj[u][v] = true; }

    void print();

};

Graph::Graph(int V)

    this->V = V;

    // Create a dynamic array of pointers

    adj = new bool*[V];

    // Create a row for every pointer

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

        // Note : Rows may not be contiguous

        adj[i] = new bool[V];

        // Initialize all entries as false to indicate

        // that there are no edges initially

        memset(adj[i], false, V * sizeof(bool));

    }
}

// Utility method to print adjacency matrix

void Graph::print()

    for (int u = 0; u < V; u++) {

        for (int v = 0; v < V; v++)

            cout << adj[u][v] << " ";

        cout << endl;

    }

// Driver method

int main()

    // Create a graph given in the above diagram

    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:

// Wrong!! (Rows of matrix at different addresses)

memset(adj, false, V*V*sizeof(bool));

15. Print size of array parameter

How to compute the size of an array parameter in a function?


Consider below C++ program:
 

 CPP

// A C++ program to show that it is wrong to

// compute size of an array parameter in a function

#include <iostream>

using namespace std;

void findSize(int arr[])

    cout << sizeof(arr) << endl;

int main()

    int a[10];

    cout << sizeof(a) << " ";


    findSize(a);

    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

// A C++ program to show that we can use reference to

// find size of array

#include <iostream>

using namespace std;

void findSize(int (&arr)[10])

    cout << sizeof(arr) << endl;

int main()

    int a[10];

    cout << sizeof(a) << " ";

    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

// A C++ program to show that we use template and

// reference to find size of integer array parameter

#include <iostream>

using namespace std;

template <size_t n>

void findSize(int (&arr)[n])

    cout << sizeof(int) * n << endl;

int main()

    int a[10];

    cout << sizeof(a) << " ";

    findSize(a);

    return 0;

Output: 

40 40
We can make a generic function as well:
 

 CPP

// A C++ program to show that we use template and

// reference to find size of any type array parameter

#include <iostream>

using namespace std;

template <typename T, size_t n>

void findSize(T (&arr)[n])

    cout << sizeof(T) * n << endl;

int main()

    int a[10];

    cout << sizeof(a) << " ";

    findSize(a);

    float f[20];

    cout << sizeof(f) << " ";

    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>

using namespace std;

int main()

    int *arr = (int*)malloc(sizeof(int) * 20);

    return 0;

16. Split a string in C/C++, Python and Java

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:  

// Splits str[] according to given delimiters.

// and returns next token. It needs to be called

// in a loop to get all tokens. It returns NULL

// when there are no more tokens.

char * strtok(char str[], const char *delims);

 C

// A C/C++ program for splitting a string

// using strtok()

#include <stdio.h>

#include <string.h>
 

int main()

    char str[] = "Geeks-for-Geeks";

    // Returns first token

    char *token = strtok(str, "-");

   

    // Keep printing tokens while one of the

    // delimiters present in str[].

    while (token != NULL)

    {

        printf("%s\n", token);

        token = strtok(NULL, "-");

    }

    return 0;

Output: Geeks

for

Geeks

Time complexity : O(n)

Auxiliary Space: O(n)

In C++

Note: The main disadvantage of strtok() is that it only works for C style strings.

Therefore we need to explicitly convert C++ string into a char array.

Many programmers are unaware that C++ has two additional APIs which are more elegant

and works with C++ string.


Method 1: Using  stringstream API of C++

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.

Some of the Most Common used functions of StringStream.

clear() — flushes the stream

str() — converts a stream of words into a C++ string object.

operator << — pushes a string object into the stream.

operator >> — extracts a word from the stream.

 The code below demonstrates it. 

 C++

#include <bits/stdc++.h>

using namespace std;

// A quick way to split strings separated via spaces.

void simple_tokenizer(string s)

    stringstream ss(s);

    string word;

    while (ss >> word) {

        cout << word << endl;

    }

// A quick way to split strings separated via any character

// delimiter.

void adv_tokenizer(string s, char del)

{
    stringstream ss(s);

    string word;

    while (!ss.eof()) {

        getline(ss, word, del);

        cout << word << endl;

    }

int main(int argc, char const* argv[])

    string a = "How do you do!";

    string b = "How$do$you$do!";

    // Takes only space separated C++ strings.

    simple_tokenizer(a);

    cout << endl;

    adv_tokenizer(b, '$');

    cout << endl;

    return 0;

Output : How

do

you

do!

Method 2: Using C++ find() and substr() APIs.

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>

using namespace std;

void tokenize(string s, string del = " ")

    int start, end = -1*del.size();

    do {

        start = end + del.size();

        end = s.find(del, start);

        cout << s.substr(start, end - start) << endl;

    } while (end != -1);

int main(int argc, char const* argv[])

    // Takes C++ string with any separator

    string a = "How$%do$%you$%do$%!";

    tokenize(a, "$%");

    cout << endl;

    return 0;

Output: Hi

do

you

do

Method 3: Using  temporary string

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>

using namespace std;

void split(string str, char del){

    // declaring temp string to store the curr "word" upto del

      string temp = "";

   

      for(int i=0; i<(int)str.size(); i++){

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

            cout << temp << " ";

              temp = "";

        }

    }

       

      cout << temp;

int main() {

    string str = "geeks_for_geeks";    // string to be split

     char del = '_';    // delimiter around which string is to be split


   

      split(str, del);

     

    return 0;

Output

geeks for geeks

Time complexity : O(n)

Auxiliary Space: O(n)

In Java : 
In Java, split() is a method in String class. 

// expregexp is the delimiting regular expression;

// limit is the number of returned strings

public String[] split(String regexp, int limit);

// We can call split() without limit also

public String[] split(String regexp)

 Java

// A Java program for splitting a string

// using split()

import java.io.*;

public class Test

    public static void main(String args[])

    {

        String Str = new String("Geeks-for-Geeks");

        // Split above string in at-most two strings 


        for (String val: Str.split("-", 2))

            System.out.println(val);

        System.out.println("");

   

        // Splits Str into all possible tokens

        for (String val: Str.split("-"))

            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.  

// regexp is the delimiting regular expression;

// limit is limit the number of splits to be made

str.split(regexp = "", limit = string.count(str))

 Python3

line = "Geek1 \nGeek2 \nGeek3"

print(line.split())

print(line.split(' ', 1))

Output: 
['Geek1', 'Geek2', 'Geek3']

['Geek1', '\nGeek2 \nGeek3']

17. Stringstream in C++ and its applications

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. 

Basic methods are:

1. clear()- To clear the stream.


2. str()- To get and set string object whose content is present in the stream. 
3. operator <<- Add a string to the stringstream object. 
4. operator >>- Read something from the stringstream object.

Examples:

1. Count the number of words in a string

Examples:

Input:  Asipu Pawan Kumar


Output:  3

Input:  Geeks For Geeks Ide


Output:  4

Below is the C++ program to implement the above approach-

 C++

// C++ program to count words in 

// a string using stringstream.

#include <iostream>

#include <sstream>

#include<string>

using namespace std;

int countWords(string str)

    // Breaking input into word

    // using string stream


   

    // Used for breaking words

    stringstream s(str);

   

    // To store individual words

    string word;

    int count = 0;

    while (s >> word)

        count++;

    return count;

// Driver code

int main()

    string s = "geeks for geeks geeks "

               "contribution placements";

    cout << " Number of words are: " << countWords(s);

    return 0;

Output

Number of words are: 6

2. Print frequencies of individual words in a string

Examples:

Input:  Geeks For Geeks Quiz Geeks Quiz Practice Practice


Output:  For -> 1
              Geeks -> 3
              Practice -> 2
              Quiz -> 2
Input:  Word String Frequency String
Output:  Frequency -> 1
              String -> 2
              Word -> 1      

Below is the C++ program to implement the above approach-

 C++

// C++ program to demonstrate use

// of stringstream to count

// frequencies of words.

#include <bits/stdc++.h>

#include <iostream>

#include <sstream>

#include<string>

using namespace std;

void printFrequency(string st)

    // Each word it mapped to

    // it's frequency

    map<string, int>FW;

   

    // Used for breaking words

    stringstream ss(st);

   

    // To store individual words

    string Word;

    while (ss >> Word)

        FW[Word]++;
 

    map<string, int>::iterator m;

    for (m = FW.begin(); m != FW.end(); m++)

        cout << m->first << "-> "

             << m->second << "\n";

// Driver code

int main()

    string s = "Geeks For Geeks Ide";

    printFrequency(s);

    return 0;

Output

For-> 1

Geeks-> 2

Ide-> 1

18. Strchr() function in C/C++

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

// C++ program to demonstrate working strchr()


#include <iostream>
#include <cstring>
using namespace std;
 
int main()
{
  char str[] = "This is a string";
  char * ch = strrchr(str,'a');
  cout << ch - str + 1;
  return 0;
}

Output: 
 
9
C Examples : 
 
 C

// C code to demonstrate the working of


// strrchr()
 
#include <stdio.h>
#include <string.h>
 
// Driver function
int main()
{
 
    // initializing variables
    char st[] = "GeeksforGeeks";
    char ch = 'e';
    char* val;
 
    // Use of strrchr()
    // returns "ks"
    val = strrchr(st, ch);
 
    printf("String after last %c is :  %s \n", ch,
val);
 
    char ch2 = 'm';
 
    // Use of strrchr()
    // returns null
    // test for null
    val = strrchr(st, ch2);
 
    printf("String after last %c is :  %s ", ch2,
val);
 
    return (0);
}

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

// C code to demonstrate the application of


// strrchr()
 
#include <stdio.h>
#include <string.h>
 
// Driver function
int main()
{
 
    // initializing the denomination
    char denom[] = "Rs 10000000";
 
    // Printing original string
    printf("The original string is : %s", denom);
 
    // initializing the initial number
    char first = '1';
    char* entire;
 
    // Use of strrchr()
    // returns entire number
    entire = strrchr(denom, first);
 
    printf("\nThe denomination value is : %s ",
entire);
 
    return (0);
}

Output: 
 
The original string is : Rs 10000000
The denomination value is : 10000000

19. Isspace() in C/C++ and its application to count whitespace characters

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:

Input : string = 'Geeks for geeks'

Output : 2

Input :string = 'My name is Ayush'

Output : 3

 C++
 C

// C++ program to illustrate

// isspace() function

#include <iostream>

using namespace std;

int main()

    // taking input

    char ch = ' ';

    // checking is it space?

    if (isspace(ch))

        cout << "\nEntered character is space";

    else

        cout << "\nEntered character is not space";

   
    return 0;

// This code is contributed by sarajadhav12052009

Output :

Entered character is space

Application: isspace() function is used to find number of spaces in a given sentence. Examples:

Input : This is a good website

Output : Number of spaces in the sentence is : 4

Input : heyy this is geeksforgeeks

Output : Number of spaces in the sentence is : 3

Input : hello how can I help you

Output : Number of spaces in the sentence is : 5

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

// C++ program to illustrate

// isspace() function

#include <iostream>

using namespace std;

// Function for counting spaces

int cnt_space(int i, int count, char ch)


{

    // input sentence

    char buf[50] = "Geeks for Geeks";

    ch = buf[0];

    // counting spaces

    while (ch != '\0') {

        ch = buf[i];

        if (isspace(ch))

            count++;

        i++;

    }

    // returning number of spaces

    return (count);

int main()

    char ch;

    int i = 0, count = 0;

    // Calling function

    count = cnt_space(i, count, ch);

 
    // printing number of spaces

    cout << "\nNumber of spaces in the sentence is : " << count;

    return 0;

// This code is contributed by sarajadhav12052009

Output:

Number of spaces in the sentence is : 2

 CPP

// CPP program to count white spaces in a string

#include <iostream>

#include <cstring>

#include <cctype>

using namespace std;

// function to calculate whitespaces

void space(string& str)

    int count = 0;

    int length = str.length();

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

        int c = str[i];

        if (isspace(c))

            count++;

    }
    cout << count;

// Driver Code

int main()

    string str = "Geeks for geeks";

    space(str);

    return 0;

Output:

20. Char* vs std:string vs char[] in C++

In this article, we are going to inspect three different ways of initializing strings in C++ and discuss
differences between them.

1. Using char*

Here, str is basically a pointer to the (const)string literal. Syntax:

char* str = "This is GeeksForGeeks";

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

// CPP program to illustrate *char

#include <iostream>

using namespace std;

 
int main()

    // pointer str points to const string literal "Hello".

    // No need to declare size.

    char* str1 = "This is GeeksForGeeks";

    cout << str1 << endl;

    int size = 30;

    // can allocate size dynamically.

    char* str2 = (char*)malloc(sizeof(char) * size);

    str2 = "GeeksForGeeks For Everyone";

    cout << str2;

    return 0;

Output:

This is GeeksForGeeks

GeeksForGeeks For Everyone

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

const char* str = "This is GeeksForGeeks";

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

// CPP program to illustrate assigning

// *char value to other variable

#include <iostream>

using namespace std;

int main()

    // This initialization gives warning in C++.

    // "deprecated conversion from string constant

    // to 'char*'"

    char* str = "Hello";

    const char* str1 = "Hello"; // No warning

    // trying to modify const string literal

    // gives Runtime error

    str[1] = 'o';

    cout << str << endl;

    return 0;

1. Output:

Segmentation Fault

2. Using std::string

Syntax:

std::string str = "This is GeeksForGeeks";


Here str is the object of std::string class which is an instantiation of the basic_string class template that
uses char (i.e., bytes) as its character type. Note: Do not use cstring or string.h functions when you are
declaring string with std::string keyword because std::string strings are of basic_string class type and
cstring strings are of const char* type. Pros: When dealing exclusively in C++ std:string is the best way
to go because of better searching, replacement, and manipulation functions. Some of the useful std:string
functions are discussed below. 

 CPP

// CPP program to illustrate

// std::string functions

#include <iostream>

using namespace std;

int main()

    // string assignment

    string s1 = "Hello";

    string s2 = "World";

    // return length of string

    cout << s1.size() << endl; // 5

    cout << s2.length() << endl; // 5

    // concatenate string using + operator.

    s1 = s1 + s2;

    cout << s1 << endl; // HelloWorld

    // append string

    s1.append("Geeks");

    cout << s1 << endl; // HelloWorldGeeks

 
    string s3 = "HelloWorldGeeks";

    // compare two strings

    if (s1.compare(s3) == 0)

        cout << "true" << endl;

    else

        cout << "false" << endl;

    // substring of string s1

    // substr(pos, length_of_substring)

    string sub = s1.substr(0, 5);

    cout << sub << endl; // Hello

    // insert into string

    // insert(pos, string)

    s1.insert(10, "For");

    cout << s1 << endl; // HelloWorldForGeeks

    string target = "World";

    // find a target string in s1

    size_t pos = s1.find(target);

    if (pos != std::string::npos) // npos=-1

        cout << "Found at Position:" << pos << endl; // pos=5

    // replace a portion of string s1

    // replace(pos, length_of_portion, string_to_replace)


    cout << s1.replace(5, 5, "Geeks") << endl; // HelloGeeksForGeeks

    return 0;

Output:

HelloWorld

HelloWorldGeeks

true

Hello

HelloWorldForGeeks

Found at Position:5

HelloGeeksForGeeks

Cases where you might prefer char* over std:string

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:

char str[] = "This is GeeksForGeeks";

or

char str[size] = "This is GeeksForGeeks";

// Here str is a array of characters denoting the string.

Pros:

1. We can modify the string at later stage in program.

 CPP
// CPP program to illustrate char

#include <iostream>

using namespace std;

int main()

    char str[] = "Hello";

    // or char str1[]={'H', 'e', 'l', 'l', 'o', '\0'};

    // modify string to "Hollo"

    str[1] = 'o';

    cout << str << endl;

    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

// CPP program to illustrate char

// concatenation using standard functions

#include <iostream>
#include <cstring>

using namespace std;

int main()

    // take large size of array

    char str[10] = "Hello";

    cout << "Before Concatenation : " << str << endl; // Hello

    strcat(str, " World");

    cout << "After Concatenation : " << str; // Hello World

    return 0;

1. Output:

Before Concatenation : Hello

After Concatenation : Hello World

Here are couple of other useful functions of C++ standard library cstring. 

 CPP

#include <iostream>

#include <cstring>

using namespace std;

int main()

    char s1[10] = "Hello";


 

    // return length of s1

    cout << strlen(s1) << endl;

    char s2[50];

    // copies s1 into s2

    strcpy(s2, s1);

    cout << s2 << endl;

    char s3[10] = "World";

    // concatenates s3 into s2

    strcat(s2, s3);

    cout << s2 << endl;

    char s4[50] = "HelloWorld";

    // return 0 if s2 and s4 are equal.

    if (strcmp(s2, s4) == 0)

        cout << "true" << endl;

    else

        cout << "false" << endl;

    char s5[30];

    // copies first 5 chars of s4 into s5


    strncpy(s5, s4, 5);

    cout << s5 << endl;

    char target[10] = "Hello";

    // search for target string in s4

    if (strstr(s4, target) != NULL)

        cout << "true" << endl;

    else

        cout << "false" << endl;

    return 0;

Output :

Hello

HelloWorld

true

Hello

true

21. Std::lexicographical_compare() in C++STL

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. 

It has the following two implementations:


Syntax 1: 

lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2)

Template:

template

bool lexicographical_compare(iter1 beg1, iter1 end1,

iter2 beg2, iter2 end2)

while (beg1!=end1)

if (beg2==end2 || *beg2<*beg1) return false;

else if (*beg1<*beg2) return true;

++beg1; ++beg2;

return (beg2!=end2);

Parameters:

 beg1:  Input iterator to the initial position of the first sequence.


 end1:  Input iterator to the final position of the first sequence.
 beg2:  Input iterator to initial position of the second sequence.
 end2:  Input iterator to the final position of the second sequence.

Return value: Returns a boolean true, if range1 is strictly lexicographically smaller than range2 else
returns a false.

Example:

 CPP

// C++ code to demonstrate the working of

// lexicographical_compare(), implementation 1

#include <algorithm>

#include <iostream>

using namespace std;

  
// Driver Code

int main()

    // initializing char arrays

    char one[] = "geeksforgeeks";

    char two[] = "gfg";

  

    // using lexicographical_compare for checking

    // is "one" is less than "two"

    if (lexicographical_compare(one, one + 13, two,

                                two + 3))

        cout << "geeksforgeeks is lexicographically less "

                "than gfg";

    else

        cout << "geeksforgeeks is not lexicographically "

                "less than gfg";

Output

geeksforgeeks is lexicographically less than gfg

Syntax 2: 

lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2, Compare comp)

Template:

template

bool lexicographical_compare(iter1 beg1, iter1 end1,

iter2 beg2, iter2 end2)

while (beg1!=end1)

{
if (beg2==end2 || *beg2<*beg1) return false;

else if (*beg1<*beg2) return true;

++beg1; ++beg2;

return (beg2!=end2);

Parameters: 

 beg1:  Input iterator to the initial position of the first sequence.


 end1:  Input iterator to the final position of the first sequence.
 beg2:  Input iterator to initial position of the second sequence.
 end2:  Input iterator to the final position of the second sequence.
 comp: The comparator function that returns a Boolean true/false of each element compared. This
function accepts two arguments. This can be a function pointer or function object and cannot
change values.

Return value: Returns a Boolean true, if range1 is strictly lexicographically smaller than range2 else
returns a false.

Example:

 CPP

// C++ code to demonstrate the working of

// lexicographical_compare()

#include <algorithm>

#include <iostream>

using namespace std;

  

// helper function to convert all into lower case:

bool comp(char s1, char s2)

    return tolower(s1) < tolower(s2);

  

// Driver Code
int main()

    // initializing char arrays

    char one[] = "geeksforgeeks";

    char two[] = "Gfg";

  

    // using lexicographical_compare for checking

    // is "one" is less than "two"

    // returns false as "g" has larger ASCII value than "G"

    if (lexicographical_compare(one, one + 13, two,

                                two + 3))

        cout << "geeksforgeeks is lexicographically less "

                "than Gfg\n";

    else

        cout << "geeksforgeeks is not lexicographically "

                "less than Gfg\n";

  

    // using lexicographical_compare for checking

    // is "one" is less than "two"

    // returns true this time as all converted into

    // lowercase

    if (lexicographical_compare(one, one + 13, two, two + 3,

                                comp)) {

        cout << "geeksforgeeks is lexicographically less ";

        cout << "than Gfg( case-insensitive )";

    }

    else {
        cout << "geeksforgeeks is not lexicographically "

                "less ";

        cout << "than Gfg( case-insensitive )";

    }

Output

geeksforgeeks is not lexicographically less than Gfg

geeksforgeeks is lexicographically less than Gfg( case-insensitive )

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

// C++ code to demonstrate the application of

// lexicographical_compare()

#include <bits/stdc++.h>

using namespace std;

  

// Driver Code

int main()

    // initializing char arrays

    char list[][100] = { { 'a', 'b', 'a', 'c', 'u', 's' },

                         { 'a', 'p', 'p', 'l', 'e' },

                         { 'c', 'a', 'r' },

                         { 'a', 'b', 'b', 'a' } };

  

    char min[100] = "zzzzzz";


  

    // using lexicographical_compare for checking

    // the smallest

    for (int i = 0; i < 4; i++)

        if (lexicographical_compare(

                list[i], list[i] + strlen(list[i]), min,

                min + strlen(min)))

            strcpy(min, list[i]);

  

    // prints "abacus"

    cout << "The smallest string is : ";

    for (int i = 0; min[i] != '\0'; i++)

        cout << min[i];

Output

The smallest string is : abacus

Exception in lexicographical_compare(): It throws an exception if either an element comparison or an


operation on an iterator throws. If the arguments are invalid, they cause undefined behavior.

22. Std::string::at in C++

std::string::at can be used to extract characters by characters from a given string. 


It supports two different syntaxes both having similar parameters: 
Syntax 1: 
 

char& string::at (size_type idx)

Syntax 2: 
 

const char& string::at (size_type idx) const

idx : index number


Both forms return the character that has the index idx (the first character has index 0).

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.

Return value : Returns character at the specified position in the string.

Exception : Passing an invalid index (less than 0

or greater than or equal to size()) throws an out_of_range exception.

 CPP

// CPP code to demonstrate std::string::at

#include <iostream>

using namespace std;

// Function to demonstrate std::string::at

void atDemo(string str)

    cout << str.at(5);

    // Below line throws out of

    // range exception as 16 > length()

    // cout << str.at(16);

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

// CPP code to extract characters from a given string

#include <iostream>

using namespace std;

// Function to demonstrate std::string::at

void extractChar(string str)

    char ch;

    // Calculating the length of string

    int l = str.length();

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

        ch = str.at(i);

        cout << ch << " ";


    }

// Driver code

int main()

    string str("GeeksForGeeks");

    extractChar(str);

    return 0;

Output: 
 

GeeksForGeeks

23. Std::substr() in C/C++

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:  

1. The index of the first character is 0 (not 1).


2. If pos is equal to the string length, the function returns an empty string.
3. If pos is greater than the string length, it throws out_of_range. If this happens, there are no
changes in the string.
4. If the requested sub-string len is greater than the size of a string, then returned sub-string is [pos,
size()).
5. If len is not passed as a parameter, then returned sub-string is [pos, size()).

Syntax: 

string substr (size_t pos, size_t len) const;

Parameters:

1. pos: Position of the first character to be copied.


2. len: Length of the sub-string.
3. size_t: It is an unsigned integral type.

Return value: 

It returns a string object.

Example:

 CPP

// CPP program to illustrate substr()

#include <string.h>

#include <iostream>

using namespace std;

int main()

    // Take any string

    string s1 = "Geeks";

    // Copy two characters of s1 (starting

    // from position 3)

    string r = s1.substr(3, 2);

    // prints the result

    cout << "String is: " << r;

    return 0;

Output

String is: ks

Time complexity: O(n)

Auxiliary Space: O(n)
Applications:

1. How to get a sub-string after a character? 

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

// CPP program to illustrate substr()

#include <string.h>

#include <iostream>

using namespace std;

int main()

    // Take any string

    string s = "dog:cat";

    // Find position of ':' using find()

    int pos = s.find(":");

    // Copy substring after pos

    string sub = s.substr(pos + 1);

    // prints the result

    cout << "String is: " << sub;

    return 0;

Output
String is: cat

Time complexity: O(n)

Auxiliary Space: O(n)                    

2. How to get a sub-string before a character? 

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

// CPP program to illustrate substr()

#include <string.h>

#include <iostream>

using namespace std;

int main()

    // Take any string

    string s = "dog:cat";

    // Find position of ':' using find()

    int pos = s.find(":");

    // Copy substring before pos

    string sub = s.substr(0 , pos);

    // prints the result

    cout << "String is: " << sub;

    return 0;
}

Output

String is: dog

Time complexity: O(n)

Auxiliary Space: O(n)

3. Print all substrings of a given string

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

// C++ program to demosntrate all possible

// substrings of a given string

#include <bits/stdc++.h>

using namespace std;

// Function to print all sub strings

void subString(string s, int n)

    // Pick starting point in outer loop

    // and lengths of different strings for

    // a given starting point

    for (int i = 0; i < n; i++)

        for (int len = 1; len <= n - i; len++)

            cout << s.substr(i, len) << endl;

// Driver program to test above function


int main()

    string s = "abcd";

    subString(s, s.length());

    return 0;

Output

ab

abc

abcd

bc

bcd

cd

Time complexity: O( n3 )

Auxiliary Space: O(1)

4. Sum of all substrings of a string representing a number

Given an integer represented as a string, we need to get the sum of all possible substrings of this string.

Example:

 C++

// C++ program to print sum of all substring of

// a number represented as a string

#include <bits/stdc++.h>
using namespace std;

// Utility method to convert character digit to

// integer digit

int toDigit(char ch)

    return (ch - '0');

// Returns sum of all substring of num

int sumOfSubstrings(string num)

    int n = num.length();

    // allocate memory equal to length of string

    int sumofdigit[n];

    // initialize first value with first digit

    sumofdigit[0] = toDigit(num[0]);

    int res = sumofdigit[0];

    // loop over all digits of string

    for (int i = 1; i < n; i++) {

        int numi = toDigit(num[i]);

        // update each sumofdigit from previous value

        sumofdigit[i] = (i + 1) * numi + 10 * sumofdigit[i - 1];


 

        // add current value to the result

        res += sumofdigit[i];

    }

    return res;

// Driver code to test above methods

int main()

    string num = "1234";

    cout << sumOfSubstrings(num) << endl;

    return 0;

Output

1670

Time Complexity: O(n)

Auxiliary Space: O(n)

5: Maximum value of all substrings of a string representing a number.

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

// C++ program to demosntrate max. of all possible

// substrings of a given string

#include <bits/stdc++.h>
using namespace std;

void subString(string s, int n)

      vector<int> v;

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

        for (int len = 1; len <= n - i; len++){

             string sub =(s.substr(i, len));

             int x=stoi(sub);

             v.push_back(x);

            }

     }

     cout<<*max_element(v.begin(),v.end())<<endl;

// Driver program to test above function

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!)

6: Minimum value of all substrings of a string representing a number.


Given an integer represented as a string, we need to get the minimum of all possible substrings of the
given string which is representing a number.

Example:

 C++

// C++ program to demosntrate minimum of all possible

// substrings of a given string

#include <bits/stdc++.h>

using namespace std;

void subString(string s, int n)

      vector<int> v;

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

        for (int len = 1; len <= n - i; len++){

             string sub =(s.substr(i, len));

             int x=stoi(sub);

             v.push_back(x);

            }

     }

     cout<<*min_element(v.begin(),v.end())<<endl;

// Driver program to test above function

int main()

    string s = "4572";

    subString(s, s.length());

    return 0;

}
Output:

Time complexity: O(N^3)

Auxiliary space: O(N!)

24. std::stol() and std::stoll() functions in C++

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.

// CPP code for illustration


// of stol() function.
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // converting decimal number.
    string dec_num = "9876543210";
    cout << "dec_num = " << 
    stol(dec_num, nullptr, 10) << "\n";
  
    // converting hexadecimal number.
    string hex_num = "FFFFFF";
    cout << "hex_num = " << 
    stol(hex_num, nullptr, 16) << "\n";
  
    // converting binary number.
    string binary_num = "1111111";
    cout << "binary_num = " << 
    stol(binary_num, nullptr, 2) << "\n";
  
    return 0;
}

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.

// CPP code for illustration


// of stoll() function.
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // converting decimal number.
    string dec_num = "9876543210";
    cout << "dec_num = " << 
    stoll(dec_num, nullptr, 10) << "\n ";
  
         
    // converting hexadecimal number.
    string hex_num = "FFFFFF";
    cout << "hex_num = " << 
    stoll(hex_num, nullptr, 16) << "\n";
  
    // converting binary number.
    string binary_num = "1111111";
    cout << "binary_num = " <<
    stoll(binary_num, nullptr, 2) << "\n";
  
        return 0;
}

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

25. Extract all integers from string in C++

Symmetric difference of two sorted ranges 


The symmetric difference between two sets is formed by the elements that are present in one of the sets,
but not in the other. Among the equivalent elements in each range, those discarded are those that
appear before in the existent order before the call. The existing order is also preserved for the copied
elements.
The elements are compared using operator< for the first version, and comp for the second. Two
elements, a and b are considered equivalent if (!(a<b) && !(b<a)) or if (!comp(a, b) && !comp(b, a)).
The elements in the ranges shall already be ordered.
1. Using default operator< :
Syntax : 
 

Template :

OutputIterator set_symmetric_difference (InputIterator1 first1, InputIterator1 last1,

InputIterator2 first2, InputIterator2 last2,

OutputIterator result);
Parameters :

first1, last1

Input iterators to the initial and final positions of the first

sorted sequence. The range used is [first1, last1), which contains

all the elements between first1 and last1, including the element

pointed by first1 but not the element pointed by last1.

first2, last2

Input iterators to the initial and final positions of the second

sorted sequence. The range used is [first2, last2).

result

Output iterator to the initial position of the range where the

resulting sequence is stored.

The pointed type shall support being assigned the value of an

element from the other ranges.

comp

Binary function that accepts two arguments of the types pointed

by the input iterators, and returns a value convertible to bool.

The function shall not modify any of its arguments.

This can either be a function pointer or a function object.

The ranges shall not overlap.

Return Type :

An iterator to the end of the constructed range.

 
 CPP

// CPP program to illustrate

// std :: set_symmetric_difference

#include <algorithm> // std::set_symmetric_difference, std::sort

#include <iostream> // std::cout

#include <vector> // std::vector

// Driver code

int main()

    int first[] = { 5, 10, 15, 20, 25 };

    int second[] = { 50, 40, 30, 20, 10 };

    int n = sizeof(first) / sizeof(first[0]);

    // Print first array

    std::cout << "First array contains :";

    for (int i = 0; i < n; i++)

        std::cout << " " << first[i];

    std::cout << "\n";

    // Print second array

    std::cout << "Second array contains :";

    for (int i = 0; i < n; i++)

        std::cout << " " << second[i];

    std::cout << "\n\n";

    std::vector<int> v(10);

    std::vector<int>::iterator it, st;


 

    // Sorting both the arrays

    std::sort(first, first + 5);

    std::sort(second, second + 5);

    // Using default operator<

    it = std::set_symmetric_difference(first, first + 5,

    second, second + 5, v.begin());

    std::cout << "The symmetric difference has "

              << (it - v.begin()) << " elements:\n";

    for (st = v.begin(); st != it; ++st)

        std::cout << ' ' << *st;

    std::cout << '\n';

    return 0;

Output: 
 

First array contains : 5 10 15 20 25

Second array contains : 50 40 30 20 10

The symmetric difference has 6 elements:

5 15 25 30 40 50

2. Using custom function :


Syntax : 
 

Template :

OutputIterator set_symmetric_difference (InputIterator1 first1, InputIterator1 last1,


InputIterator2 first2, InputIterator2 last2,

OutputIterator result, Compare comp);

Parameters :

first1, last1, first2, last2, result are same as described above.

comp

Binary function that accepts two arguments of the types pointed

by the input iterators, and returns a value convertible to bool.

The function shall not modify any of its arguments.

This can either be a function pointer or a function object.

The ranges shall not overlap.

Return Type :

An iterator to the end of the constructed range.

 CPP

// CPP program to illustrate

// std :: set_symmetric_difference

#include <algorithm> // std::set_symmetric_difference, std::sort

#include <iostream> // std::cout

#include <vector> // std::vector

// Custom function

bool comp(int a, int b)

{
    return a < b;

// Driver code

int main()

    int first[] = { 5, 10, 15, 20, 25 };

    int second[] = { 50, 40, 30, 20, 10 };

    int n = sizeof(first) / sizeof(first[0]);

    // Print first array

    std::cout << "First array contains :";

    for (int i = 0; i < n; i++)

        std::cout << " " << first[i];

    std::cout << "\n";

    // Print second array

    std::cout << "Second array contains :";

    for (int i = 0; i < n; i++)

        std::cout << " " << second[i];

    std::cout << "\n\n";

    std::vector<int> v(10);

    std::vector<int>::iterator it, st;

    // Sorting both the arrays

    std::sort(first, first + 5);


    std::sort(second, second + 5);

    // Using default operator<

    it = std::set_symmetric_difference(first, first + 5,

                                       second, second + 5, v.begin(), comp);

    std::cout << "The symmetric difference has "

              << (it - v.begin()) << " elements:\n";

    for (st = v.begin(); st != it; ++st)

        std::cout << ' ' << *st;

    std::cout << '\n';

    return 0;

Output: 
 

First array contains : 5 10 15 20 25

Second array contains : 50 40 30 20 10

The symmetric difference has 6 elements:

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

// CPP program to illustrate

// std :: set_symmetric_difference
#include <bits/stdc++.h>

using namespace std;

int main()

    // students attending first class

    std::vector<string> class1{ "Samir", "Manoj", "Pranav", "Rajesh" };

    // students attending second class

    std::vector<string> class2{ "Samir", "Junaid", "Manoj", "Pankaj",


"Arpit" };

    cout << "Students attending first class are : ";

    for (auto i : class1) {

        cout << i << " ";

    }

    cout << "\nStudents attending second class are : ";

    for (auto i : class2) {

        cout << i << " ";

    }

    // to store the result of symmetric difference

    std::vector<string> result(10);

    std::vector<string>::iterator it;

    // finding symmetric difference


    it = set_symmetric_difference(class1.begin(),

                                  class1.end(), class2.begin(), class2.end(),


result.begin());

    cout << "\n\nList of students that are not taking both classes :";

    for (std::vector<string>::iterator i = result.begin(); i != it; i++) {

        cout << *i << " ";

    }

    return 0;

OUTPUT : 
 

Students attending first class are : Samir Manoj Pranav Rajesh

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. 

26. Strchr() function in C++ and its applications

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:

// Returns pointer to the first occurrence


// of c in str[]
char *strchr(const char *str, int c) 

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: 

Input :  str[] = ‘This is a string’


Output :  9
Input :  str[] = ‘My name is Ayush’
Output :  5

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.

Below is the implementation of the above algorithm:

 CPP

// CPP program to find position of a character

// in a given string.

#include <iostream>

#include <cstring>

using namespace std;

int main()

    char str[] = "My name is Ayush";

    char* ch = strchr(str, 'a');

    cout << ch - str + 1;

    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” 

Input :  str[] = ‘My name is Ayush’, 


        ch1 = ‘A’, ch2 = ‘z’
Output :  A is present in the string
          z is not present in the string

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.

Below is the implementation of the above algorithm:

 CPP

// CPP program to demonstrate working of strchr()

#include <iostream>

#include <cstring>

using namespace std;

// Driver code

int main()

    char str[] = "My name is Ayush";

    char ch = 'A', ch2 = 'z';

    if (strchr(str, ch) != NULL)

        cout << ch << " "

             << "is present in string" << endl;

    else

        cout << ch << " "

             << "is not present in string" << endl;

    if (strchr(str, ch2) != NULL)

        cout << ch2 << " "

             << "is present in string" << endl;

    else

        cout << ch2 << " "

             << "is not present in string" << endl;

    return 0;

Output
A is present in string

z is not 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

// C program to find directory path

#include <string.h>

#include<stdio.h>

   

int main()

   char string[]={"/home/test/sample"};

   int len;

     

    //position of last char

    char* pos;

    // save length of string

    len = strlen(string);

    // Find the last character with

    pos = strrchr(string,'/') ;
    printf("%s\n",string);

    // replace last occurrence of / with NULL character.

    *pos='\0';                 

    printf("%s\n",string);

    return 0;

Output

/home/test/sample

/home/test

27. Strcat() vs strncat() in C++

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

// CPP program to demonstrate

// strcat

#include <cstring>

#include <iostream>

using namespace std;

int main()

{
    char dest[50] = "This is an";

    char src[50] = " example";

    strcat(dest, src);

    cout << dest ;

    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

// CPP program to demonstrate

// strncat

#include <cstring>

#include <iostream>

using namespace std;

int main()

{
    char dest[25] = "This is an example";

    char src[50] = " to show working of strncat() this is not added";

     

strncat(dest, src, 29);

    cout << dest ;

    return 0;

Output: 

This is an example to show working of strncat()

How strncat() is different from strcat() ?

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

// C,C++ program demonstrate difference between

// strncat() and strcat()

#include <stdio.h>

#include <string.h>

int main()

   

   // Take any two strings

   char src[50] = "forgeeks";

   char dest1[50] = "geeks";


   char dest2[50] = "geeks";

  

   printf("Before strcat() function execution, ");

   printf("destination string : %s\n", dest1);

    

   // Appends the entire string of src to dest1

   strcat(dest1, src);

  

   // Prints the string

   printf("After strcat() function execution, ");

   printf("destination string : %s\n", dest1);

  

   printf("Before strncat() function execution, ");

   printf("destination string : %s\n", dest2);

    

   // Appends 3 characters from src to dest2

   strncat(dest2, src, 3);

     

   // Prints the string

   printf("After strncat() function execution, ");

   printf("destination string : %s\n", dest2);

    

   return 0;

Output:  

Before strcat() function execution, destination string : geeks

After strcat() function execution, destination string : geeksforgeeks

Before strncat() function execution, destination string : geeks


After strncat() function execution, destination string : geeksfor

28. Strncat() function in C/C++

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 –

 The strings overlap.


 The dest array is not large enough to append the contents of src.

Syntax: 

char *strncat(char *dest, const char *src, size_t n)

Parameters: This method accepts the following parameters: 

 dest: the string where we want to append.


 src: the string from which ‘n’ characters are going to append.
 n: represents a maximum number of characters to be appended. size_t is an unsigned integral
type.

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:  

Input: src = "world"

dest = "Hello "

Output: "Hello world"

Input: src = "efghijkl"

dest = "abcd"

Output: "abcdefghi"

Program:  

 C++
 C

// C,C++ program demonstrate functionality of strncat()


#include <cstring>

#include <iostream>

using namespace std;

int main()

   

   // Take any two strings

   char src[50] = "efghijkl";

   char dest[50]= "abcd";

  

   // Appends 5 character from src to dest

   strncat(dest, src, 5);

     

   // Prints the string

   cout <<"Source string : "<< src << endl;

   cout <<"Destination string : "<< dest;

    

   return 0;

// This code is contributed by shivanisinghss2110

Output: 

Source string : efghijkl

Destination string : abcdefghi

How strncat() is different from strcat() ?


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.
 C++
 C

// C,C++ program demonstrate difference between

// strncat() and strcat()

#include <cstring>

#include <iostream>

using namespace std;

int main()

   

   // Take any two strings

   char src[50] = "forgeeks";

   char dest1[50] = "geeks";

   char dest2[50] = "geeks";

  

   cout << "Before strcat() function execution, ";

   cout << "destination string : "<< dest1 << endl;

    

   // Appends the entire string of src to dest1

   strcat(dest1, src);

  

   // Prints the string

   cout << "After strcat() function execution, ";

   cout << "destination string : "<< dest1 << endl;

  

   cout << "Before strncat() function execution, ";

   cout << "destination string : "<< dest2 << endl;


    

   // Appends 3 characters from src to dest2

   strncat(dest2, src, 3);

     

   // Prints the string

   cout << "After strncat() function execution, ";

   cout << "destination string : "<< dest2 << endl;

    

   return 0;

// this code is contributed by shivanisinghss2110

Output: 

Before strcat() function execution, destination string : geeks

After strcat() function execution, destination string : geeksforgeeks

Before strncat() function execution, destination string : geeks

After strncat() function execution, destination string : geeksfor

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.

// C code to demonstrate the working of


// strpbrk
#include <stdio.h>
#include <string.h>
  
// Driver function
int main()
{
    // Declaring three strings
    char s1[] = "geeksforgeeks";
    char s2[] = "app";
    char s3[] = "kite";
    char* r, *t;
  
    // Checks for matching character
    // no match found
    r = strpbrk(s1, s2); 
    if (r != 0)
        printf("First matching character: %c\n", *r);
    else
        printf("Character not found");
  
    // Checks for matching character
    // first match found at "e"
    t = strpbrk(s1, s3);
    if (t != 0)
        printf("\nFirst matching character: %c\n", *t);
    else
        printf("Character not found");
  
    return (0);
}

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.

// C code to demonstrate practical application


// of strpbrk
#include <stdio.h>
#include <string.h>
  
// Driver function
int main()
{
    // Initializing victory string
    char s1[] = "victory";
  
    // Declaring lottery strings
    char s2[] = "a23";
    char s3[] = "i22";
    char* r, *t;
  
    // Use of strpbrk()
    r = strpbrk(s1, s2);
    t = strpbrk(s1, s3);
  
    // Checks if player 1 has won lottery
    if (r != 0)
        printf("Congrats u have won");
    else
        printf("Better luck next time");
  
    // Checks if player 2 has won lottery
    if (t != 0)
        printf("\nCongrats u have won");
    else
        printf("Better luck next time");
  
    return (0);
}

Output:
Better luck next time
Congrats u have won

30. strcoll() in C/C++

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:

int strcoll(const char *str1, const char *str2)

Parameters: Function strcoll() takes two strings as parameters and returns an integer value.

Value Meaning

less than zero str1 is less than str2

zero str1 is equal to str2

greater than zero str1 is greater than str2

1. less than zero : When  str1 is less than str2 

 C++
 C

// C++ program to illustrate strcoll()


 

#include <iostream>

#include <cstring>

using namespace std;

int main()

    char str1[13];

    char str2[13];

    int ret;

    strcpy(str1, "GEEKSFORGEEKS");

    strcpy(str2, "geeksforgeeks");

    ret = strcoll(str1, str2);

    if (ret > 0) {

        cout << "str1 is greater than str2";

    } else if (ret < 0) {

        cout << "str1 is lesser than str2";

    } else {

        cout << "str1 is equal to str2";

    }

    return 0;

// This code is contributed by sarajadhav12052009


1. Output:

str1 is lesser than str2

1. greater than zero :when str1 is greater than str2 

 C++
 C

// C++ program to illustrate strcoll()

#include <iostream>

#include <cstring>

using namespace std;

int main()

    char str1[13];

    char str2[13];

    int ret;

    strcpy(str1, "geeksforgeeks");

    strcpy(str2, "GEEKSFORGEEKS");

    ret = strcoll(str1, str2);

    if (ret > 0) {

        cout << "str1 is greater than str2";

    } else if (ret < 0) {

        cout << "str1 is lesser than str2";

    } else {

        cout << "str1 is equal to str2";


    }

    return 0;

// This code is contributed by sarajadhav12052009

1. Output:

str1 is greater than str2

1. Is equal to zero : when str1 is equal to str2 

 C++
 C

// C++ program to illustrate strcoll()

#include <iostream>

#include <cstring>

using namespace std;

int main()

    char str1[13];

    char str2[13];

    int ret;

    strcpy(str1, "GEEKSFORGEEKS");

    strcpy(str2, "GEEKSFORGEEKS");

    ret = strcoll(str1, str2);


 

    if (ret > 0) {

        cout << "str1 is greater than str2";

    } else if (ret < 0) {

        cout << "str1 is lesser than str2";

    } else {

        cout << "str1 is equal to str2";

    }

    return 0;

Output:

str1 is equal to str2

31. Why strcpy and strncpy are not safe to use?

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:

char *strcpy( char *dest, const char *src )

Parameters: This function accepts two parameters as mentioned above and described below:

 src: The string which will be copied.


 dest: Pointer to the destination array where the content is to be copied.

Return Value: It returns a pointer to the destination string. 

 C++
 C
// C++ Program to illustrate the

// strcpy() function in C/C++

#include <iostream>

#include <cstring>

using namespace std;

int main()

    char src[] = "geeksforgeeks";

    // Here destination is large enough

    // to store the src with Null

    // character at the end

    char dest[14];

    // copying src into dest.

    strcpy(dest, src);

    cout << "Copied string: " << dest << endl;

     

    return 0;

// This code is contributed by sarajadhav12052009

Output:

Copied string: geeksforgeeks


Problem with strcpy(): The strcpy() function does not specify the size of the destination array,
so buffer overrun is often a risk. Using strcpy() function to copy a large character array into a
smaller one is dangerous, but if the string will fit, then it will not be worth the risk. If the
destination string is not large enough to store the source string then the behavior of strcpy() is
unspecified or undefined. 

 C++
 C

// C++ Program to illustrate the problem in

// strcpy() function in C/C++

#include <iostream>

#include <cstring>

using namespace std;

int main()

    char src[] = "geeksforgeeks";

    // Here destination is not large

    // enough to store the src. so the

    // behaviour of strcpy is unspecified.

    // program may crashed, but its

    // printing geeksforgeeks

    char dest[2];

     

    // copying src into dest.

    strcpy(dest, src);

    cout << "Copied string: " << dest << endl;


     

    return 0;

// This code is contributed by sarajadhav12052009

Output:

Copied string: geeksforgeeks

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:

char *strncpy( char *dest, const char *src, size_t n )

Parameters: This function accepts three parameters as mentioned above and described below:

 src: The string which will be copied.


 dest: Pointer to the destination array where the content is to be copied.
 n: The first n character copied from src to dest.

Return Value: It returns a pointer to the destination string. 

Example: 

 C++
 C

// C++ Program to illustrate the

// strcpy() function in C/C++

#include <iostream>

#include <cstring>

using namespace std;

 
int main()

    char src[] = "geeksforgeeks";

     

    // The destination string size is 14.

    char dest[14];

     

    // copying n bytes of src into dest.

    strncpy(dest, src, 14);

    cout << "Copied string: " << dest << endl;

     

    return 0;

// This code is contributed by sarajadhav12052009

Output:

Copied string: geeksforgeeks

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

// C++ Program to illustrate the problem in

// strcpy() function in C/C++

#include <iostream>
#include <cstring>

using namespace std;

int main()

    char src[] = "geeksforgeeks";

     

    // The destination string size is 8

    // which is less than length of src.

    char dest[8];

     

    // copying 8 bytes of src into dest.

    // dest is not NULL terminated.

    strncpy(dest, src, 8);

     

    // using strlen function on non terminated.

    // string which can cause segfault.

    int len = strlen(dest);

     

    cout << "Copied string: " << dest << endl;

    cout << "Length of destination string: " << len << endl;

     

    return 0;

// This code is contributed by sarajadhav12052009


Output:

Copied string: geeksfor

Length of destination string: 8

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:

if (strlcpy(dst, src, dstsize) >= dest_size)

return -1;

Ranking the functions according to level of sanity:

strcpy < strncpy < snprintf < strlcpy

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

// C++ Program to demonstrate working of a function

#include <iostream>

using namespace std;

// Following function that takes two parameters 'x' and 'y'

// as input and returns max of two input numbers

int max(int x, int y)

    if (x > y)

        return x;

    else

        return y;

// main function that doesn't receive any parameter and

// returns integer

int main()

    int a = 10, b = 20;

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

    int m = max(a, b);

    cout << "m is " << m;

    return 0;

}
Output

m is 20

Why Do We Need Functions?

 Functions help us in reducing code redundancy. If functionality is performed at multiple


places in software, then rather than writing the same code, again and again, we create a
function and call it everywhere. This also helps in maintenance as we have to change at
one place if we make future changes to the functionality.

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

 Functions provide abstraction. For example, we can use library functions without


worrying about their internal work.

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

// C++ Program to show function that takes

// two integers as parameters and returns


// an integer

int max(int, int);

// A function that takes an int

// pointer and an int variable

// as parameters and returns

// a pointer of type int

int* swap(int*, int);

// A function that takes

// a char as parameter and

// returns a reference variable

char* call(char b);

// A function that takes a

// char and an int as parameters

// and returns an integer

int fun(char, int);

Types of Functions
Types of Function in C++

User Defined Function

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.

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. 

Formal Parameter and Actual Parameter

There are two most popular ways to pass 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++

// C++ Program to demonstrate function definition

#include <iostream>

using namespace std;

void fun(int x)

    // definition of

    // function

    x = 30;

int main()

    int x = 20;

    fun(x);

    cout << "x = " << x;

    return 0;

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

// C++ Program to demonstrate working of

// function using pointers

#include <iostream>

using namespace std;

void fun(int* ptr) { *ptr = 30; }

int main()

    int x = 20;

    fun(&x);

    cout << "x = " << x;

    return 0;

Output

x = 30

Difference between call by value and call by reference in C++ 

Call by value Call by reference 

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

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

void function name(int a)

    ....... // Function Body

        return; // Function execution would get terminated

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.

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(){

recursionfunction(); //calling self function

To know more see this article.

C++ Passing Array to Function

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

 C++

functionname(arrayname); //passing array to function

 Example: Print minimum number

 C++

#include <iostream>
using namespace std;

void printMin(int arr[5]);

int main()

    int ar[5] = { 30, 10, 20, 40, 50 };

    printMin(ar); // passing array to function

void printMin(int arr[5])

    int min = arr[0];

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

        if (min > arr[i]) {

            min = arr[i];

        }

    }

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

//Code submitted by Susobhan Akhuli

Output

Minimum element is: 30

C++ Overloading (Function)

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

It is because these members have parameters only.

Types of overloading in C++ are:

 Function overloading

 Operator overloading

C++ Function 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++

// program of function overloading when number of arguments

// vary

#include <iostream>

using namespace std;

class Cal {

public:

    static int add(int a, int b) { return a + b; }

    static int add(int a, int b, int c)

    {

        return a + b + c;

    }

};

int main(void)

{
    Cal C; // class object declaration.

    cout << C.add(10, 20) << endl;

    cout << C.add(12, 20, 23);

    return 0;

//Code Submitted By Susobhan Akhuli

Output

30

55

Example: when the type of the arguments vary.

 C++

// Program of function overloading with different types of

// arguments.

#include <iostream>

using namespace std;

int mul(int, int);

float mul(float, int);

int mul(int a, int b) { return a * b; }

float mul(double x, int y) { return x * y; }

int main()

    int r1 = mul(6, 7);

    float r2 = mul(0.2, 3);


    cout << "r1 is : " << r1 << endl;

    cout << "r2 is : " << r2 << endl;

    return 0;

//Code Submitted By Susobhan Akhuli

Output

r1 is : 42

r2 is : 0.6

Function Overloading and Ambiguity

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.

 Function with default arguments.

 Function with pass by reference.

Type Conversion:-

 C++

#include <iostream>

using namespace std;

void fun(int);

void fun(float);

void fun(int i)

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

}
void fun(float j)

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

int main()

    fun(12);

    fun(1.2);

    return 0;

//Code Submitted By Susobhan Akhuli

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>

using namespace std;

void fun(int);

void fun(int, int);

void fun(int i)

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

void fun(int a, int b = 9)


{

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

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

int main()

    fun(12);

    return 0;

//Code Submitted By Susobhan Akhuli

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>

using namespace std;

void fun(int);

void fun(int&);

int main()

    int a = 10;

    fun(a); // error, which f()?

    return 0;
}

void fun(int x) { cout << "Value of x is : " << x << endl; }

void fun(int& b)

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

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

3. C function argument and return values

4. Inline Functions

5. Return from void functions

6. Returning multiple values from a function


using Tuple and Pair

7. Function Call Puzzle

8. Functors

9. Ciel and floor functions in C++

10. Const member functions

11. atol(), atoll() and atof() functions in C/C++

12. swap() in C++

13. wmemmove() function in c++

14. wcscat() function in C++

15. wcscmp() function in C++ with Examples

16. wcscpy() function in C++ with Examples

17. wcslen() function in C++ with Examples


18. difftime() function in C++

19. asctime() function in C++

20. localtime() function in C++

21. scalbn() function in C++

22. isunordered() function in C++

23. isnormal() in C++

24. isinf() function in C++

25. quick_exit() function in C++ with Examples

26. ctime() Function in C/C++

27. clock() function in C/C++

28. nearbyint() function in C++

29. quick_exit() function in C++ with Examples

30. wcscmp() function in C++ with Examples

31. wcscpy() function in C++ with Examples

32. wcslen() function in C++ with Examples

Pointers and References

1. Pointers in C and C++

2. What is Array Decay in C++? How can


it be prevented?

3. Opaque Pointer

4. References

5. Can references refer to invalid location?

6. Pass arguments by reference or pointer

7. Smart Pointers

8. ‘this’ pointer

9. Type of ‘this’ pointer

10. “delete this”

11. auto_ptr, unique_ptr, shared_ptr and weak_ptr

12. Dangling, Void , Null and Wild Pointers


13. Passing by pointer Vs Passing by Reference

14. NaN in C++ – What is it and how to check for it?

15. nullptr

16. Pointers vs References in C++

Dynamic memory allocation

1. new and delete operator in C++

2. malloc() vs new

3. delete() and free()

4. Std::get_temporary_buffer in C++

Object Oriented Programming(OOP)

1. Object oriented design

2. Introduction to OOP in C++

3. Classes and Objects

4. Access Modifiers

5. Inheritance

6. Polymorphism

7. Encapsulation

8. Data Abstraction

9. Structure vs class

10. Can a C++ class have an object of self type?

11. Why is the size of an empty class not zero?

12. Static data members in C++

13. Some interesting facts about static member functions

14. Friend class and function

15. Local Class

16. Nested Classes

17. Simulating final class

Constructor and Destructor

1. Constructors
2. Copy Constructor

3. Destructors

4. Does compiler create default constructor


when we write our own?

5. When should we write our


own copy constructor?

6. When is copy constructor called?

7. Initialization of data members

8. Use of explicit keyword

9. When do we use Initializer List in?

10. Default Constructors

11. Private Destructor

12. Playing with Destructors

13. Copy elision

14. C++ default constructor | Built-in types

15. When does compiler create a


default constructor and copy constructor?

16. Why copy constructor argument should be


const in C++?

17. Advanced C++ | Virtual Constructor

18. Advanced C++ | Virtual Copy Constructor

19. When are static objects destroyed?

20. Is it possible to call constructor


and destructor explicitly?

Function Overloading

1. Function Overloading

2. Functions that can’t be overloaded

3. Function overloading and const keyword

4. Function overloading and return type

5. Does overloading work with Inheritance?

6. Can main() be overloaded

7. Function Overloading and float


Operator Overloading

1. Operator Overloading

2. Copy constructor vs assignment operator

3. When should we write our


own assignment operator?

4. Operators that cannot be overloaded

5. Conversion Operators

6. Is assignment operator inherited?

7. Default Assignment Operator and References

8. Overloading stream insertion (<<)


and extraction (>>) operators

9. Overloading array index operator []

Virtual Functions

1. Virtual Functions and Runtime Polymorphism

2. Default arguments and virtual function

3. Virtual functions in derived classes

4. Can static functions be virtual?

5. Virtual Destructor

6. Virtual Constructor

7. Virtual Copy Constructor

8. RTTI (Run-time type information)

9. Can virtual functions be private?

10. Inline virtual function

11. Pure Virtual Functions and Abstract Classes

12. Pure virtual destructor

Exception Handling

1. Exception Handling Basics

2. Stack Unwinding

3. Catching base and derived classes as exceptions

4. Catch block and type conversion


5. Exception handling and object destruction

Namespace

1. Namespace in C++ | Set 1 (Introduction)

2. Set 2 (Extending namespace and


Unnamed namespace)

3. Namespace in C++ | Set 3 (Accessing,


creating header, nesting and aliasing)

4. Inline namespaces and usage of the


“using” directive inside namespaces

5. Can namespaces be nested?

Standard Template Library (STL)

Algorithms

1. Introduction to STL

2. Sorting

3. Searching

Containers:

1. Pair (Practice)

2. Vector (Practice)

 Ways to copy a vector in C++

 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)

 2D vector in C++ with user defined size

 Vector::clear() and vector::erase() in C++ STL

 Passing vector to a function in C++

 Vector::push_back() and vector::pop_back() in C++ STL

 Vector::empty() and vector::size() in C++ STL

 vector::front() and vector::back() in C++ STL

 Initialize a vector; Different ways

 Sorting 2D Vector in C++ | Set 1 (By row and column) , (Sort by first and second)

 Computing index using pointers returned by STL functions in C++


3. List

 List in C++ | Set 2 (Some Useful Functions)

 Forward List in C++ | Set 1 (Introduction and Important Functions)

 Forward List in C++ | Set 2 (Manipulating Functions)

 list::remove() and list::remove_if() in C++ STL

 Forward_list::front() and forward_list::empty() in C++ STL

 Forward_list::remove() and forward_list::remove_if() in C++ STL

 forward_list::unique() in C++ STL

 forward_list::reverse() in C++ STL

 forward_list::max_size() in C++ STL

 forward_list::before_begin() in C++ STL

 forward_list::cbefore_begin() in C++ STL

 forward_list::unique() in C++ STL

 forward_list::before_begin() in C++ STL

 forward_list::cbefore_begin() in C++ STL

 forward_list::reverse() in C++ STL

 forward_list::max_size() in C++ STL

 forward_list::splice_after() in C++ STL

 list::empty() and list::size() in C++ STL

 list::front() and list::back() in C++ STL

 list::pop_front() and list::pop_back() in C++ STL

 list::push_front() and list::push_back() in C++ STL

 list push_front() function in C++ STL

 list pop_back() function in C++ STL

 list pop_front() function in C++ STL

 list reverse function in C++ STL

 list resize() function in C++ STL

 list size() function in C++ STL

 list max_size() function in C++ STL


4. Dequeue

5. Deque::empty() and deque::size() in C++ STL

6. Deque::pop_front() and deque::pop_back() in C++ STL

7. Deque::clear() and deque::erase() in C++ STL

8. Queue (Practice)

9. Queue::front() and queue::back() in C++ STL

10. Queue::push() and queue::pop() in C++ STL

11. queue::empty() and queue::size() in C++ STL

12. Priority Queue

13. Stack (Practice)

14. Stack::push() and stack::pop() in C++ STL

15. Forward_list :: push_front() and forward_list :: pop_front() in C++ STL

16. Stack::top() in C++ STL

17. Stack::empty() and stack::size() in C++ STL

18. Set (Practice)

 Count number of unique Triangles using STL | Set 1 (Using set)

 std::istream_iterator and std::ostream_iterator in C++ STL

19. Std::next_permutation and prev_permutation in C++

20. Std::stoul and std::stoull in C++

21. Shuffle vs random_shuffle in C++

22. Difference between set, multiset, unordered_set, unordered_multiset

23. Check if a key is present in a C++ map or unordered_map

24. Std::stable_partition in C++

25. Valarray slice selector

26. Std::memchr in C++

27. Std::strncmp() in C++

28. Stable_sort() in C++ STL

29. Std::memcmp() in C++


30. Std::memset in C++

31. Std::bucket_count and std::bucket_size in unordered_map in C++

32. Map of pairs in STL

33. Range-based for loop in C++

34. Std::includes() in C++ STL

35. Std::set_symmetric_difference in C++

36. Std::sort_heap in C++

37. Map vs unordered_map in C++

38. Round() in C++

39. Modulus of two float or double numbers

40. Multiset

41. Map (Practice)

42. Heap using STL C++

Multimap

 Multimap in C++ Standard Template Library (STL)

 multimap::find() in C++ STL

 multimap::erase() in C++ STL

 map emplace() in C++ STL

 multimap::emplace_hint() in C++ STL

 multimap::emplace() in C++ STL

 multimap::count() in C++ STL

 multimap::find() in C++ STL

 multimap::erase() in C++ STL

 multimap::begin() and multimap::end() in C++ STL

 multimap::cbegin() and multimap::cend() in C++ STL

 map cbegin() and cend() function in C++ STL

 multimap::crbegin() and multimap::crend() in C++ STL

 multimap size() function in C++ STL


 multimap lower_bound() function in C++ STL

 multimap swap() function in C++ STL

 multimap upper_bound() function in C++ STL

 multimap maxsize() in C++ STL

 multimap insert() in C++ STL

 multimap equal_range() in C++ STL

CPP-Math

 sinh() function in C++ STL

 cosh() function in C++ STL

 tanh() function in C++ STL

 acos() function in C++ STL

 asinh() function in C++ STL

 acosh() function in C++ STL

 atanh() function in C++ STL

More:

1. sort() in C++ STL

2. Strand sort

3. Type Inference in C++ (auto and decltype)

4. transform() in C++ STL

5. Variadic function templates in C++

6. Template Specialization

7. Implementing iterator pattern of a singly linked list

8. Binary Search functions in C++ STL

9. Descending order in Map and Multimap of C++ STL

10. Insertion and Deletion in STL Set C++

11. set::key_comp() in C++ STL

12. set value_comp() function in C++ STL

13. unordered_set get_allocator() in C++ STL with Examples

Inheritance
 What all is inherited from parent class in C++?

 Virtual Functions and Runtime Polymorphism in C++

 Multiple Inheritance in C++

 What happens when more restrictive access is given to a derived class method in C++?

 Object Slicing in C++

 Hiding of all overloaded methods in base class

 Inheritance and friendship

 Simulating final class

C++ Library

1. <random> file – generators and distributions

2. Array type manipulation

3. C++ programming and STL facts

4. Sqrt, sqrtl and sqrtf in C++

5. std::stod, std::stof, std::stold in C++

6. C program to demonstrate fork() and pipe()

7. Complex numbers in C++ | Set 1 Set 2

8. Inbuilt library functions for user Input

9. Rename function in C/C++

10. Chrono

11. valarray class

12. Floating Point Manipulation (fmod(), remainder(), remquo() … in cmath) (Practice)

13. Character Classification: cctype

14. Snprintf() in C library

15. Boost::split in C++ library

16. Modulus of two float or double numbers

17. Is_trivial function in C++

18. Array sum in C++ STL

19. Div() function in C++


20. Exit() vs _Exit() in C and C++

21. Std::none_of in C++

22. Isprint() in C++

23. Iscntrl() in C++ and its application to find control characters

24. Std::partition_point in C++

25. Iterator Invalidation in C++

26. Fesetround() and fegetround() in C++ and their application

27. Rint(), rintf(), rintl() in C++

28. Hypot(), hypotf(), hypotl() in C++

29. Std::gslice | Valarray generalized slice selector

30. std::setbase, std::setw , std::setfill in C++

31. Strxfrm() in C/C++

32. Set position with seekg() in C++ language file handling

33. Strstr() in C/C++

34. Difftime() C library function

35. Socket Programming

36. Precision of floating point numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())

37. <bit/stdc++.h> header file

38. std::string class in C++

39. Merge operations using STL in C++ (merge, includes, set_union, set_intersection,
set_difference, ..)

40. std::partition in C++ STL

41. Ratio Manipulations in C++ | Set 1 (Arithmetic)  , Set 2 (Comparison)

42. numeric header in C++ STL | Set 1 (accumulate() and partial_sum()) , Set 2 (adjacent_difference(),
inner_product() and iota())

43. Bind function and placeholders

44. Array class

45. Tuples

46. Regex (Regular Expression)


47. Common Subtleties in Vector STLs

48. Understanding constexpr specifier

49. unordered_multiset and its uses

50. unordered_multimap and its application

51. Populating a vector in C++ using fill() and fill_n()

52. Writing OS Independent Code in C/C++

53. C Program to display hostname and IP address

54. Database Connectivity using C/C++

55. C++ bitset and its application

56. unordered_map in STL and its applications

57. unorderd_set in STL and its applications

58. nextafter() and nexttoward()

C++ Advanced

1. User Defined Literal

2. Placement new operator

3. Advanced C++ with boost library

4. Copy-and-Swap Idiom

5. Zombie and Orphan Processes

6. Lambda expression

7. C++ | Signal Handling

8. Preventing Object Copy in C++

9. Command line arguments in C++

C++ in Competitive Programming

1. Writing C/C++ code efficiently in Competitive programming

2. Useful Array algorithms in C++ STL

3. searching in fork()

4. Data Type Ranges and their macros

5. Cin-Cout vs Scanf-Printf

6. getchar_unlocked() – faster input in C/C++ for Competitive Programming


7. C qsort() vs C++ sort()

8. Middle of three using minimum comparisons

9. Check for integer overflow on multiplication

10. Generating Test Cases (generate() and generate_n()

Puzzles

1. Can we call an undeclared function in?

2. Can we access global variable if there


is a local variable with same name?

3. Can we use function on left side


of an expression in C and C++?

4. Can we access private data members


of a class without using a member
or a friend function?

5. How to make a C++ class whose objects


can only be dynamically allocated?

6. How to print “GeeksforGeeks” with empty main()

7. Print 1 to 100, without loop and recursion

8. C/C++ Tricky Programs

9. Print a number 100 times without using loop, recursion and macro expansion in C++

10. How to restrict dynamic allocation of objects

11. Sum of digits of a number in single statement

12. Write a URL in a C++ program

13. Zoom digits of an integer

14. Composite Design Pattern in C++

15. Assign value without any control statement

16. Printing pyramid pattern

17. How to swap two variables in one line in C/C++, Python and Java?

18. Program to shut down a computer

Interview Questions

1. Commonly Asked C++ Interview Questions | Set 1

2. Commonly Asked OOP Interview Questions | Set 1


3. C/C++ Programs

Quick Links:

 Recent Articles on C++

 Practice Track on C++

 C++ Output & Multiple Choice Questions

You might also like