Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views136 pages

C++ Notes

Uploaded by

ss1999das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views136 pages

C++ Notes

Uploaded by

ss1999das
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 136

Why Do We Need Programming Languages

The Role of the Central Processing Unit (CPU)

The CPU is the brain of the computer. It performs calculations and runs tasks. For
example, it can quickly generate multiplication tables for the first thousand numbers,
a task that would take humans much longer.

Writing Programs for the CPU

The CPU understands instructions in a format called binary, which is a sequence of 0s


and 1s. Writing programs directly in binary is very difficult for humans because
remembering and writing long sequences of 0s and 1s is impractical. This is where
high-level programming languages come into play.

Programming Languages

Languages like C, C++, Java, and Python make it easier for humans to give
instructions to the CPU. These languages have specific rules (syntax) that must be
followed precisely. A small mistake can cause the program to fail.

Depending on the language you choose, we say that your code is


either compiled or interpreted into machine code capable of being executed by
your CPU. Most programming languages include a program called a compiler or
an interpreter which performs this translation step.

COMPILER VS INTERPRETER

COMPILER INTERPRETER

A compiler translates the entire An interpreter translates the entire source


source code in a single run. code line by line.

It consumes less time i.e., it is It consumes much more time than the
faster than an interpreter. compiler i.e., it is slower than the compiler.

C++ Introduction
C++ is a programming language that was first released in 1985, making it older than
languages like Java and Python.
Why C++ is Still Relevant

Even though Java and Python are more commonly used in the industry today, C++ is
still important for certain applications. It is especially popular in competitive
programming and is also used for software development. The main reasons for this
are its ability to handle low-level programming and its speed of execution, meaning it
requires fewer resources to run tasks quickly.

C++ as an Extension of C

C++ was created as an extension of the C programming language, which is one of the
oldest high-level languages. C is known for allowing direct hardware access, which
is possible through pointers. Since C++ is based on C, it inherits these features,
allowing programmers to directly manipulate memory and hardware.

Features of C++

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

 Simple
 Machine Independent but Platform Dependent
 Mid-level language
 Rich library support
 Speed of execution
 Pointer and direct Memory-Access
 Object-Oriented
 Compiled Language
Other important features include:

1. Generic Programming: C++ allows you to write code that works for multiple
types using templates, which makes your code more reusable.
2. Exception Handling: Unlike C, C++ includes exception handling to manage
errors more effectively.
3. Standard Template Library (STL): C++ has a richer library than C, including
the STL, which provides commonly used data structures and algorithms like
lists, maps, and stacks.

Real-World Applications of C++

C++ finds varied usage in applications such as:

 Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)


 Browsers (Chrome & Firefox)
 Graphics & Game engines (Photoshop, Blender, Unreal-Engine)
 Database Engines (MySQL, MongoDB, Redis etc.)
 Cloud/Distributed Systems

C++ Standards and Implementation


Just like spoken languages such as English and Hindi have grammatical rules,
programming languages like C++ also follow rules known as standards. These
standards define what is correct or incorrect in the language, ensuring consistency
and quality.

C++ Standards Timeline

C++ was first standardized in 1998. Before this, it was released in 1985 but didn't
have a formal standard. The first official version of C++ was C++98. Since then,
C++ has gone through several updates to improve the language. The major versions
include:

 C++03
 C++11
 C++14
 C++17
 C++20
 The next version, C++23, is currently in development.

What Are the Rules in C++ Standards?

Each programming language has its own rules to define what is allowed and what
isn’t. For example:

 Variable names cannot have special characters.


 The multiplication operator (*) is used for multiplication.
 Operators like * and + follow a specific order of precedence in expressions.
These rules are clearly stated in the C++ standards documentation. As a
programmer, it's important to follow these rules to write correct programs.

Implementing the Rules: C++ Compilers

To ensure that the rules are followed, compilers are used. Compilers are software
tools that convert your C++ code into executable machine code. Some popular C++
compilers include:

 GCC (GNU Compiler Collection) – commonly used and supports a wide range
of C++ standards.
 MSVC (Microsoft Visual C++) – developed by Microsoft.
 IBM, Oracle, and Intel also offer C++ compilers.
These compilers implement the rules specified in the C++ standards. They also
provide their own extra functionalities or libraries. For example, GCC includes built-in
functions for tasks like computing the GCD or counting set bits. These extra
features are not part of the official C++ standard, but they are useful for specific
tasks.

Undefined Behaviour in C++


In C++, there are some expressions that are syntactically correct but do not
have defined behaviour according to the standard. This means that different
compilers may handle these expressions differently, leading to unexpected results. As
a programmer, it is important to avoid writing code that leads to undefined behaviour
to prevent inconsistencies in output.

How does a C++ program run


When developing software using C++, you first write your code in a text editor. C++
is a high-level language, which means that the CPU cannot directly understand the
code you write. Therefore, it needs to be converted into something that the CPU can
process. This conversion process involves a few steps, and often, you also use
libraries—pre-written code by other developers to perform tasks like displaying output
or getting user input.

Writing and Compiling Code

1. Writing Code: C++ programs are usually written in a text editor. When you
write your program, you save it as a .cpp file. You might also use libraries
(external functions) to help with common tasks in your program.
2. Compilation: Since your CPU can’t directly execute C++ code, you need to
compile it. This step generates an executable file:
o On Windows, this file will have a .exe extension.
o On Linux, it will be an executable file named a.out by default.
3. Running the Program: After the code is compiled, you can run the generated
executable file. The CPU can now understand the instructions, and your program
will run on your machine.

Using Integrated Development Environments (IDEs)

A better way to write and run C++ programs is by using an Integrated


Development Environment (IDE). Popular IDEs include:

 Code::Blocks
 DevC++
 Microsoft Visual Studio
 Xcode (for macOS)
 Sublime Text (with extensions)
IDEs make programming much easier by providing a user-friendly editor with features
like syntax highlighting, which colors different parts of your code to make it easier
to read. With a single click, you can compile and run your code. These IDEs handle
all the background work of compiling and running the code.

Even though IDEs simplify the process, they are still performing the same actions you
would manually do using the command line. Here's what happens behind the scenes:

1. Writing Source Code: In the IDE, you write your C++ code, and the editor will
highlight the syntax (keywords, variables, etc.) to make it easier to spot errors.
2. Compiling:
When you click the compile button, the IDE invokes a compiler, which turns
your C++ source code into object code. This object code is a machine-
readable version of your program, but it is still not ready to be executed.
3. Linking:
If your program uses libraries or external functions, the IDE will also invoke
a linker. The linker combines your object code with the object code from
libraries or other external sources to create the final executable.
4. Running:
Once the executable file is created, you can run your program directly from the
IDE. The CPU can now understand and execute the program.

Key Steps in the Compilation Process

 Preprocessing: This step handles tasks like including libraries and defining
constants.
 Syntax Checking: The compiler checks the code for any errors in syntax.
 Linking: The linker combines your program’s object code with external libraries
and functions to form a complete executable.

C++ vs. Java and Python

C++ operates differently from languages like Java and Python. For Java and Python,
the source code is typically first converted into bytecode—a machine-independent
code. A virtual machine then runs the bytecode on different platforms, which is why
Java and Python are called platform-independent.

On the other hand, C++ code is compiled directly into machine-specific object code.
The compiled executable is designed for a specific platform, meaning the compiler
must be tailored for the operating system or hardware you are using (e.g., Windows or
Linux). This makes C++ platform-dependent.

Basic Programming Terminology


1. Keywords:

Keywords are reserved words in a programming language that have predefined


meanings and cannot be used as variable or function names. For example:

 for: Used to create loops that repeat actions.


 while: Used to execute a block of code repeatedly.
 true and false: Boolean values that represent truth and falsity.

2. Variables:

Variables are named storage locations in a program that can hold a value of a
particular data type. In C++, variables must be declared with a specific data type
before they can be used. Common data types in C++ include "int" for integers, "float"
for decimal numbers, and "char" for characters.

3. Functions:
A function is a block of code that performs a specific task. For example, max(a, b) is a
function that takes two inputs and returns the larger value. Functions like printf() in
C/C++ take inputs (like a string) and output them to the screen. You can define your
own functions for repeated tasks in your code.

4. Object-Oriented Programming (OOP):

There are two main programming paradigms:

 Functional Programming: Everything is done via functions calling other


functions.
 Object-Oriented Programming (OOP): Instead of functions calling each
other, you create objects that interact with each other.
OOP is ideal for larger software projects as it organizes code into classes and objects.
In OOP:

 A class is a blueprint that defines the properties and behaviours of objects. For
example, a Student class might have properties like name and enrolment
number, and behaviours like enroll() or graduate().
 An object is an instance of a class. For example, student1 can be an object
created from the Student class.
C++ supports both functional programming (with functions interacting)
and object-oriented programming (with objects interacting).

5. Primitive and Non-Primitive Types

C++ and Java support both:

 Primitive types: Variables like int, float, and char that store basic data values.
 Non-Primitive types: Objects that are instances of classes.
In Python, everything is an object, so there are no primitive types like in C++ or Java.

6. Statically Typed vs Dynamically Typed:

 Statically Typed Languages (C++ and Java): Variables must be declared with
a specific type before use. For example, you must specify int x = 5; before
using x.
 Dynamically Typed Languages (Python): Variables don't need an explicit
type declaration. You can assign a value to a variable without specifying its
type, like x = 5, and later change x to store a string.

7. Header Files:

In C++, header files are files that contain declarations for functions, variables, and
other constructs. These files are included in C++ programs using the preprocessor
directive #include. Header files allow the program to use functions and variables
without having to know the implementation details. For example, #include
<iostream> allows the use of input/output operations like cout and cin.
8. Namespace:

A namespace is a container for organizing code into logical groups. For


example, std is a namespace that contains standard libraries and functions in C++.
The advantage of namespaces is that they prevent name collisions. If two different
libraries or parts of your code define a variable with the same name, namespaces
allow them to coexist by distinguishing them. For example, std::cout refers to
the cout function in the std namespace.

First C++ Program


#include<iostream>
using namespace std ;
int main()
{
cout << "GeeksForGeeks" ;
return 0 ;
}

Output:
GeeksforGeeks

Let us now understand every line and the terminologies of the above program:

1. #include <iostream>

 What it does: This is a preprocessor directive. Lines beginning with # are


processed by the preprocessor, which is the first step in the compilation
process. The preprocessor replaces these lines with relevant code before the
compiler starts compiling.
 Why iostream:
The iostream header file is included because it contains the declaration of
the cout object, which is used to print output to the screen.
o iostream stands for Input-Output Stream.
o Without including this file, you cannot use input/output functions
like cout or cin.

2. using namespace std;

 What it does: This line imports the entire std namespace into the program's
current scope.
o The std namespace contains all the standard C++ library functions and
objects like cout and cin.
o By including this line, you can directly write cout instead of std::cout.
 Better Practice: It’s considered better practice to avoid using namespace
std; in larger programs to prevent conflicts between multiple namespaces.
Instead, use std::cout explicitly.
3. int main()

 What it does: The main() function is where every C++ program begins
execution.
o The int before main() indicates that the function will return an integer
value.
o The return value signals the program's exit status:
 return 0; means the program finished successfully.
 Curly Braces {}:
o The { indicates the start of the function body, and } marks the end.
Everything between these braces is part of the function.

4. std::cout << "GeeksforGeeks";

 What it does: This statement outputs the string "GeeksforGeeks" to the screen.
o std::cout: Stands for "character output" and represents the standard
output stream (usually the screen).
o << operator: This is the stream insertion operator used to send data to
the output stream.
o String inside quotes: Anything enclosed in double quotes will be printed
as is.
 Semicolon ;:
o The semicolon indicates the end of the statement. Missing a semicolon
results in a syntax error.

5. return 0;

 What it does: This statement ends the program and returns the value 0 to
indicate successful completion.
o Functions in C++ generally return a value, and since main() is of type int,
it should return an integer value

6. Indentation and Readability


 What it does: Indentation is not mandatory in C++ but is highly
recommended.
o It helps organize the code and makes it more readable.
o Typically, 4 spaces or a tab is used for indentation.

Key Points to Remember:

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

1. Always include the necessary header files for the smooth execution of functions.
2. Avoid using using namespace std; in large programs. Instead, use std:: before
standard library objects and functions.
3. The execution of code begins from the main() function.
4. It is a good practice to use Indentation and comments in programs for easy
understanding.
5. A semicolon marks the end of a statement. Omitting it will cause syntax errors.
6. Curly braces define the boundaries of code blocks, such as functions, loops, or
conditionals.

Comments in C++

A well-documented program is a good practice as a programmer. It makes a program


more readable and error finding become easier. One important part of good
documentation is Comments.

 In computer programming, a comment is a programmer-readable explanation or


annotation in the source code of a computer program
 Comments are statements that are not executed by the compiler and
interpreter.
In C/C++ there are two types of comments :

1. Single line comment


2. Multi-line comment

Single line Comment

Represented as // double forward slash It is used to denote a single line comment. It


applies comment to a single line only. It is referred to as C++-style comments as it is
originally part of C++ programming. for example:

// single line comment

Example:

// C++ program to illustrate


// use of single-line comment
#include <iostream>
int main()
{

// Single line Welcome user comment


std::cout << "Welcome to GeeksforGeeks";
return 0;
}

Output
Welcome to GeeksforGeeks

Multi-line comment

Represented as /* any_text */ start with forward slash and asterisk (/*) and end with
asterisk and forward slash (*/). It is used to denote multi-line comment.

/*Comment starts
continues
continues
.
.
Comment ends*/

Example:

/* This is
a multi-line
comment */
#include <iostream>
int main()
{
/* Multi-line Welcome user comment
written to demonstrate comments
in C/C++ */
std::cout << "Welcome to GeeksforGeeks";
return 0;
}

Output
Welcome to GeeksforGeeks

Comment at End of Code Line

You can also create a comment that displays at the end of a line of code. But
generally its a better practice to put the comment before the line of code.

Example:

int age; // age of the person

When and Why to use Comments in programming?

 Comments Enhance Readability: Comments make the code easier to


understand for someone reading it, especially in large or complex programs.
 Explain Algorithms: Comments can provide detailed explanations of
algorithms or logic used in the code.
 Helpful for Future Reference: Comments are useful for the original
developer when revisiting the code after a long time.
 Improves Collaboration: In collaborative projects, comments help team
members understand each other's code more easily.

Variables in C++
Variables in C++ 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

 The name of the variable contains letters, digits, and underscores.


 The name of the variable is case sensitive (ex Arr and arr both are different
variables).
 The name of the variable does not contain any whitespace and special
characters (ex #,$,%,*, etc).
 All the variable names must begin with a letter of the alphabet or an
underscore(_).
 In C++, reserved keywords like float, double, and class cannot be used as
variable names.

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.

datatype: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

Example:

#include<iostream>
using namespace std ;
int main()
{
int x = 5 ;
cout << x << " " ;
x = 8 ; // we can update the value also
cout << x << " " ;
int y = 10 ;
cout << y ;
return 0 ;
}

Key Points

1. Declaration: int x = 5; creates an integer variable x with an initial value of 5.


2. Update: x = 8; changes the value of x to 8.
3. New Variable: int y = 10; declares a second variable y with value 10.
4. Output: The program prints 5 8 10.
other variable declaration Examples:

// Declaring float variable float simpleInterest;


// Declaring integer variable int time, speed;
// Declaring character variable char var;
Variable Naming Rules
Variable names in C++ are identifiers used to store data, and there are specific rules
and conventions that must be followed to ensure the compiler correctly interprets the
code. Let’s explore these rules, along with examples of valid and invalid variable
names.

Rules for Naming Variables

1. Allowed Characters:
o Lowercase Letters: a to z
Example: age, name
o Uppercase Letters: A to Z
Example: UserName, PlayerScore
o Digits: 0 to 9
Example: x23, value1
o Underscore (_):
Example: _temp, max_value

2. Cannot Start with a Digit:


o Variable names must start with a letter or an underscore.
o Valid: x1, _count
o Invalid: 1a, 2value
3. Cannot Contain Special Characters:
o Only underscore (_) is allowed; other characters like @, #, $, etc., are
invalid.
o Invalid: a#b, total$amount
4. Cannot Be a Reserved Keyword:
o Reserved keywords like int, else, for, etc., cannot be used as variable
names.
o Invalid: else, for

Conventions for Naming Variables

To make code more readable and maintainable, follow these naming conventions:

1. Camel Case:
o Start with a lowercase letter, and capitalize subsequent words.
o Example: currentYear, playerName, maxValue
2. Snake Case:
o Use underscores to separate words.
o Example: current_year, player_name, max_value
3. For Constants:
o Use all uppercase letters with underscores between words.
o Example: MAX_AGE, PI, LIMIT
o (_):
Example: _temp, max_value
2. Cannot Start with a Digit:
o Variable names must start with a letter or an underscore.
o Valid: x1, _count
o Invalid: 1a, 2value
3. Cannot Contain Special Characters:
o Only underscore (_) is allowed; other characters like @, #, $, etc., are
invalid.
o Invalid: a#b, total$amount
4. Cannot Be a Reserved Keyword:
o Reserved keywords like int, else, for, etc., cannot be used as variable
names.
o Invalid: else, for

Conventions for Naming Variables

To make code more readable and maintainable, follow these naming conventions:

1. Camel Case:
o Start with a lowercase letter, and capitalize subsequent words.
o Example: currentYear, playerName, maxValue
2. Snake Case:
o Use underscores to separate words.
o Example: current_year, player_name, max_value
3. For Constants:
o Use all uppercase letters with underscores between words.
o Example: MAX_AGE, PI, LIMIT

Data Types in C++


In C++, data types define the type of data a variable can hold. Data types are
essential for specifying the type of value stored in variables and ensuring proper
memory allocation. They are broadly classified into Primitive (or Fundamental) Types
and Non-Primitive Types.

1. Primitive (Fundamental) Types

Primitive data types are predefined by the C++ language and include the following
categories:

a. Integer Types

Used to store whole numbers (both positive and negative).

 Examples: short, int, long, long long


 Unsigned Variants: unsigned short, unsigned int, unsigned long, unsigned long
long (used for positive values only).

b. Character Types

Used to store single characters.

 Examples: char, unsigned char


 Specialized Types: wchar_t (wide character), char16_t, char32_t (for Unicode).

c. Floating-Point Types
Used to store decimal or fractional numbers.

 Examples: float, double, long double

d. Other Types
 Boolean (bool): Used to store true or false.
 Void (void): Represents the absence of a value, primarily used for functions
that do not return any value.

2. Non-Primitive Types

Non-primitive types are derived from primitive types or created by the programmer.
Examples:

 Array: A collection of elements of the same type.


 Pointers: Variables that store the address of another variable.
 User-Defined Types: Created by the programmer using classes, structs, or
enums.

Example Program

The following program demonstrates the use of various data types in C++:

#include<iostream>
#include<string>
using namespace std ;
int main()
{
int age = 39 ;
string name = "Sandeep" ;
char gender = 'M' ;
bool isMarried = true ;
float weight = 68.5 ;
cout << name << "\n"
<< age << "\n"
<< gender << "\n"
<< isMarried << "\n"
<< weight ;
return 0 ;
}

Output of the Program

Sandeep
39
M
1
68.5

1: Represents true for the boolean value.

Explanation of Code
1. Integer (int):
int age = 39;
Stores the age as an integer.
2. String (string):
string name = "Sandeep";
A non-primitive type used to store a sequence of characters.
3. Character (char):
char gender = 'M';
Stores a single character ('M' for Male).
4. Boolean (bool):
bool isMarried = true;
Stores a logical value (true or false).
5. Floating-Point (float):
float weight = 68.5;
Stores the weight as a decimal number.

Operator sizeof in C++


The sizeof operator is a unary compile-time operator used to determine the size of
variables, data types, and constants in bytes at compile time. It can also determine
the size of classes, structures, and unions.

Key Features of sizeof() Operator

1. Compile-Time Evaluation:
o The sizeof() operator is evaluated during the compilation of the program.
This means that its results are known before the program runs.
2. Determines Size in Bytes:
o It returns the number of bytes required to store a particular data type or
object in memory.
3. Flexible Usage:
o It can be used with basic data types, user-defined types, variables, and
even expressions.
Syntax:

sizeof (data type) or

sizeof (expression)
Here:

 type refers to a built-in or user-defined data type.


 expression evaluates to an object or a data type.

Example 1: Number of bytes taken by different data types.

Below is the C++ program to implement sizeof operator to determine the number of
bytes taken by different data types:

#include <iostream>
using namespace std;

int main() {
cout << "Size of int: " << sizeof(int) << " bytes\n";
cout << "Size of char: " << sizeof(char) << " bytes\n";
cout << "Size of long long: " << sizeof(long long) << " bytes\n";
cout << "Size of float: " << sizeof(float) << " bytes\n";

return 0;
}

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

Example 2: Number of bytes taken by variables of different data


types.

Below is the C++ program to implement sizeof to determine the number of bytes
taken by variables of different data types:

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

int main()
{
int x;
double d = 10.2;
cout << sizeof(x) << "\n";
cout << sizeof(d) << "\n";
cout << sizeof(10ll) << "\n";
cout << sizeof(3.4) << "\n";
cout << sizeof(3.4f) << "\n" ;
return 0;
}

Output:

4
8
8
8
4

Global Variables and Scope


In programming , 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
2. Global Variables
Local Variables - Variables defined within a function or block are said to be local to
those functions.

Anything between ‘{‘ and ‘}’ is said to be 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

int main()
{
int x = 10;
cout<<x;

return 0;
}
//Local variable

Output:
10

Global Variables - Global Variables can be accessed from any part of the program.

They are available throughout the lifetime of a program.


They are declared at the top of the program outside all of the functions or
blocks.
Declaring global variables: Global variables are usually declared outside of all of
the functions and blocks, at the top of the program. They can be accessed from any
portion of the program.

#include<iostream>
using namespace std;

int x = 10;
int main()
{
cout<<x;

return 0;
}
//global variable

Output:
10
In the program, the variable “global” is declared at the top of the program outside all
of the functions so it is a global variable and can be accessed or updated from
anywhere in the program.

NOTE - Whenever there is a local variable defined with same name as that of
a global variable then the compiler will give precedence to the local
variable.

Referencing Variables Outside Their Scope:

When a variable is referenced outside its scope:

 A local variable cannot be accessed outside the function/block where it is


declared, resulting in a compiler error.
 A global variable can be accessed anywhere in the program unless explicitly
hidden by a local variable.

Using the extern Keyword

If a global variable is defined after it is used in the program, the compiler throws an
error. To solve this, we use the extern keyword, which tells the compiler that the
variable is defined elsewhere in the program.

Example 1: Without extern (Compiler Error)


#include <iostream>
using namespace std;

int main()
{
cout << x; // Error: x is not declared yet
return 0;
}

int x = 10;

Example 2: Using extern (Correct)


#include <iostream>
using namespace std;

extern int x;
int main()
{
cout << x;
return 0;
}
int x = 10;

Output:
10

Local and Global Variables with the Same Name


When a local and global variable share the same name:

 The local variable takes precedence within the block where it is declared.
 The global variable is overshadowed but still exists and can be accessed using
the scope resolution operator (::).

Example 1: Local Variable Overshadows Global Variable


#include <iostream>
using namespace std;
int x = 20; // Global variable
int main()
{
int x = 10; // Local variable
cout << x;
return 0;
}
Output:

10

Example 2: Nested Local Variables


#include <iostream>
using namespace std;

int x = 20;
int main()
{
int x = 10;
{
int x = 30;
cout << x;
}
return 0;
}
Output:

30

Example 3: Redefining a Variable in the Same Scope (Error)


#include <iostream>
using namespace std;
int x = 20;
int main()
{
int x = 10;
int x = 20; // Error: Redefinition of x in the same scope
cout << x;
return 0;
}

Scope Rules in C++

1. Functions, Loops, and Conditional Statements Create a New Scope:


Each function, loop, or conditional block introduces a new scope.
o
Variables declared inside the block are local to that scope.
o
2. Outer Scope Variables Are Accessible in Inner Scopes:
o Variables from an outer scope can be used inside inner scopes unless
overshadowed.
o However, inner scope variables are not accessible outside their block.
3. Creating a New Scope with Curly Braces:
o Curly braces {} can be used to create a new block scope anywhere in the
program.

Ranges of Data Types in C++


Data type modifiers available in C++ are:

 Signed
 Unsigned
 Short
 Long
The below table summarizes the modified size and range of built-in datatypes which
also depends upon the compiler( i.e 32bits or 64bits ) when combined with the type
modifiers:

Size (in
Data Type Range
bytes)

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

-32,768 to 32,767 or -2,147,483,648 to


int 2 or 4
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


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

signed char 1 -128 to 127

unsigned char 1 0 to 255


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

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

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

wchar_t 2 or 4 1 wide character

Static Variables in C++


A static variable is a variable that is allocated memory only once during the
lifetime of a program. Its value is retained across multiple function calls and persists
until the program terminates.

Key Characteristics of Static Variables

1. Lifetime:
o Static variables exist for the entire lifetime of the program.
2. Scope:
o A static variable declared inside a function has local scope but retains its
value across multiple calls to the function.
o A static global variable has file scope (internal linkage) and is not
accessible outside the file in which it is defined.
3. Initialization:
o Static variables are initialized only once, and if not explicitly initialized,
they are automatically initialized to zero.
4. Memory Allocation:
o Memory for static variables is allocated in the data segment, not the
stack.
// C++ program to demonstrate
// the use of static Static
// variables in a Function
#include <iostream>
using namespace std;
int main()
{
static int x;
cout<<x<<endl;
return 0;
}

Output:
0

Const in C++
In C++, the const keyword is used to define constants — variables whose values
cannot be modified once they are initialized. This is an essential feature when working
with values that should remain constant throughout the execution of a program,
ensuring immutability and preventing accidental changes.

What is a const Variable?

A const variable is a variable whose value cannot be changed after initialization. It


must be initialized at the time of declaration, and any attempt to modify it will result
in a compiler error.

Example:
#include <iostream>
using namespace std;

int main() {
const int x = 10;
x = x + 1; // Compiler error: Cannot modify a const variable
cout << x;
return 0;
}
If we remove the modification line (x = x + 1), the program will compile successfully
and output 10.

Real-World Example of const

Constants are particularly useful in real-world applications where certain values must
remain unchanged. For example:

#include <iostream>
using namespace std;

const double PI = 3.14;

int main() {
int r;
cout << "Enter the radius of the circle: ";
cin >> r;
cout << "Area of the circle is: " << PI * r * r;
return 0;
}

Alternative to const: Using #define

Before the introduction of const, the #define preprocessor directive was commonly
used to define constants.

#define var 5

Since Macros are handled by the preprocessor(the pre-processor does text


replacement in our source file, replacing all occurrences of ‘var’ with the literal 5), not
by the compiler.

Hence it wouldn’t be recommended because Macros don’t carry type-checking


information and are also prone to error.
Constants vs. Macros (#define)

Feature const #define

Type Provides type


No type checking
Safety safety

Obeys scoping Global scope, no


Scope
rules scoping

Debuggin
Easier to debug Harder to trace
g

Best Practices

There are a certain set of rules for the declaration and initialization of the constant
variables -:

 The const variable cannot be left un-initialized at the time of the assignment.
 It cannot be assigned value anywhere in the program.
 Explicit value needed to be provided to the constant variable at the time of
declaration of the constant variable.
Ex- const int num = 1;

Auto Keyword in C++


The auto keyword in C++ is a modern and powerful feature introduced in C++11 that
simplifies variable declarations. By using auto, the compiler automatically deduces
the type of a variable based on the type of the initializer. This feature not only
enhances code readability but also reduces the chance of type mismatch errors.

Note: The variable declared with auto keyword should be initialized at the time of its
declaration only or else there will be a compile-time error.

How auto Works

The auto keyword allows the compiler to infer the type of a variable at compile time
based on its initializer. The programmer doesn't need to explicitly specify the type,
making the code cleaner and easier to write.

Example: Using auto

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

int main() {
auto a = 5; // Type of 'a' is deduced as int
auto b = 10.5; // Type of 'b' is deduced as double

cout << a << " " << b << "\n";


cout << typeid(a).name() << " " << typeid(b).name();
return 0;
}

Output:
5 10.5
id

Explanation:

 The auto keyword automatically deduces the type


of a as int and b as double based on the values assigned.
 The typeid It is an operator which is used where the dynamic type of an object
needs to be known.
 typeid(x).name() returns the data type of x, for example, it return ‘i’ for
integers, ‘d’ for doubles, ‘Pi’ for the pointer to integer etc. But the actual name
returned is mostly compiler dependent.

Advantages

1. No Conversion happens when auto is used

float x = 3.4 //double literal converted to float.

auto y = 3.4 //type of y is double.

2. If a function returns auto, its return type can be changed without worrying about
prototype change.

3. Can be very helpful for lengthy types, especially STL iterators

vector<int>::iterator i; can be replaced with auto i;

4. It can be used in Lambda Expressions

Disadvantages

The main drawback is that, by using auto, you don't necessarily know the type of
object being created. There are also occasions where the programmer might expect
the compiler to deduce one type, but the compiler adamantly deduces another. It
takes more processing time.

Literals in C++
Literals are the Constant values that are assigned to the constant variables. Literals
represent fixed values that cannot be modified. Literals contain memory but they do
not have references as variables. Generally, both terms, constants, and literals are
used interchangeably.
For example, “const int variable_name = 5;“, is a constant expression and the value 5
is referred to as a constant integer literal. There are 5 types of literal in C++.

 Integer literal
 Float literal
 Character literal
 String literal
 Boolean literal

Integer literals

Integer literals are used to represent and store the integer values only. Integer literals
are expressed in two types i.e.

A) Prefixes: The Prefix of the integer literal indicates the base in which it is to be
read.

There are basically represented into 4 types:

a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more


decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).

Example:

56, 78

b. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6,


7).

Example:

045, 076, 06210

c. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal digits(0, 1,


2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).

Example:

0x23A, 0Xb4C, 0xFEA

d. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0, 1).

Example:

0b101, 0B111

Example:

#include <iostream>
using namespace std;
int main()
{
cout << "Prefixes in Integer Literals\n" ;
{
int a = 20 ; //Decimal
int b = 0x1A; //Hexadecimal
int c = 016; //Octal
int d = 0b11; //Binary
cout << a << "\n"
<< b << "\n"
<< c << "\n"
<< d << "\n";
}
return 0;
}

Output:
Prefixes in Integer Literals
20
26
14
3

B) Suffixes: The Prefix of the integer literal indicates the type in which it is to be
read.

For example:

#include <iostream>
using namespace std;

int main() {

cout << "Suffixes in Integer Literals\n";


int a = 124;
unsigned b = 124u;
long int c = 124L;
long long int d = 124LL;
cout << a << "\n"
<< b << "\n"
<< c << "\n"
<< d << "\n";

return 0;
}

Floating-Point Literals

These are used to represent and store real numbers. The real number has an integer
part, real part, fractional part, and exponential part. The floating-point literals can be
stored either in decimal form or exponential form. While representing the floating-
point decimals one must keep two things in mind to produce valid literal:

In the decimal form, one must include the decimal point, exponent part, or both,
otherwise, it will lead to an error.
 In the exponential form, one must include the integer part, fractional part, or
both, otherwise, it will lead to an error.
A few floating-point literal representations are shown below:
Valid Floating Literals:

10.125
1.215E-10
10.5E-3

Invalid Floating Literals:

123E
1250f
0.e879

Example:

#include <iostream>
using namespace std;

int main()
{
cout << "Floating Point Literals\n";
{
float a = 10.5f;
double b = 10.515;
float c = 2.1e15f;
double d = 200.1e-60;
double f = 0x1A.1p2;
cout << a << "\n"
<< b << "\n"
<< c << "\n"
<< d << "\n"
<< f << "\n";
}
return 0;
}

Output:
Floating Point Literals
10.5
10.515
2.1e+15
2.001e-58
104.25

Character Literal

This refers to the literal that is used to store a single character within a single quote.
To store multiple characters, one needs to use a character array. Storing more than
one character within a single quote will throw a warning and display just the last
character of the literal. It gives rise to the following two representations:
A. char type: This is used to store normal character literal or narrow-character
literals.

Example:
char chr = 'G';

B. wchar_t type: If the character is followed by L, then the literal needs to be stored
in wchar_t. This represents a wide-character literal.

Example:
wchar_t chr = L'G';

Escape Sequences : There are various special characters that one can use to
perform various operations.

Character Literals

Character literals are enclosed in single quotes ( ') and can include prefixes for
different encoding types:

Prefi Examp
Encoding Description
x le

(non Default 1-byte character


ASCII (default) 'g'
e) literal

u8 UTF-8 u8'g' 1-byte UTF-8 encoded literal

2-byte UTF-16 encoded


u UTF-16 u'g'
literal

4-byte UTF-32 encoded


U UTF-32 U'g'
literal

wchar_t (wide Platform-dependent wide


L L'g'
character) literal

4) String Literals

String literals are similar to that character literals, except that they can store multiple
characters and uses a double quote to store the same. It can also accommodate the
special characters and escape sequences mentioned in the table above. We can break
a long line into multiple lines using string literal and can separate them with the help
of white spaces.

Example:
string stringVal = "GeeksforGeeks"

String Literals
String literals are enclosed in double quotes ( ") and may also have prefixes for
encoding:

Prefi Examp
Encoding Description
x le

(non
ASCII (default) "hello" Default string literal
e)

u8"hello UTF-8 encoded string


u8 UTF-8
" literal

UTF-16 encoded string


u UTF-16 u"hello"
literal

UTF-32 encoded string


U UTF-32 U"hello"
literal

wchar_t (wide
L L"hello" Wide string literal
character)

Example:

#include <iostream>
using namespace std;

int main()
{
cout << "Character and String Literals\n";
{
char c = 'g';
const char *s1 = "gfg";
string s2 = "courses";
cout << c << "\n"
<< s1 << "\n"
<< s2 << "\n";
}
return 0;
}

Output:
Character and String Literals
g
gfg
courses

Boolean Literals

This literal is provided only in C++ and not in C. They are used to represent the
boolean datatypes. These can carry two values:

 true: To represent True value. This must not be considered equal to int 1.
 false: To represent a False value. This must not be considered equal to int 0.

Example:

#include <iostream>
using namespace std;

int main()
{
const bool isTrue = true;
const bool isFalse = false;

cout << "isTrue? "


<< isTrue << "\n";
cout << "isFalse? "
<< isFalse << "\n";

return 0;
}

Output
isTrue? 1
isFalse? 0

Type Conversion in C++


A type cast is basically a conversion from one type to another. There are two types of
type conversion:

1. Implicit Type Conversion Also known as ‘automatic type conversion’.


o Done by the compiler on its own, without any external trigger from the
user.
o Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to
avoid lose of data.
o All the data types of the variables are upgraded to the data type of the
variable with largest data type.
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long ->
float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when

signed is implicitly converted to unsigned), and overflow can occur (when long
long is implicitly converted to float).
Example of Type Implicit Conversion:

#include<iostream>
using namespace std;

int main()
{
int x = 10;
char y = 'A';
cout << (x+y) << '\n';
float z = 5.5;
cout << (x+z) << '\n';
bool b = z;
cout << b << '\n';
return 0;
}

Output:
75
15.5
1

2. Explicit Type Conversion: This process is also called type casting and it
is user-defined. Here the user can typecast the result to make it of a
particular data type.

C++ provides several ways to perform explicit type conversion:

1. C-Style Casting
2. C++ Style Casting:
o static_cast
o dynamic_cast
o const_cast
o reinterpret_cast

1. C-Style Casting

This is the traditional way of type casting, inherited from the C programming
language.

Syntax:

(target_type) variable

Example:

#include <iostream>
using namespace std;

int main() {

int x=15,y=2;
double z= double(x)/y;
cout<<z;

return 0;
}

2. C++ Style Casting

C++ introduces safer and more specialized casting operators to replace the generic
C-style cast. These include:

 Static Cast
 Dynamic Cast
 Const Cast
 Reinterpret Cast
Example:

#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
// using cast operator
int b = static_cast<int>(f);
cout << b;
}
Output
3

Advantages of Type Conversion:

 This is done to take advantage of certain features of type hierarchies or type


representations.
 It helps to compute expressions containing variables of different data types.

Input & Output in C++


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

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

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


1. iostream: iostream stands for standard input-output stream. This header file
contains definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The methods declared
in these files are used for manipulating streams. This file contains definitions of
setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This header file is
used to handle the data being read from a file as input or data being written into
the file as output.
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.

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

#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 used to output error messages. It is unbuffered, meaning
messages sent to cerr are displayed immediately without being stored in a
buffer. This ensures errors are displayed promptly. Unlike cout, which is
buffered, cerr is suitable for critical messages. Both cout and cerr can be
redirected, but they are managed as separate streams.

#include <iostream>
using namespace std;

int main()
{
cerr << "An error occurred";
return 0;
}
Output:

An error occurred
 buffered standard error stream (clog): The clog stream in C++ is used for
logging error messages and is buffered. This means data is first inserted into a
buffer and displayed only when the buffer is full or explicitly flushed (e.g., using
flush()). In the provided program, clog outputs the message "An error occurred"
because the program ends, and the buffer is flushed automatically.

#include <iostream>

using namespace std;

int main()
{
clog << "An error occurred";

return 0;
}
Output:
An error occurred

Output in C++
What is cout?
The cout (short for "character output") is part of the Standard Input/Output Stream
Library in C++. It is used to print data to the standard output device, typically the
console. To use cout, the iostream header must be included in your program.

Example 1: Printing a Simple Message

Here is a simple program that demonstrates how to print a message:

#include <iostream>
using namespace std;
int main() {
cout << "Hello Geek!";
return 0;
}
Output:
Hello Geek!

Output Operation: cout << "Hello Geek!"; sends the string "Hello Geek!" to the
console.

Return Statement: return 0; indicates successful program execution.

Example 2: Printing Different Data Types and Expressions

This program demonstrates printing variables of different data types and evaluating
expressions:

#include<iostream>
using namespace std;
int main()
{
// Printing different data types
int a = 1;
float b = 1.1f;
string s = "string";
char c = 'c';
cout << a << " " << b << " " << s << " " << c << endl;

// Printing Literals and expressions


cout << 10 << " " << 10*2 << endl;
return 0;
}
Output:
1 1.1 string c
10 20

Explanation:
Variable Declarations and Initialisation:

 int a = 1;: Declares an integer variable a and assigns it the value 1.


 float b = 1.1f;: Declares a floating-point variable b and assigns it 1.1. The f suffix
specifies it as a float.
 string s = "string";: Declares a string variable s and assigns it the value "string".
 char c = 'c';: Declares a character variable c and assigns it the value 'c'.
Printing Variables:

 cout << a << " " << b << " " << s << " " << c << endl; prints the values of a,
b, s, and c, separated by spaces. The endl moves the cursor to the next line.
Printing Literals and Expressions:

 cout << 10 << " " << 10*2 << endl; prints the literal 10 and the result of the
expression 10*2 (which is 20).

Key Takeaways

Versatile Output: The cout object in C++ can handle multiple data types, including
integers, floats, strings, and characters.

Use of Expressions: You can directly print expressions and their results using cout.

Combining Outputs: The << operator allows chaining, enabling multiple items to be
printed in a single statement.

Line Breaks: Use endl or \n for line breaks in the console output.

Input in C++
The cin object C++ is used to accept the input from the standard input device i.e.,
keyboard. it is the instance of the class istream. It is associated with the standard C
input stream stdin. 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.

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++ program to implement cin object to take input from the user:

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

Note: Multiple inputs can also be taken using the extraction operators(>>) with cin.

C++ program to implement multiple inputs from the user:

// C++ program to demonstrate the taking


// multiple inputs from the user
#include <iostream>
using namespace std;

// Driver Code
int main()
{
string name;
int age;

// Take multiple input using cin


cin >> name >> age;

// Print output
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;

return 0;
}

Input:

ABC
10

Output:
Name : ABC
Age : 10

Taking Full String Input Using getline

In certain cases, the extraction operator (>>) may not be sufficient, such as when
handling multi-word inputs. To handle such scenarios, the getline() function is used to
read the entire line of input.

#include <iostream>
using namespace std;

int main()
{
string name;

cout << "Please enter your name \n";


getline(cin, name); // Reading the full line as input
// cin >> name; // Wrong approach, try giving a full name
cout << "Hi " << name << ", \n"
<< "Welcome to GfG";

return 0;
}

Input: Sandeep jain


Output:
Please enter your name
Hi Sandeep jain,
Welcome to GfG

In this example, getline(cin, name) is used to take the full name of the user as input.
The cin object with the extraction operator (>>) would have only read the first word
("Sandeep") and ignored the rest. By using getline(), the program reads the entire line
of input, including spaces, ensuring the correct output.

A Buffering Example in C++


Understanding Buffering in C++

Buffering is a mechanism used in input/output (I/O) operations to temporarily store


data in memory, known as a buffer, before processing it. In C++, buffering helps to
manage input and output efficiently by reducing the number of direct interactions
with hardware devices like the keyboard or the screen.

What is Buffering?

When you use input operations such as cin, the data entered by the user is first stored
in a temporary memory area called the buffer. The program then retrieves the data
from this buffer. Similarly, output operations like cout temporarily store the data in an
output buffer before displaying it on the screen.

Example: Demonstrating Buffering in C++

The following program illustrates the concept of buffering by taking two integers as
input from the user and displaying their multiplication as the output.

#include <iostream>
using namespace std;

int main()
{
int x, y;

cout << "Enter the first integer: \n";


cin >> x; // Input stored in the buffer and then assigned to x

cout << "Enter the second integer: \n";


cin >> y; // Input stored in the buffer and then assigned to y

cout << "Multiplication is: " << (x * y) << '\n';


return 0;
}
Input:

4
Output:
Enter the first integer:
Enter the second integer:
Multiplication is: 12

Input Buffering:
 When the user enters the first integer (3), it is temporarily stored in the input
buffer.
 The cin >> x; statement retrieves the value from the buffer and assigns it to the
variable x.
 Similarly, when the user enters the second integer (4), it is stored in the buffer
and then assigned to y using cin >> y;.

Output Buffering:
 The cout statements do not directly print to the screen. Instead, the data is
stored in an output buffer.
 The buffer is flushed (i.e., the contents are sent to the screen) when a newline
character (\n) or endl is encountered, ensuring efficient output.

Escape Sequences in C++


The escape sequences are special non-printing characters that are used to control
the printing behavior of the output stream objects (such as ‘cout’). These characters
are not displayed in the output. An escape sequence is prefixed with a backslash (\)
and a coded character is used to control the printing behavior. The backslash (\) is
called an escape character. So the escape sequence looks like two characters.

The escape sequence is used inside a string constant or independently. These are
written in single or double-quotes. The escape sequence can be inserted in any
position of the string such as:

 At the beginning of the string.


 In the middle of the string.
 At the end of the string etc.
For example, the escape sequence ‘\n’ is used to insert a new line. The cursor moves
from the current position on the output device to the beginning of the next line. If
escape sequence ‘\n’ is inserted at the beginning of the string then the string will be
printed after printing a blank line e.g.

cout<<”\nWelcome”;

This statement results in the following output:

Welcome

List of Escape Sequences


Note - The line continuation sequence (\ followed by a new-line character) is not an
escape sequence. It is used in character strings to indicate that the current line of
source code continues on the next line.

 The value of an escape sequence represents the member of the character set
used at run time. Escape sequences are translated during preprocessing. For
example, on a system using the ASCII character codes, the value of the escape
sequence \x56 is the letter V.
 Use escape sequences only in character constants or in string literals. An error
message is issued if an escape sequence is not recognized.
 In string and character sequences, when you want the backslash to represent
itself (rather than the beginning of an escape sequence), you must use
a \ backslash escape sequence. For example: cout << "The escape
sequence \\n." << endl;
This statement results in the following output:

The escape sequence \n

Example -

// c++ program to illustrate


// \n escape sequence
#include <iostream>
using namespace std;
int main()
{
// Here we are using \n, which
// is a new line character.
cout<<"Hello\n"<<endl;
cout<<"GeeksforGeeks"<<endl;
return 0;
}

Output
Hello
GeeksforGeeks

Example - program that displays square, the cube of a number in table form using
Escape Sequences

#include <iostream>
using namespace std;
int main()
{
cout<<" Number\t Square\t Cube "<<endl;
cout<<" 1\t\t"<<1*1<<"\t\t"<<1*1*1<<endl;
cout<<" 2\t\t"<<2*2<<"\t\t"<<2*2*2<<endl;
cout<<" 3\t\t"<<3*3<<"\t\t"<<3*3*3<<endl;
cout<<" 4\t\t"<<4*4<<"\t\t"<<4*4*4<<endl;

Output
Number Square Cube
1 1 1
2 4 8
3 9 27
4 16 64
 The code prints a table with three columns: "Number", "Square", and "Cube".
 The \t escape sequence is used to add tab spaces between the columns,
ensuring the data is aligned properly.
 The endl escape sequence is used to print a newline after each row, making the
output look organized.

IO Manipulation
In C++, input and output (I/O) are fundamental components of any program. Often,
we need to format the output to make it more readable or to meet certain
requirements. C++ provides several tools and manipulators to modify how data is
displayed on the screen. In this article, we will explore some common I/O
manipulations using code examples.

1. Boolean Output Formatting

In C++, the bool data type is used to store Boolean values (true or false). By default,
printing a Boolean value using cout outputs 1 for true and 0 for false. However, we
can use manipulators to change this behavior.

#include <iostream>
using namespace std;
int main()
{
bool a = true;
cout << a << "\n"; // 1
cout << std::boolalpha; // Set output to true/false
cout << a << "\n"; // true
cout << std::noboolalpha; // Set output back to 0/1
cout << a; // 1

return 0;
}

Explanation:

std::boolalpha: This manipulator causes the Boolean values to be printed as true or


false instead of 1 or 0.

std::noboolalpha: Reverts the formatting back to printing 1 for true and 0 for false.

2. Changing Number Base (Decimal, Hexadecimal, Octal)

C++ allows us to display numbers in different numeral systems. By default, integers


are displayed in decimal format, but we can use manipulators to change this to
hexadecimal (std::hex) or octal (std::oct).

#include <iostream>
using namespace std;
int main()
{
int a = 26, b = 20;
cout << a << " " << b << "\n"; // 26 20
cout << std::hex;
cout << a << " " << b << "\n"; // 1a 14
cout << std::oct;
cout << a << " " << b << "\n"; // 32 24
cout << std::dec;
cout << a << " " << b << "\n"; // 26 20
return 0;
}

Explanation:

std::hex: Prints numbers in hexadecimal format (base 16).

std::oct: Prints numbers in octal format (base 8).

std::dec: Reverts back to the default decimal format (base 10).

3. Showing Base Prefix and Uppercase Hexadecimal

In certain cases, it is useful to display numbers with a prefix indicating their base
(e.g., 0x for hexadecimal). Additionally, you may want to display hexadecimal letters
in uppercase.

#include <iostream>
using namespace std;

int main()
{
int a = 26;
cout << std::showbase;
cout << std::oct;
cout << a << "\n"; // 032
cout << std::hex;
cout << a << "\n"; // 0x1a
cout << std::showbase;
cout << a << "\n"; // +0x1a
cout << std::uppercase;
cout << a << "\n"; // +0X1A
return 0;
}

Explanation:

std::showbase: Displays the base prefix (0x for hexadecimal, 0 for octal).

std::uppercase: Converts letters in hexadecimal numbers to uppercase (e.g., a


becomes A).

4. Width, Fill, and Alignment


C++ provides manipulators for controlling the width of the output and for filling empty
spaces. You can set the fill character and control the alignment of the printed data.

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

int main()
{
int a = 12;
cout << std::setw(5); // Set width to 5
cout << std::setfill('*'); // Set fill character to '*'
cout << a << "\n"; // ***12
cout << std::setw(5);
cout << "Hi" << "\n"; // ***Hi
cout << std::left; // Left-align the output
cout << std::setw(5);
cout << a << "\n"; // 12***
return 0;
}

Explanation:

std::setw(n): Sets the width of the output to n characters.

std::setfill(c): Specifies the character to be used for padding if the data is smaller
than the set width. In this case, it is *.

std::left: Aligns the output to the left within the given width. Other alignment options
include std::right (default) and std::center (available in some implementations).

Floating Point Default Print Format


Floating-point numbers are a fundamental part of programming, used to represent
real numbers with fractional parts. However, their default printing behavior can
sometimes be surprising to developers. This article explores the default floating-point
print format, highlighting its quirks and practical implications.

1. No Trailing Zeros

By default, floating-point numbers are printed without unnecessary trailing zeros after
the decimal point. This behavior ensures a more compact and clean representation.
For example:

 3.140000 will be printed as 3.14


 5.000000 will be printed as 5
This approach is beneficial for readability but might need manual adjustments when
uniform formatting (like fixed-width outputs) is required.

2. Precision Refers to Total Digits

Precision in floating-point printing defines the total number of significant digits,


not just the digits after the decimal point. For example:
 If the number is 123.456789, with the default precision of 6, it will be printed
as 123.457 (rounded to six significant digits).
 For 0.000123456, it will be printed as 0.000123456 without rounding until six
significant digits are used.
This behavior emphasizes the value's overall accuracy rather than merely focusing on
its decimal representation.

3. Default Precision Value is 6

When no specific precision is defined, the default is set to 6 significant digits. This
value strikes a balance between readability and precision, ensuring numbers are
neither overly truncated nor too detailed. For example:

 1.23456789 will be printed as 1.23457


 123456789.0 will be printed as 1.23457e+08 (discussed further below).
Developers can modify this default precision using formatting functions (e.g., printf or
Python’s string formatting tools) to suit their application needs.

4. Switching to Power Format

When the value before the decimal point exceeds the available precision (6 digits by
default), the floating-point number is printed in scientific notation (power format).
This ensures that the number remains compact and avoids potential ambiguities. For
example:

 1234567.89 will be printed as 1.23457e+06


 0.000123456 remains 0.000123456 until it requires more precision or falls out of
the precision limit.
Scientific notation is helpful for showing very large or very small numbers in a short
and clear way. However, if scientific notation is not suitable for your needs, you can
adjust the formatting to display the numbers differently.

#include<iostream>
using namespace std;
int main()
{
double x = 1.2300;
cout << x << '\n';
double y = 1567.56732;
cout << y << '\n';
double z = 1244567.45;
cout << z << '\n';
double w = 124456.67;
cout << w << '\n';
double u = 123e+2;
cout << u << '\n';
return 0;
}

Output
1.23
1567.57
1.24457e+06
124457
12300

Floating point Manipulating Default Format


Floating-point numbers are often printed using their default format in programming,
but sometimes, customization is necessary to meet specific requirements. Various
tools and functions allow developers to manipulate the default format, tailoring how
floating-point numbers are displayed. In this article, we’ll explore key methods for
manipulating the default format and their practical applications.

1. Changing Precision with setprecision(n)

The setprecision(n) function lets you control the number of significant digits displayed
when printing floating-point numbers. By default, the precision is set to 6 digits, but
this can be increased or decreased as needed.

2. Showing or Hiding Trailing Zeros with showpoint()

By default, trailing zeros after the decimal point are omitted to keep the output
compact. The showpoint() function forces the display of trailing zeros,
while noshowpoint() reverts back to the default behavior.

3. Displaying Positive Signs with showpos()

By default, only negative numbers are shown with a sign ( -). The showpos() function
explicitly displays the + sign for positive numbers, while noshowpos() disables it.

4. Changing Exponential Notation Case with uppercase()

When using scientific notation, the e in the output is lowercase by default.


The uppercase() function converts it to uppercase ( E), while nouppercase() reverts this
change.

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
cout << setprecision(4);
double x = 15.5683, y = 34267.1;
cout << x << ' ' << y << ' ' << '\n';
double z = 1.23;
cout << showpoint << z << '\n';
cout << showpos << z << '\n';
cout << uppercase << y << '\n';
return 0;
}
Output
15.57 3.427e+04
1.230
+1.230
+3.427E+04

Floating Point Fixed and Scientific


When working with floating-point numbers, the format in which they are displayed
can vary depending on the context. Two primary formats, fixed and scientific,
provide distinct ways to represent these numbers, and each serves different
purposes.

1. Default Format

In the default floating-point format:

 Precision refers to the total number of significant digits in the number.


 The default precision is usually 6 digits, and numbers exceeding this precision
are represented using e-notation (e.g., 1.23×102 is written as 1.23e+02).
Trailing zeros are omitted unless explicitly specified. This results in a concise and
compact representation of numbers.

2. Fixed Format

In the fixed format:

 Precision refers to the number of digits after the decimal point.


 Trailing zeros are added to ensure the specified precision is met.
 e-notation is never used, regardless of the size of the number.

Example:

For a precision of 6:

 X=1.23: Printed as 1.230000


 Y=1122456.453: Printed as 1122456.453000
If the precision is set to 2:

 X=1.23: Printed as 1.23


 Y=1122456.453: Printed as 1122456.45 (rounded to 2 decimal places)

3. Scientific Format

The scientific format always uses e-notation:

 The number is represented as a single digit before the decimal, followed by the
remaining digits and an exponent.
 Precision determines the number of digits after the decimal point.
 Trailing zeros are added to match the desired precision.

Example:

For a precision of 6:

 X=1.23: Printed as 1.230000e+00


 Y=1122456.453: Printed as 1.122456e+06
For a precision of 2:

 X=1.23: Printed as 1.23e+001.23e+001.23e+00


 Y=1122456.453: Printed as 1.12e+06
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double x = 1.23, y = 1122456.453;
cout << std::fixed;
cout << x << "\n"
<< y << "\n";
cout << std::setprecision(2);
cout << x << "\n"
<< y << "\n";
double z = 1.2e+7;
cout << z;
return 0;
}

Output
1.230000
1122456.453000
1.23
1122456.45
12000000.00

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

An operator operates the operands. For example,

int c = a + b;

Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.

Operators in C++ can be classified into 6 types:

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

Arithmetic Operators

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


operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used
for multiplication, etc.

Arithmetic Operators can be classified into 2 Types:

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

Symb
Name Description Example
ol

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

int a = 5;
Decrement Decreases the integer value of the
--
Operator variable by one a- -; // returns
4

Example:

// CPP Program to demonstrate the increment


// and decrement operators
#include <iostream>
using namespace std;

int main()
{
int a = 10;
cout << "a++ is " << a++ << endl;
cout << "++a is " << ++a << endl;
int b = 15;
cout << "b-- is " << b-- << endl;
cout << "--b is " << --b << endl;

return 0;
}

Output
a++ is 10
++a is 12
b-- is 15
--b is 13

Note: ++a and a++, both are increment operators, however, both are slightly
different.

In ++a, the value of the variable is incremented first and then It is used in the
program. In a++, the value of the variable is assigned first and then It is
incremented. Similarly happens for the decrement operator.
B) Binary Operators: These operators operate or work with two operands. For
example: Addition(+), Subtraction(-), etc.

Symb
Name Description Example
ol

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

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

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

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

Modulo % Returns the remainder an integer int a = 8, b = 6;


Operation division
Symb
Name Description Example
ol

int c = a%b; // c
=2

Note: The Modulo operator(%) operator should only be used with integers.
Example:

// CPP Program to demonstrate the Binary Operators


#include <iostream>
using namespace std;

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

// Addition operator
cout << "a + b = " << (a + b) << endl;

// Subtraction operator
cout << "a - b = " << (a - b) << endl;

// Multiplication operator
cout << "a * b = " << (a * b) << endl;

// Division operator
cout << "a / b = " << (a / b) << endl;

// Modulo operator
cout << "a % b = " << (a % b) << endl;

return 0;
}

Output
a + b = 11
a-b=5
a * b = 24
a/b=2
a%b=2

Logical Operators
These operators are used to combine two or more conditions or constraints or to
complement the evaluation of the original condition in consideration. The result
returns a Boolean value, i.e., true or false.

Symb
Name Description Example
ol

Logical && Returns true only if all the operands are true int a = 3, b =
Symb
Name Description Example
ol

6;

AND or non-zero
a&&b;

// returns true

int a = 3, b =
6;
Returns true if either of the operands is true
Logical OR ||
or non-zero a||b;

// returns true

int a = 3;

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

// CPP Program to demonstrate the Logical Operators


#include <iostream>
using namespace std;

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

// Logical AND operator


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

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

// Logical NOT operator


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

return 0;
}

Output
a && b is 1
a ! b is 1
!b is 0

Here, 0 denotes false and 1 denotes true.


Short-Circuiting in Logical Operators:

 In the case of logical AND, the second operand is not evaluated if the first
operand is false. For example, program 1 below doesn’t print “GeeksQuiz” as
the first operand of logical AND itself is false.
#include <iostream>
using namespace std;

int main()
{
int a = 10, b = 4;
bool res = ((a == b) && cout << "GeeksQuiz");
return 0;
}
 But the below program prints “GeeksQuiz” as the first operand of logical AND is
true.
#include <iostream>
using namespace std;

int main()
{
int a = 10, b = 4;
bool res = ((a != b) && cout << "GeeksQuiz");
return 0;
}

Output
GeeksQuiz
 In the case of logical OR, the second operand is not evaluated if the first
operand is true. For example, program 1 below doesn’t print “GeeksQuiz” as the
first operand of logical OR itself is true.
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 4;
bool res = ((a != b) || cout << "GeeksQuiz");
return 0;
}
 But the below program prints “GeeksQuiz” as the first operand of logical OR is
false.
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 4;
bool res = ((a == b) || cout << "GeeksQuiz");
return 0;
}

Output
GeeksQuiz

Assignment Operators
Assignment operators are used to assigning value to a variable. The left side operand
of the assignment operator is a variable and right side operand of the assignment
operator is a value. The value on the right side must be of the same data-type of the
variable on the left side otherwise the compiler will raise an error. Different types of
assignment operators are shown below:

 “=”: 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';
 “+=”: 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. Example:
(a += b) can be written as (a = a + b)

If initially value stored in a is 5. Then (a += 6) = 11.

 “-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the current value of the variable on left from the value on the right
and then assigns the result to the variable on the left. Example:
(a -= b) can be written as (a = a - b)

If initially value stored in a is 8. Then (a -= 6) = 2.

 “*=”This operator is 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. Example:
(a *= b) can be written as (a = a * b)

If initially value stored in a is 5. Then (a *= 6) = 30.

 “/=”This operator is 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. Example:
(a /= b) can be written as (a = a / b)

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

// C++ program to demonstrate


// working of Assignment operators

#include <iostream>
using namespace std;

int main()
{

// Assigning value 10 to a
// using "=" operator
int a = 10;
cout << "Value of a is "<<a<<"\n";

// Assigning value by adding 10 to a


// using "+=" operator
a += 10;
cout << "Value of a is "<<a<<"\n";
// Assigning value by subtracting 10 from a
// using "-=" operator
a -= 10;
cout << "Value of a is "<<a<<"\n";

// Assigning value by multiplying 10 to a


// using "*=" operator
a *= 10;
cout << "Value of a is "<<a<<"\n";

// Assigning value by dividing 10 from a


// using "/=" operator
a /= 10;
cout << "Value of a is "<<a<<"\n";

return 0;
}

Output
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10

Comparison Operator
Comparison operators are used for comparing two elements. They are commonly used
in conditional statements like if-else because they return a boolean value: true (1) if
the condition is satisfied, or false (0) if it is not.

There are mainly 6 Comparison Operators namely:

1. Greater than (>) : Checks if the left operand is greater than the right operand.

Example:

5 > 3 // Returns true

2. Greater than or equal to ( >=): Checks if the left operand is greater than or
equal to the right operand.

Example:

5 >= 5 // Returns true

3. Less than (<): Checks if the left operand is less than the right operand.

Example:

3 < 5 // Returns true


4. Less than or equal to (<=): Checks if the left operand is less than or equal to the
right operand.

Example:

5 <= 5 // Returns true

5. Equal to (==): Checks if the left operand is equal to the right operand.

Example:

5 == 5 // Returns true

6. Not equal to (!=): Checks if the left operand is not equal to the right operand.

Example:

5 != 3 // Returns true

Example Code to cover all 6 Comparison Operators:

#include<iostream>
using namespace std;
int main()
{
int x = 10, y = 20 ;
cout << (x<y) << "\n"
<< (x>y) << "\n"
<< (x==y) << "\n"
<< (x>=y) << "\n"
<< (x<=y) << "\n"
<< (x!=y) << "\n";
return 0;
}

Output
1
0
0
0
1
1

Operator Precedence and Associativity


Operator Precedence determines which operation is performed first in an expression
with more than one operators with different precedence. For example: Solve

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

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


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

Operators Precedence and Associativity are two characteristics of operators

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


brackets.

For example: Solve

100 + 200 / 10 - 3 * 10

1) Associativity is only used when there are two or more operators of same
precedence.
2) All operators with the same precedence have same associativity

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

4) Comma has the least precedence among all operators and should be used
carefully

5) There is no chaining of comparison operators

Example 1: Operators Precedence


#include <iostream>
using namespace std;

int main() {

// evaluates 17 * 6 first
int num1 = 5 - 17 * 6;

// equivalent expression to num1


int num2 = 5 - (17 * 6);

// forcing compiler to evaluate 5 - 17 first


int num3 = (5 - 17) * 6;

cout << "num1 = " << num1 << endl;


cout << "num2 = " << num2 << endl;
cout << "num3 = " << num3 << endl;

return 0;
}

Output
num1 = -97
num2 = -97
num3 = -72

Example 2: Operators Associativity


#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 4;

// a -= 6 is evaluated first
b += a -= 6;

cout << "a = " << a << endl; ;


cout << "b = " << b;
}

Output
a = -5
b = -1

Operator Description Associativ


ity

Parentheses (function call) (see Note 1)


()
Brackets (array subscript)
[]
Member selection via object name left-to-
.
Member selection via pointer right
->
Postfix increment/decrement (see Note
++ – –
2)

Prefix increment/decrement
++ – – Unary plus/minus
+– Logical negation/bitwise complement
!~ Cast (convert value to temporary value
right-to-
(type) of type)
left
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this
implementation

left-to-
* / % Multiplication/division/modulus
right
left-to-
+ – Addition/subtraction
right

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

Relational less than/less than or equal


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

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

left-to-
& Bitwise AND
right

left-to-
^ Bitwise exclusive OR
right

left-to-
| Bitwise inclusive OR
right

left-to-
&& Logical AND
right

left-to-
|| Logical OR
right

right-to-
?: Ternary conditional
left

= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
right-to-
%= &= Modulus/bitwise AND assignment
left
^= |= Bitwise exclusive/inclusive OR
<<= assignment
>>= Bitwise shift left/right assignment

left-to-
, Comma (separate expressions)
right

It is good to know precedence and associativity rules, but the best thing is to use
brackets, especially for less commonly used operators (operators other than +, -, *..
etc). Brackets increase the readability of the code as the reader doesn’t have to see
the table to find out the order.

Binary Representation of Negative Numbers


In computer science, negative numbers are commonly represented using two's
complement form. This method is standard across most programming languages,
even though the language specifications might not explicitly state it. Here's an easy-
to-understand breakdown of what two's complement is and why it's widely used.

Two's Complement: What and Why?

When dealing with binary numbers, the range of values that can be represented
depends on the number of bits used. In two's complement form:

 The range for n bits is from -2n-1 to 2n-1 - 1.


For example, if you have 4 bits:

 The range is -8 to +7.


 This means you can represent 16 distinct numbers (-8, -7, ..., 0, ..., +7).

How Two's Complement Works

To store a negative number in two's complement form:

1. Find the binary representation of the positive value.


2. Invert all the bits (change 0s to 1s and 1s to 0s).
3. Add 1 to the result.

Example: Representing -3 with 4 Bits


1. Start with the binary of 3: 0011.
2. Invert the bits: 1100.
3. Add 1: 1100 + 1 = 1101.
Thus, 1101 is the two's complement representation of -3.

Why Two's Complement is Preferred

Other methods like sign-bit representation and one's complement exist but come with
drawbacks:

1. Sign-bit Representation:
o Uses the first bit to indicate the sign (0 for positive, 1 for negative).
o Problem: There are two representations for 0 (positive 0 and negative 0),
leading to inefficiencies and confusion in arithmetic operations.
2. One's Complement:
o Inverts all the bits of the positive number to represent the negative.
o Problem: Similar to sign-bit, there are two representations for 0, reducing
the range of numbers and complicating arithmetic.
Two's Complement Advantages:

1. Single Representation for Zero:


o Unlike other methods, two's complement has only one representation for
zero.
2. Simplified Arithmetic:
o Adding and subtracting numbers becomes straightforward because the
negative number is stored as 0 - X.
oNo need for special handling of subtraction.
3. Easy to Identify Negative Numbers:
o The leading bit (most significant bit) is always 1 for negative numbers
and 0 for positive numbers.

The Intuition Behind Two's Complement

Two's complement essentially represents negative numbers as their value subtracted


from zero. For example:

 To represent -3, you subtract 3 from 0. The binary representation obtained


aligns with the two's complement form.
This approach simplifies operations like addition and subtraction:

 Adding two's complement numbers (positive or negative) uses the same logic as
adding positive numbers in binary.

Two's complement is the standard way to represent negative numbers in most


programming languages because it simplifies arithmetic, provides a single
representation for zero, and eliminates ambiguities present in other methods. Its
intuitive design ensures efficiency and consistency in computing systems.

Bitwise Operators
These operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands. The mathematical operations such as addition, subtraction, multiplication,
etc. can be performed at the bit-level for faster processing.

Symb
Name Description Example
ol

int a = 2,
b = 3;
The bitwise AND operator performs a bit-by-bit
Binary comparison of two numbers. It returns 1 for each
& (a &
AND bit position where both corresponding bits in the
operands are 1; otherwise, it returns 0. b);
//returns
2

Binary | The bitwise OR operator performs a bit-by-bit int a = 2,


OR comparison of two numbers. It returns 1 for each
b = 3;
bit position where at least one of the corresponding
bits in the operands is 1.
(a | b);
Symb
Name Description Example
ol

//returns
3

int a = 2,
The bitwise XOR operator performs a bit-by-bit b = 3;
comparison of two numbers. It returns 1 for each
Binary
^ bit position where the corresponding bits in the (a ^
XOR
operands are different (i.e., one is 1 and the other b);
is 0); otherwise, it returns 0. //returns
1

int a = 2,
The left shift operator (<<) shifts the bits of its left- b = 3;
hand operand to the left by the number of positions
Left specified by its right-hand operand. For each left
<< (a <<
Shift shift, the most significant bits (leftmost) are
discarded, and 0s are inserted into the least 1);
significant bits (rightmost). //returns
4

The right shift operator (>>) shifts the bits of its int a = 2,
left-hand operand to the right by the number of b = 3;
positions specified by its right-hand operand. For
Right
>> each right shift, the least significant bits (rightmost) (a >>
Shift
are discarded, and the most significant bits 1);
(leftmost) are filled with 0 for unsigned numbers or //returns
the sign bit for signed numbers
1

int b = 3;
The bitwise NOT operator (~) inverts the bits of its
Bitwise operand. For every bit in the number, 0 becomes 1,
~ (~b);
NOT and 1 becomes 0. It essentially flips all bits of the
operand. //returns -
4

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

Example 1: Bitwise AND (&)


#include <iostream>
using namespace std;

int main() {
int x = 3; // Binary: 0011
int y = 6; // Binary: 0110

cout << (x & y); // Perform bitwise AND


return 0;
}
Explanation:

 3 in binary: 0011
 6 in binary: 0110
 AND: 0010
Output: 2

Example 2: Bitwise OR (|)


#include <iostream>
using namespace std;

int main() {
int x = 3; // Binary: 0011
int y = 6; // Binary: 0110

cout << (x | y); // Perform bitwise OR


return 0;
}
Explanation:

 3 in binary: 0011
 6 in binary: 0110
 OR: 0111
Output: 7

Example 3: Bitwise XOR (^)


#include <iostream>
using namespace std;

int main() {
int x = 3; // Binary: 0011
int y = 6; // Binary: 0110

cout << (x ^ y); // Perform bitwise XOR


return 0;
}
Explanation:

 3 in binary: 0011
 6 in binary: 0110
 XOR: 0101
Output: 5

Example 4 : Left Shift Operator (<<)


#include <iostream>
using namespace std;

int main() {
int x = 3; // Binary: 0000...0011
cout << (x << 1) << endl; // Shift left by 1
cout << (x << 2) << endl; // Shift left by 2

int y = 4; // Binary: 0000...0100


int z = (x << y); // Shift left by 4
cout << z; // Output the result

return 0;
}

Explanation of the Code

1. Variable Initialization:
o x = 3: Binary representation: 0000...0011.
o y = 4: Binary representation: 0000...0100.
2. Shift Left by 1 (x << 1):
o Shifting 3 (0000...0011) left by 1 position: 0000...0110.
o Result = 6.
3. Shift Left by 2 (x << 2):
o Shifting 3 (0000...0011) left by 2 positions: 0000...1100.
o Result = 12.
4. Shift Left by y (x << y):
o Shifting 3 (0000...0011) left by 4 positions: 0000...110000.
o Result = 48.
5. Output:
o The program outputs:
 6 for x << 1.
 12 for x << 2.
 48 for x << y

Example 5 : Right Shift Operator (>>)


#include <iostream>
using namespace std;

int main() {
int x = 33; // Binary: 0000...100001
cout << (x >> 1) << endl; // Shift right by 1
cout << (x >> 2) << endl; // Shift right by 2

int y = 4; // Binary: 0000...0100


int z = (x >> y); // Shift right by 4
cout << z; // Output the result

return 0;
}

Explanation of the Code

1. Variable Initialization:
o x = 33: Binary representation: 0000...100001.
o y = 4: Binary representation: 0000...0100.
2. Right Shift Operations:
o x >> 1: Shifts x (33) right by 1 bit ( 0000...100001 → 0000...010000), result
= 16.
o x >> 2: Shifts x (33) right by 2 bits ( 0000...100001 → 0000...001000), result
= 8.
o x >> y: Shifts x (33) right by 4 bits (0000...100001 → 0000...000010), result
= 2.
3. Output:
o First cout outputs 16.
o Second cout outputs 8.
o Third cout outputs 2.

Left Shift Operator (<<)


1. The left shift operator is equivalent to multiplying a number by 2 y, where y is the
number of positions shifted.
2. Appending a 0 to the trailing bits during a left shift is what makes the operation
equivalent to multiplication by 2.
3. It assumes that the leading bits of the number are 0. If the leading bits
are 1 (e.g., in very large numbers), the result may not correctly represent
2y multiplication.
4. Using left shift for multiplication is efficient and fits well within the constraints of
32-bit integers. Traditional multiplication may not work correctly with very large
numbers due to overflow.

Right Shift Operator (>>)


1. The right shift operator is equivalent to dividing a number by 2 y and taking the
floor of the result (integer division).
2. It discards the least significant bits (trailing bits) during the shift.
3. For example:
o 33 >> 1 is equivalent to 33/21=16.5, and the floor is 16.
o 33 >> 2 is equivalent to 33/22=8.25, and the floor is 8.
4. The right shift is useful for efficiently performing division by powers of 2 without
introducing decimal points or inaccuracies.

Example 6 : Bitwise NOT Operator (~)


#include <iostream>
using namespace std;

int main() {
unsigned int x = 1; // Binary: 0000...0001
cout << (~x) << endl; // Perform bitwise NOT on x

x = 5; // Binary: 0000...0101
cout << (~x) << endl; // Perform bitwise NOT on x

return 0;
}

Explanation of the Code

1. Variable Initialization:
o x = 1: Binary representation: 0000...0001.
o x = 5: Binary representation: 0000...0101.
2. Bitwise NOT Operation:
o For x = 1:
 ~x: Inverts 0000...0001 to 1111...1110.
 Decimal value: 232−1−1=42949672942^{32} - 1 - 1 =
4294967294232−1−1=4294967294 (for 32-bit unsigned integer).
o For x = 5:
 ~x: Inverts 0000...0101 to 1111...1010.
 Decimal value: 232−1−5=42949672902^{32} - 1 - 5 =
4294967290232−1−5=4294967290.
3. Output:
o First cout outputs 4294967294.
o Second cout outputs 4294967290.

Day before N days


In this article, we will explore a problem-solving technique in C++ to calculate the day
before a given day. This involves leveraging modular arithmetic and conditional
checks. The goal is to determine the previous day based on a numerical
representation of the week, where 0 corresponds to Sunday, 1 to Monday, 2 to
Tuesday, and so on, up to 6 for Saturday.

Problem Description

You are provided with:

 d: A numerical representation of a current day.


 n: The number of days to go back.
Your task is to calculate the day before N days. For example:

 If d = 1 (Monday) and n = 1, the output is 0 (Sunday).


 If d = 0 (Sunday) and n = 9, the output is 5 (Friday).

Solution Steps

To solve this problem, we use the following steps:

1. Reduce N to a Cyclic Range (0-6):


o Compute N % 7. This ensures N is within a single week's range since the
week repeats cyclically every 7 days.
2. Subtract N from D:
o Compute D - (N % 7) to find the preliminary day before N days.
3. Handle Negative Results:
o If the result of the subtraction is negative, add 7 to bring it back within the
valid range of 0-6.
4. Output the Result:
o Return the calculated day.

Code Implementation
#include <bits/stdc++.h>
using namespace std;
// Deleting element while you go

int main() {
int d = 0; // The current day (0 = Sunday)
int n = 9; // Days to go back

// Step 1: Calculate the cyclic range of N


int x = n % 7;

// Step 2: Subtract the value from D


int ans = d - x;

// Step 3: Handle negative results


if (ans >= 0)
cout << ans;
else
cout << ans + 7;

return 0;
}
Output: 5

Explanation:

 d=0,n=9
 Calculate n%7:9%7=2.
 Subtract x from d: 0−2=−2
 Check if the result is negative: −2 is negative, so add 7: −2+7=5.
 The output is 5, which corresponds to Friday.

Last Digit of a Number


In this article, we will discuss how to find the last digit of a given number. This
problem includes handling both positive and negative integers to determine the
correct last digit. The solution is simple and involves the modulus operator % to
isolate the last digit. We'll also explore how to handle negative numbers effectively to
ensure that the output is always a positive last digit.

Problem Statement

Given an integer, the task is to find its last digit. For instance:

 For 123, the last digit is 3.


 For −352, the last digit is 2.
 For 1049, the last digit is 9.
 For −49, the last digit is 9.

Observations and Approach

Key Observations:
1. When dividing a number by 10, the remainder gives the last digit.
o For example, 123%10=3, which is the last digit.
2. If the number is negative, using the modulus operator directly will yield a
negative last digit.
o For example, abs(−235%10) = 5.

Solution Steps:
1. Calculate the last digit using the modulus operator % 10.
2. If the number is negative, use the abs() function to convert the last digit to a
positive value.

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

int main() {
int x = -235; // Input number
int ans = abs(x % 10); // Find the last digit using modulus and convert to positive if needed

cout << ans; // Output the last digit


return 0;
}

Output: 5

AP Term
In this article, we will explore how to find the Nth term of an Arithmetic Progression
(AP) series. Arithmetic Progression is a sequence of numbers in which the difference
between any two consecutive terms is constant. This difference is referred to as
the common difference (denoted as D).

Understanding Arithmetic Progression

An Arithmetic Progression (AP) follows this rule: TN=A+(N−1)×D

Where:

TN : The Nth term to be calculated.

A : The first term of the series.

D : The common difference between consecutive terms.

N : The term number to find.

Example

Consider the AP: 2,5,8,11,14.

 The first term (A) = 2.


 The common difference (D) = 3.
Using the formula:

 The 3rd term (T3) = 2+(3-1) x 3=2+6=8.


 The 5th term (T5) = 2+(5-1) x 3 = 2+12=14.

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

int main() {
// Starting number
int a = 2;

// Common difference
int d = 1;

// Nth term to find


int N = 5;

// Calculate the Nth term


int ans = (a + (N - 1) * d);

cout << ans;

return 0;
}
Output : 6

Geometric Progression
In this article, we will explore how to find the Nth term of a Geometric Progression
(GP) using C++. A geometric progression is a sequence where each term is obtained
by multiplying the previous term by a fixed, non-zero number called the common
ratio.

Understanding Geometric Progression

In a Geometric Progression, the Nth term can be calculated using the formula:

TN=A×R(N−1)

Where:

TN : The Nth term to be calculated.

A: The first term of the series.

R: The common ratio between consecutive terms.

N: The term number to find.

Example

Consider the GP: 2,4,8,16,32


 The first term (A) = 2.
 The common ratio (R) = 2.
Using the formula:

 The 3rd term (T3) = 2 x 2(3-1)= 2 x 4 = 8


 The 5rd term (T5) = 2 x 2(5-1)= 2 x 16 = 32

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

// CPP Program to find nth term of geometric progression


int main() {
// Starting number
int a = 2;

// Common ratio
int r = 3;

// Nth term to be found


int N = 3;

// Calculate the Nth term


int ans = a * (int)(pow(r, N - 1));

// Display the output


cout << ans;

return 0;
}
Output: 18

If Else Syntax in C++


Decision Making helps to write decision driven statements and execute a particular
set of code based on certain conditions.

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

Working of if-else statements

1. Control falls into the if block.


2. The flow jumps to Condition.
3. Condition is tested.
1. If Condition yields true, goto Step 4.
2. If Condition yields false, goto Step 5.
4. The if-block or the body inside the if is executed.
5. The else block or the body inside the else is executed.
6. Flow exits the if-else block.

Example: Even or Odd Program


Let’s look at an example to determine whether a given number is even or odd using
the if-else statement.

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter your number:\n";
cin >> n;

if (n % 2 == 0) {
cout << "Even \n";
} else {
cout << "Odd \n";
}

return 0;
}

How the Program Works

1. Input:
o The user is prompted to enter a number, which is stored in the variable n.
2. Condition Check:
o The condition n % 2 == 0 is evaluated:
 If n is divisible by 2 (i.e., the remainder is 0), the condition is true,
and the program prints "Even".
 Otherwise, the condition is false, and the program prints "Odd".
3. Output:
o Based on the evaluation of the condition, the appropriate block of code is
executed.
Input:

Enter your number: 7


Output:

Odd

Else If with Example


There come situations in real life when we need to make some decisions and based on
these decisions, we decide what should we do next. Similar situations arise in
programming also where we need to make some decisions and based on these
decisions we will execute the next block of code.
For example, in C++ if x occurs then execute y else execute z. There can also be
multiple conditions like in C++ if x occurs then execute p, else if condition y occurs
execute q, else execute r. This condition of C++ else-if is one of the many ways of
importing multiple conditions.

if-else-if ladder in C++


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 is true, then the final else statement will be executed.

Syntax:

if (condition1)
{
// Execute if condition1 is true
}
else if (condition2)
{
// Execute if condition2 is true
}
.
.
else
{
// Execute if no other condition is true
}
Example: Check if a Number is Positive, Negative, or Zero

Let’s use the else if statement to determine if a number is positive, negative, or zero.

#include<iostream>
using namespace std;
int main()
{
int n;
cout << "Enter a number:\n";
cin >> n;
if(n>0)
{
cout << "Positive \n";
}
else if(n<0)
{
cout << "Negative \n";
}
else
{
cout << "Zero \n";
}
return 0;

}
Conditions:

 First if condition: Checks if n > 0. If true, the program prints "Positive".


 else if condition: If the first condition is false, checks if n < 0. If true, the
program prints "Negative".
 else block: If neither condition is true (i.e., n == 0), the program prints "Zero".

Input 1:
Enter a number: 5

Output:

Positive

Nested If Else with Example


A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. 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 both condition1 and condition2 are true
}
else
{
// Executes when condition1 is true and condition2 is false
}
}
else
{
//Executes when condition1 is false
}

Flowchart

Example: Check Positive, Negative, Even, Odd, or Zero

Let’s explore a program that uses nested if-else to determine:

 If a number is positive, negative, or zero.


 If it's even or odd (for positive and negative numbers).
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a number:\n";
cin >> n;

if (n > 0) {
cout << "Positive ";
if (n % 2 == 0) {
cout << "Even\n";
} else {
cout << "Odd\n";
}
} else if (n < 0) {
cout << "Negative ";
if (n % 2 == 0) {
cout << "Even\n";
} else {
cout << "Odd\n";
}
} else {
cout << "Zero\n";
}

return 0;
}

Explanation of the Code

1. Outer if-else:
o The first if checks if the number is greater than 0. If true, it identifies the
number as positive.
o The else if checks if the number is less than 0. If true, it identifies the
number as negative.
o The else block handles the case where the number is 0.
2. Inner if-else:
o Inside the positive and negative blocks, an inner if-else checks whether
the number is even (n % 2 == 0) or odd (else block).

Input 1:
Enter a number:
5

Output:

Positive Odd

Input 2:
Enter a number:
-8

Output:

Negative Even
Switch in C++
The switch statement in C++ is a control structure that allows you to execute one
block of code out of many based on the value of a variable or expression. It is an
alternative to using multiple if-else statements and provides better readability and
performance for multi-branch condition.

In C++, the switch statement is used for executing one condition from multiple
conditions. It is similar to an if-else-if ladder.

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 i.e., the “case value” can be of “char” and “int” type.
Flowchart:

Example:

#include <iostream>
using namespace std;

int main() {
int x = 0, y = 0;
cout << "Enter a choice (L, R, U, D):\n";
char move;
cin >> move;

switch (move) {
case 'L':
x--; // Move left
break;
case 'R':
x++; // Move right
break;
case 'U':
y++; // Move up
break;
case 'D':
y--; // Move down
break;
default:
cout << "Invalid choice";
}

cout << "New Position: " << x << " " << y << '\n';
return 0;
}

Input 1:
Enter a choice (L, R, U, D):
L

Output:

-1 0

Input 2:
Enter a choice (L, R, U, D):
Z

Output:

Invalid choice
New Position: 0 0

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

For example: Suppose we want to print “Hello World” 10 times. This can be done in
two ways as shown below:

Manual Method (Iterative Method)

Before understanding loops, let’s look at the manual way to solve repetitive tasks.
Here is an example program to print the multiplication table of a number: So, here
loops have their role.

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a Number: ";
cin >> n;

// Manually printing the table


cout << n * 1 << " "
<< n * 2 << " "
<< n * 3 << " "
<< n * 4 << " "
<< n * 5 << " "
<< n * 6 << " "
<< n * 7 << " "
<< n * 8 << " "
<< n * 9 << " "
<< n * 10 << endl;
return 0;
}
Example Input and Output:

Input: n = 3

Output:

3 6 9 12 15 18 21 24 27 30

While this works, the manual method becomes tedious and error-prone when scaling
up for larger tasks. That’s where loops come in.

Applications of Loops in C++

Loops have a wide range of applications in programming. Some common use cases
include:

1. Performing Repeated Tasks:


o Loops are used to execute a set of instructions multiple times. For
example, calculating factorials, generating patterns, or processing
multiple inputs.
2. Traversing Through Collections:
o Loops are essential for traversing arrays, strings, maps, and other data
structures. They make it easy to iterate through elements for
manipulation or computation.
o Example: Traversing an array to calculate the sum of its elements.
3. Running Services in Systems:
o Loops can run indefinitely to keep systems and services operational.
o Examples include:
 Web Servers: An infinite loop listens for and handles user requests.
 Memory Managers: Continuously monitor and allocate memory.
 Process Managers: Handle multiple processes in an operating
system.

While Loop in C++


The while loop is one of the fundamental loops in C++ that allows repeated
execution of a block of statements as long as a specified condition evaluates to true
##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.

Syntax:

initialization expression
while (condition) {
// Statement 1
// Statement 2
// ...
}
 Condition: The condition is evaluated before each iteration of the loop.
 If the condition is true, the statements inside the loop body are executed.
 If the condition is false, the loop terminates, and the program continues with the
next statement after the loop.

Flow Diagram of while loop:


#include <iostream>
using namespace std;

int main() {
int i = 0;
while (i < 5) {
cout << "GfG\n";
i++;
}
return 0;
}

Output:
GfG
GfG
GfG
GfG
GfG

Execution Flow

Here is the detailed execution flow of the program:

 Iteration 1:
o i=0
o Condition i < 5 is true.
o Output: GfG
o i is incremented to 1.
 Iteration 2:
o i=1
o Condition i < 5 is true.
o Output: GfG
o i is incremented to 2.
 Iteration 3:
o i=2
o Condition i < 5 is true.
o Output: GfG
o i is incremented to 3.
 Iteration 4:
o i=3
o Condition i < 5 is true.
o Output: GfG
o i is incremented to 4.
 Iteration 5:
o i=4
o Condition i < 5 is true.
o Output: GfG
o i is incremented to 5.
 Iteration 6:
o i=5
o Condition i < 5 is false.
o The loop terminates.

For Loop in C++


The for loop is a fundamental looping construct in C++ that allows you to execute a
block of code a specific number of times. It is especially useful when the number of
iterations is known in advance.

Syntax:

for (initialization; condition; update)


{ // Statements to be executed inside the loop
}

In for loop, a loop variable is used to control the loop. First, initialize this loop variable
to some value, then check whether this variable is less than or greater than the
counter value. If the statement is true, then the loop body is executed and the loop
variable gets updated. Steps are repeated till the exit condition comes.

1. Initialization: This part initializes the loop control variable(s). It is executed


once at the beginning of the loop.
2. Condition: This condition is evaluated before each iteration of the loop. If it
evaluates to true, the loop body executes. If it evaluates to false, the loop
terminates.
3. Update: This part updates the loop control variable(s) after each iteration.
Example 1: Basic For Loop
#include <iostream>
using namespace std;

int main() {
for (int i = 0; i < 3; i++) {
cout << "GfG\n";
}
return 0;
}
Explanation:

 Initialization: int i = 0 sets i to 0.


 Condition: i < 3 ensures the loop runs as long as i is less than 3.
 Update: i++ increments i after each iteration.

Output:
GfG
GfG
GfG

Example 2: Printing Variable Values


#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 3; i++) {
cout << "GfG " << i << endl;
}
return 0;
}
Explanation:

 The variable i is printed alongside "GfG" during each iteration.

Output:
GfG 0
GfG 1
GfG 2

Flow Diagram of for loop:

Example 3: Modifying the Start Condition


#include <iostream>
using namespace std;

int main() {
for (int i = 3; i < 3; i++) {
cout << "GfG\n";
}
return 0;
}
Explanation:

 The condition i < 3 is false at the start, so the loop body does not execute.
 Output: No output.

Example 4: Custom Increment


#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 10; i += 2) {
cout << "GfG\n";
}
return 0;
}
Explanation:

The increment step is i += 2, so i increases by 2 after each iteration.


Output:

GfG
GfG
GfG
GfG
GfG

Example 5: Infinite For Loop


#include <iostream>
using namespace std;

int main() {
for (;;) {
cout << "GfG\n";
}
return 0;
}
Explanation:

 All parts of the for loop (initialization, condition, update) are omitted.
 This creates an infinite loop that prints "GfG" endlessly.
 Output: "GfG" printed continuously until manually terminated.

When to Use a For Loop vs. While Loop

1. For Loop:
o Use when the number of iterations is known or can be calculated in
advance.
o Example: Iterating over an array or printing a sequence of numbers.
2. While Loop:
o Use when the number of iterations depends on a condition that is
evaluated during runtime.
o Example: Waiting for user input or processing data until a certain
condition is met.
Key Difference: The initialization, condition, and update are handled in one line in a
for loop, making it concise and ideal for counters. A while loop offers more flexibility
when the condition is dynamically determined.

Do While Loop in C++


Loops come into use when we need to repeatedly execute a block of statements.
Like while the do-while loop execution is also terminated on the basis of a test
condition. The main difference between a do-while loop and a 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 the do-while loop, the loop body will execute at least once irrespective of the
test condition.

Syntax:

do
{
// Statements to be executed inside the loop

update_expression;
}
while (test_expression);

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


The various parts of the do-while loop are:

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
the update expression. Otherwise, we will exit from the while loop.
2. Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value.
3. Body: It is the Collection of statements i.e, variables and functions, etc. The
condition is not satisfied until the condition is executed automatically after a
successful iteration. do-while loop, code can be used to print simple names,
execute complex algorithms, or perform functional operations.

How does a do-While loop execute?


1. Control falls into the do-while loop.
2. The statements inside the body of the loop get executed.
3. Updation takes place.
4. The flow jumps to Condition
5. Condition is tested.
o If the Condition yields true, go to Step 6.
o If the Condition yields false, the flow goes outside the loop
6. The flow goes back to Step 2.
7. The do-while loop has been ended and flow has gone outside the loop.

Flow Diagram of do-while loop:


Example

#include <iostream>
using namespace std;

int main() {
int i = 3;
do {
cout << "GfG\n";
i++;
} while (i < 3);

return 0;
}
Explanation:

1. Initialization: The variable i is initialized to 3.


2. Loop Body Execution: The statement cout << "GfG\n"; is executed before the
condition is checked.
3. Condition: The condition i < 3 is evaluated after the first iteration.
Since i becomes 4 after the increment, the condition evaluates to false, and the
loop terminates.

Output:
GfG

Key Point: The loop executes the body at least once, even if the condition is false
initially.
Characteristics of the Do-While Loop

1. Guaranteed Execution: The loop body is executed at least once, regardless of


whether the condition is true or false.
2. Condition Checking: The condition is checked after the loop body executes,
making it suitable for scenarios where you want to ensure the code runs at least
once.

When to Use a Do-While Loop

1. Menu-Driven Programs:
o When you need to display a menu and take user input at least once.
o Example:
char choice;
do {
cout << "Enter your choice (y/n): ";
cin >> choice;
} while (choice != 'n');
2. Input Validation:
o When you need to validate user input and ensure the prompt is displayed
at least once.
o Example:
int num;
do {
cout << "Enter a positive number: ";
cin >> num;
} while (num <= 0);
3. Running Code At Least Once:
o When the logic requires the code to run before evaluating a condition.

Comparison with Other Loops

Feature For Loop While Loop Do-While Loop

Condition Before the loop Before the loop body After the loop body
Check body executes executes executes

Execution Executes only if the Executes only if the Executes the loop
Guarantee condition is true condition is true body at least once

Known number of Condition-based Run-at-least-once


Use Case
iterations iterations scenarios

Break in C++
The break in C++ is a loop control statement which is used to terminate the loop. As
soon as the break statement is encountered from within a loop, the loop iterations
stops there and control returns from the loop immediately to the first statement after
the loop.
Syntax:

break;

Basically break statements are used in the situations when we are not sure about the
actual number of iterations for the loop or we want to terminate the loop based on

some condition.

We will see here the usage of break statement with three different types of
loops:

1. Simple loops
2. Nested loops
3. Infinite loops

Example: Finding the Smallest Divisor


The following program demonstrates how to use the break statement to find the
smallest divisor of a number greater than 1:

#include <iostream>
using namespace std;

int main() {
int n;
cin >> n;
for (int x = 2; x <= n; x++) {
if (n % x == 0) {
cout << "Smallest Divisor: " << x << endl;
break;
}
}
return 0;
}
Explanation:

1. The loop starts with x = 2 and increments x on each iteration.


2. The condition n % x == 0 checks if x is a divisor of n.
3. If the condition is true, the smallest divisor is printed, and the break statement
terminates the loop.
4. The loop exits as soon as the first divisor is found, making the program efficient.
Input and Output:

 Input: n = 6
Output:
Smallest Divisor: 2
 Input: n = 49
Output:
Smallest Divisor: 7

Example: Using break in a While Loop

Consider another example where break is used to terminate a while loop when a
specific condition is met:

#include <iostream>
using namespace std;

int main() {
int i = 1;
while (i <= 5) {
if (i == 3) {
break;
}
cout << i << " ";
i++;
}
cout << i << " ";
return 0;
}

Explanation:
1. The loop starts with i = 1 and continues until i <= 5.
2. When i == 3, the break statement is executed, and the loop terminates.
3. The value of i is printed before the condition is checked.
Output:

123

Applications of break

1. Early Exit from Loops:


o Use break to stop a loop once the desired result is achieved, improving
efficiency.
o Example: Finding a specific element in an array.
2. Menu-Driven Programs:
o Use break to exit from a loop when the user chooses to quit.
3. Switch Statements:
o Use break to terminate a case block in a switch statement, ensuring the
program doesn’t execute subsequent cases unnecessarily.

Continue in C++
Continue is also a loop control statement just like the break
statement. continue statement is opposite to that of break statement, instead of
terminating the loop, it forces to execute the next iteration of the loop.
As the name suggest the continue statement forces the loop to continue or execute
the next iteration. When the continue statement is executed in the loop, the code
inside the loop following the continue statement will be skipped and next iteration of
the loop will begin.

Syntax:

continue;

When the continue statement is encountered in a loop, the rest of the code inside the
loop following the continue statement is skipped, and the next iteration begins.

Example:
Consider the situation when you need to write a program which prints number from 1
to n that are not multiples of x. It is specified that you have to do this using loop and
only one loop is allowed to use.
Here comes the usage of continue statement. What we can do here is we can run a
loop from 1 to n and every time we have to compare the value to the multiple of x. If
it is multiple of x we will use the continue statement to continue to next iteration
without printing anything otherwise we will print the value.
Below is the implementation of the above idea:

#include <iostream>
using namespace std;
int main() {
int n, x;
cout << "Enter n \n";
cin >> n;
cout << "Enter x \n";
cin >> x;
for (int i = 1; i <= n; i++) {
if (i % x == 0)
continue;
cout << i << " ";
}
return 0;
}
Explanation:

1. The user inputs two numbers n and x.


2. A for loop iterates from 1 to n.
3. The condition if (i % x == 0) checks if i is a multiple of x.
4. If the condition is true, the continue statement is executed, skipping the rest of
the loop body and moving to the next iteration.
5. If the condition is false, the number i is printed.
Input and Output:

Input: n = 10, x = 3
Output:
1 2 4 5 7 8 10
Input: n = 7, x = 5

Output:
123467

Use Case: Skipping Specific Conditions in Loops

Consider a situation where you need to print numbers from 1 to 10 but skip the
number 6. This can be achieved using the continue statement as shown below:

#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 6)
continue;
cout << i << " ";
}
return 0;
}
Output:

1 2 3 4 5 7 8 9 10

Explanation:

 The loop skips the iteration where i == 6 and continues with the next iteration,
thereby avoiding printing 6.
Nested loop in C++
In C++, a nested loop is a loop inside another loop. Nested loops are useful for
iterating over multi-dimensional data structures or performing repetitive tasks that
involve multiple variables. This article explores the concept of nested loops, their
syntax, and examples based on the provided lecture notes.

Syntax of Nested Loops

The general structure of nested loops is:

for ( initialization; condition; increment )


{

for ( initialization; condition; increment )


{

// statement of inside loop


}

// statement of outer loop


}
Outer Loop: The outer loop controls the number of iterations for the inner loop.

Inner Loop: The inner loop executes completely for every iteration of the outer

loop.
Syntax for Nested While loop:

while(condition)
{
while(condition)
{

// statement of inside loop


}

// statement of outer loop


}

Note: There is no rule that a loop must be nested inside its own type. In fact, there
can be any type of loop nested inside any type and to any level.
Syntax:

do{

while(condition)
{

for ( initialization; condition; increment )


{

// statement of inside for loop

// statement of inside while loop

// statement of outer do-while loop

}while(condition);

Below are some examples to demonstrate the use of Nested Loops:

Example 1: Multiplication Table


The following program demonstrates the use of nested loops to print a multiplication
table:

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter n:\n";
cin >> n;

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


for (int i = 1; i <= 10; i++) {
cout << (x * i) << " ";
}
cout << "\n";
}
return 0;
}
Execution Flow:

For x = 1, the inner loop prints the multiples of 1: 1 2 3 4 5 6 7 8 9 10.


For x = 2, the inner loop prints the multiples of 2: 2 4 6 8 10 12 14 16 18 20.
For x = 3, the inner loop prints the multiples of 3: 3 6 9 12 15 18 21 24 27 30.
Input and Output:

 Input: n = 3
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30

Example 2: Below program uses a nested for loop to print all prime factors of a
number.

// C++ Program to print all prime factors


// of a number using nested loop

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

/* Driver program to test above function */


int main()
{
int n = 315;
// Print the number of 2s that divide n
while (n % 2 == 0)
{
cout << 2;
n = n / 2;
}

// n must be odd at this point. So we can skip


// one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i + 2)
{
// While i divides n, print i and divide n
while (n % i == 0)
{
cout << i;
n = n / i;
}
}

// This condition is to handle the case when n


// is a prime number greater than 2
if (n > 2)
cout << n;
return 0;
}

Output
3357

Functions in C++
Functions are one of the most essential features in C++ (and most programming
languages), offering a modular way to write, organize, and maintain code. By
encapsulating specific tasks within functions, developers can reduce redundancy,
improve code readability, and simplify debugging. This article delves into the concept
of functions in C++, exploring their syntax, use cases, and benefits.

Syntax:

Key Benefits of Functions:

1. Code Reusability: Write once, use multiple times.


2. Reduced Redundancy: Avoid repeating similar code in multiple places.
3. Ease of Maintenance: Changes in the function logic need to be done only
once, and they automatically reflect wherever the function is called.
4. Improved Readability: Functions with meaningful names help make code self-
explanatory.

Example 1: A Simple Function


#include <iostream>
using namespace std;

void fun() {
cout << "Fun() Called\n";
}

int main() {
cout << "Before calling fun()\n";
fun();
cout << "After calling fun()\n";
return 0;
}
Output:

Before calling fun()


Fun() Called
After calling fun()

Explanation:

 The function fun() is defined to print a message.


 In the main() function, fun() is called, executing its logic.
 Once the function completes, control returns to the caller ( main()), which
continues execution.

Example 2: Function with Multiple Calls


#include <iostream>
using namespace std;

void fun() {
cout << "Fun() Called\n";
}

int main() {
cout << "Before calling fun()\n";
fun();
fun();
cout << "After calling fun()\n";
return 0;
}
Output:

Before calling fun()


Fun() Called
Fun() Called
After calling fun()

This demonstrates that a function can be called multiple times, each time executing
its logic.

Functions with Parameters and Return Values

A function can also take inputs (parameters) and return a result. This enhances
flexibility and reusability.

Example 3: Finding the Maximum of Two Numbers

#include <iostream>
using namespace std;

int getMax(int x, int y) {


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

int main() {
int a = 10, b = 20;
cout << getMax(a, b);
return 0;
}
Output:

20

Explanation:

 The function getMax() takes two integers and returns the larger of the two.
 The main() function calls getMax() with a and b as arguments.

Example: Modular Code with Multiple Functions

Here’s an example with two functions: greetMsg() for a greeting message


and exitMsg() for a goodbye message.

#include <iostream>
using namespace std;

void greetMsg() {
cout << "Hi,\n";
cout << "Welcome to GeeksforGeeks\n";
}

void exitMsg() {
cout << "Bye,\n";
cout << "Visit again\n";
}

int main() {
greetMsg();
cout << "Hope you are enjoying\n";
exitMsg();
return 0;
}
Output:

Hi,
Welcome to GeeksforGeeks
Hope you are enjoying
Bye,
Visit again

Explanation:

 greetMsg() is called at the start, printing a welcome message.


 After an intermediate message in the main() function, exitMsg() is called,
printing a goodbye message.

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.

How Functions Work in C++?


When working with C++ programs, understanding how functions are executed
internally is critical. Let’s explore this concept using an example program and the
concept of the function call stack.

The Code Example

Below is the program that demonstrates function calls in C++:

#include <iostream>
using namespace std;

void fun2() {
cout << "Inside fun2()\n";
}

void fun1() {
cout << "Before fun2()\n";
fun2();
cout << "After fun2()\n";
}

int main() {
cout << "Before fun1()\n";
fun1();
cout << "After fun1()\n";
return 0;
}
Output of the Program
The output of this program will be:

Before fun1()
Before fun2()
Inside fun2()
After fun2()
After fun1()

Program Execution Flow

The program consists of three functions: main, fun1, and fun2. Here’s the step-by-step
flow of execution:
1. The main function starts execution.
2. main calls fun1 and pauses its execution.
3. fun1 begins execution and prints "Before fun2()".
4. fun1 calls fun2 and pauses its execution.
5. fun2 begins execution, prints "Inside fun2()", and completes.
6. Control returns to fun1, which resumes execution and prints "After fun2()".
Then, fun1 finishes.
7. Control returns to main, which resumes execution and prints "After fun1()".
Finally, main finishes.

Function Call Stack

The function call stack is a key concept to understand how function calls work in C+
+:

1. What is a Stack?
o A stack is a data structure with a Last In, First Out (LIFO) property.
Elements are added and removed from the top of the stack.
2. How Function Calls Use a Stack
o When a function is called, an entry is pushed onto the function call stack.
o This entry contains:
 The function’s local variables.
 The current execution state of the function (e.g., the next line to
execute).
o When the function completes, its entry is removed (popped) from the
stack, and control returns to the caller function.

Step-by-Step Function Call Stack Execution

Let’s see how the stack evolves for the provided program:

1. Initial State
o main starts, and its entry is pushed onto the stack.
2. Calling fun1
o main calls fun1.
o The state of main is saved (paused), and an entry for fun1 is pushed onto
the stack.
3. Calling fun2
o fun1 calls fun2.
o The state of fun1 is saved, and an entry for fun2 is pushed onto the stack.
4. Completion of fun2
o fun2 completes execution and is popped from the stack.
o Control returns to fun1.
5. Completion of fun1
o fun1 completes execution and is popped from the stack.
o Control returns to main.
6. Completion of main
o main completes execution and is popped from the stack.

Visualizing the Stack

Here’s how the stack evolves during execution:


Stack (Top to
Step
bottom)

Start main main

main calls
fun1,main
fun1

fun1 calls
fun2,fun1,main
fun2

fun2
fun1,main
completes

fun1
main
completes

main
(Empty)
completes

Key Points to Remember

1. The function call stack ensures proper sequencing of function calls and returns.
2. When a function is called, its execution is suspended until the called function
completes.
3. The LIFO nature of the stack allows the most recently called function to
complete first.
4. Local variables and execution state are stored in the stack for each function call.

Applications of Functions
Functions play a crucial role in programming by enhancing code efficiency,
readability, and maintainability. Here's an overview of functions' various applications
and why they are essential in software development.

Avoiding Code Redundancy


There are certain functionalities are needed repeatedly. For example, printing an
array of data, sorting the array, and searching for an item in the array.

Instead of rewriting the same code every time, you can create dedicated functions.
For instance:

 printArray() function handles printing the array.


 sortArray() function handles sorting.
 searchArray() function handles searching.
By using functions, you:
Avoid Redundancy: Write the logic once and reuse it as needed.
Simplify Maintenance: If a functionality changes, you only update the
function definition, and all calls automatically reflect the update.
Example:

If a company prints its tagline on every form:

 Without functions: You’d need to update every occurrence if the tagline


changes.
 With a printTagline() function, a single update applies universally, reducing
errors and ensuring consistency.

Make Code Modular


Functions make code modular, readable, and maintainable.

Example: You write a program, that takes a large amount of data, then process the
data and produces some useful data. To handle this thing you divide the whole
process into functions. Like:

 takeInputu(): To take input from users or somewhere.


 processData(): This function performs some operation of input data.
 produceOutput(): In this function, we simply return the data or result after
processing the data.
By creating separate functions for these tasks, you make the program more
understandable. Anyone reading the code can quickly grasp its structure and
functionality.

Abstraction
Functions provide abstraction by hiding implementation details. Library functions are
a prime example. For example:

 When using printf() to display output, you don’t need to understand its internal
workings.
 Sorting functions in libraries (like qsort in C) can be updated or optimized
without affecting your code.

Avoiding Variable Name Collisions


When everything is written in a single block of code, you may run out of unique
variable names. Functions help avoid this problem by introducing scope. Each function
has its local variables, meaning two functions can use the same variable name
without conflict.

Function declaration & definition


In C++, functions are essential tools that allow programmers to write reusable,
efficient, and organized code. To use functions effectively, it is important to
understand their declaration, definition, and usage. Let’s break this down step by
step.

Function Declaration
Just like variables need to be declared before they are used, functions in C++ must
also be declared to inform the compiler about their existence, the number and types
of parameters, and their return type.

A function declaration (also called a prototype) tells the compiler about the function’s
return type, name, and parameters without providing the implementation. It is
typically written before the main function or in a header file.

Example:

int getMax(int x, int y); // Declaration or Prototype

Here:

 int specifies the return type of the function.


 getMax is the name of the function.
 (int x, int y) specifies the parameter types. Note that parameter names are
optional in the declaration.

Example Program

#include <iostream>
using namespace std;

int getMax(int x, int y); // Declaration

int main() {
int a = 10, b = 20;
cout << getMax(a, b); // Using the function
return 0;
}

int getMax(int x, int y) { // Definition


if (x > y)
return x;
else
return y;
}
Output: 20
Importance of Declaration in C++

In C++, if you try to use a function before declaring or defining it, the compiler will
throw an error because it does not know the function’s signature.

 If a function is declared before its usage but not defined, a linker error will
occur during compilation.
 If a function is used without being declared or defined, a compiler error will
occur.

Types of Functions

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

In addition to creating your own functions, C++ provides numerous built-in functions
in libraries, such as those in the <cmath> header file. These functions are pre-
declared in the respective libraries and can be used after including the relevant
header.

Example:

#include <iostream>
#include <cmath> // Header file for math functions
using namespace std;

int main() {
double a = 2, b = 4;
cout << pow(a, b) << endl; // 2^4 = 16

double x = 100;
cout << log10(x) << endl; // log10(100) = 2

return 0;
}
Output:
16
2

Explanation:

 pow(a, b): Raises a to the power b.


 log10(x): Returns the base-10 logarithm of x.

How Library Functions Work

Library functions are efficient and tested. They are declared in header files
(e.g., <cmath> for mathematical functions). When you include a header file, its
function declarations are made available to the program. During linking, the compiler
matches the function calls with their definitions provided by the library.

Key Points to Remember

1. Function Declaration: Specifies the function’s name, parameters, and return


type. Optional in some cases if the function is defined before usage.
2. Function Definition: Provides the actual logic of the function.
3. Compiler and Linker Errors:
o Missing declaration: Compiler error.
o Missing definition: Linker error.
4. Library Functions: Use pre-declared and pre-defined functions to save time
and ensure reliability.

Default Arguments in C++


Default arguments are a feature in C++ that allows a function to be called without
explicitly providing values for some of its parameters. If no value is provided for a
parameter, the function automatically assigns it a pre-defined default value. Let’s
explore this concept in detail.

What Are Default Arguments?

Default arguments allow flexibility in function calls by assigning a default value to one
or more parameters during the function declaration or definition. If the caller does not
provide a value for these parameters, the default value is used.

Example:

#include <iostream>
using namespace std;

void printDetails(int id, string name = "NA", string address = "NA") {


cout << "Id is " << id << "\n";
cout << "Name is " << name << "\n";
cout << "Address is " << address << "\n";
}

int main() {
printDetails(101, "Sandeep", "Noida");
cout << "\n";
printDetails(201, "Shivam");
cout << "\n";
printDetails(301);
return 0;
}

Output:

Id is 101
Name is Sandeep
Address is Noida

Id is 201
Name is Shivam
Address is NA

Id is 301
Name is NA
Address is NA

In this example:

 The printDetails function has default values "NA" for


the name and address parameters.
 When all arguments are provided, the default values are ignored.
 If fewer arguments are provided, the remaining parameters take their default
values.

Rules for Using Default Arguments

1. Default Arguments Must Appear at the End

All default arguments must be declared after non-default arguments. This ensures
that the compiler can correctly assign values to parameters.

Incorrect Code:

void printDetails(string name = "NA", int id) { // Compiler error


cout << "Id is " << id << "\n";
cout << "Name is " << name << "\n";
}

Output: Compiler error.

Correct Code:

void printDetails(int id, string name = "NA") {


cout << "Id is " << id << "\n";
cout << "Name is " << name << "\n";
}

2. Default Values Can Be Provided in Declaration or Definition

You can specify default values in either the declaration or the definition of the
function, but not both.

Example:

#include <iostream>
using namespace std;

int sum(int a, int b, int c = 0, int d = 0); // Declaration with defaults


int main() {
cout << sum(10, 20, 30) << "\n"; // Output: 60
cout << sum(10, 5) << "\n"; // Output: 15
return 0;
}
int sum(int a, int b, int c, int d) { // Definition without defaults
return (a + b + c + d);
}
Output:

60
15

Key Point:
 If default arguments are provided in the declaration, they should not be
repeated in the definition.
 The preferred approach is to provide defaults in the declaration, as it helps with
documentation and readability.

Inline Functions in C++


Inline functions in C++ are a feature designed to optimize program execution by
reducing the overhead associated with function calls. By suggesting the compiler to
replace a function call with the actual code of the function, inline functions can help
improve performance, especially for small, frequently used functions.

What Are Inline Functions?

An inline function is a special type of function where the compiler attempts to replace
the function call with the function’s body during compilation. This avoids the overhead
of function calls, such as parameter passing, stack operations, and returning values.

Syntax:

To make a function inline, use the inline keyword before the function definition.

Example:
#include <iostream>
using namespace std;

inline int getMax(int x, int y) {


return (x > y) ? x : y;
}

int main() {
cout << getMax(10, 20); // Output: 20
return 0;
}

In this example:

 The getMax function is defined as inline.


 During compilation, the compiler replaces getMax(10, 20) with (10 > 20) ? 10 :
20 to avoid the function call overhead.

Why Use Inline Functions?

1. Optimization for Small Functions For small functions, the overhead of


function calls can be significant compared to the actual execution of the
function body. Inline functions eliminate this overhead by directly placing the
function code at the call site.
2. Improves Execution Speed By avoiding function calls, inline functions can
improve the execution speed of the program, especially when the function is
called multiple times in performance-critical sections.

Inline Functions vs. Macros

Inline functions are often compared to macros because both can replace code at the
call site. However, inline functions have significant advantages over macros:

1. Type Checking Inline functions perform type checking, while macros do not.
This makes inline functions safer and less error-prone.
2. Scope and Syntax Inline functions follow the same scoping rules as regular
functions, whereas macros are simple text replacements that can lead to
unexpected behavior if not written carefully.
3. Example Comparison:
4. #define add(x, y) x + y
5.
6. int main() {
7. cout << 4 * add(10, 20); // Output: 60 (Unexpected result due to lack of parentheses)
8. return 0;
9. }

10.
5. Here, the macro expands to 4 * 10 + 20, which evaluates as 40 + 20 =
60 instead of the expected 4 * (10 + 20) = 120. This issue does not occur with
inline functions.

Important Facts About Inline Functions


1. Compiler's Choice Declaring a function as inline is merely a suggestion to the
compiler. The compiler may decide not to inline the function if the function body
is too large or if inlining would increase the program size significantly.
2. Binary File Size Overusing inline functions in large programs can increase the
size of the binary executable because the function code is copied at every call
site.
3. Inline Functions in Classes When you define a function inside a class, it is
automatically considered an inline function.
4. Modern Compiler Behavior Modern compilers may inline some functions even
if they are not explicitly marked as inline. Conversely, they may ignore
the inline keyword for functions that are unsuitable for inlining.
Inline functions in C++ are a powerful optimization tool that can enhance
performance by eliminating the overhead of function calls. However, they should be
used judiciously to balance the benefits of reduced call overhead with potential
increases in binary size. Inline functions also provide safer and more predictable
behavior compared to macros, making them a preferred choice for developers.

Function Overloading
Function overloading is a concept in C++ that allows multiple functions with the same
name but different parameter lists. It enhances code readability and reusability,
enabling developers to use the same name for functions performing similar tasks with
different types or numbers of parameters.

What is Function Overloading?

Function overloading allows defining multiple versions of a function where


the number or type of parameters differs. When you invoke a function, the compiler
determines which version to execute based on the arguments passed. This feature
eliminates the need for unique function names, making the code more intuitive and
manageable.

Example 1

#include <iostream>
using namespace std;

// Function to find the maximum of two integers


int myMax(int x, int y) {
return (x > y) ? x : y; // Ternary operator to find the maximum
}

// Function to find the maximum of three integers


int myMax(int x, int y, int z) {
return myMax(myMax(x, y), z); // Compare maximum of x and y with z
}

int main() {
int a = 10, b = 30, c = 5;

// Call to the two-parameter version of myMax


cout << myMax(a, b) << "\n";
// Call to the three-parameter version of myMax
cout << myMax(a, b, c) << "\n";

return 0;
}
Output:

30
30

Explanation
1. myMax(int x, int y): This function takes two integers and returns the larger
value using the ternary operator.
2. myMax(int x, int y, int z) : This function calculates the maximum of three
integers by first finding the maximum of x and y using myMax(int x, int y) and
then comparing the result with z.
3. In main(): The appropriate function is invoked based on the number of
arguments passed:
o Passing two integers calls the two-parameter version.
o Passing three integers calls the three-parameter version.
Example 2

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

// Function to print a string


void print(string s) {
cout << s << "\n";
}

// Function to print an integer


void print(int x) {
cout << x << "\n";
}

// Function to print a character


void print(char c) {
cout << c << "\n";
}

int main() {
print('a'); // Calls the print(char) function
print(10); // Calls the print(int) function
print("GfG"); // Calls the print(string) function

return 0;
}
Output:

a
10
GfG

Explanation
1. print(string s): Prints the input string.
2. print(int x): Prints the input integer.
3. print(char c): Prints the input character.
4. In main():
o The compiler determines the function to call based on the type of the
argument:
 'a' calls print(char c).
 10 calls print(int x).
 "Hello, World!" (C-style string) automatically converts to
a std::string and calls print(string s).

Handling Implicit Type Conversion

If the print(char c) function is removed, calling print('a') will invoke print(int x) because
a char can be implicitly converted to an int. The ASCII value of 'a' (97) will be printed
instead of the character.

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

void print(string s) {
cout <<s << "\n";
}

void print(int x) {
cout << x << "\n";
}

int main() {
print('a'); // 'a' is implicitly converted to int, printing ASCII value
print(10);
print("GfG");

return 0;
}
Output:

97
10
GfG

Important Notes About Function Overloading

1. Parameters Must Differ: Overloading relies on differences in parameter types


or counts. Functions cannot be overloaded based solely on the return type.
2. void print(int x);
3. int print(int x); // Error: Functions cannot differ only in return type.

4.
3. Automatic Type Conversion: If no exact match is found, the compiler
performs implicit type conversion to find the best match.
4. Templates vs. Overloading:
o Use function overloading when logic differs for each implementation.
o Use templates when logic remains the same but supports different data
types. For instance, sorting integers, floats, or strings using the same
algorithm.

Default Arguments in Function Overloading

Default arguments are parameters with predefined values. If a value for the
parameter is not provided during the function call, the default value is used. While
default arguments enhance function flexibility, they may introduce ambiguity when
multiple overloaded functions exist.

Example of Ambiguity in Function Overloading

#include <iostream>
using namespace std;

// Function with a default argument


void print(int x = 0) {
cout << x << "\n";
}

// Overloaded function with no arguments


void print() {
cout << "No arguments" << "\n";
}

int main() {
print(); // Ambiguous call
return 0;
}

Explanation
1. print(int x = 0): This function accepts an integer parameter with a default
value of 0. If no argument is provided during the function call, the value 0 is
used.
2. print(): This overloaded function takes no arguments and prints a fixed
message.
3. Function Call in main():
o The call to print() is ambiguous because both functions are potential
matches:
 The first function can be called with the default value 0.
 The second function can also be called, as it explicitly takes no
arguments.
o The compiler cannot decide which function to invoke, resulting in an error.

Practice Problems on C++ Functions


Problem 1: Undefined Function Call
#include <iostream>
using namespace std;

void fun(int, string="NA");


int main() {
fun(101);
return 0;
}

void fun(int id, string name ) {


cout << id << " " << name;
}

Output
101 NA

Key Points:

 Initially, this program caused a linker error because the function fun was called
before being declared.
 The issue was resolved by declaring the function prototype before main.
 The output of this program is 101 NA because the name parameter uses the
default value "NA."
 Best Practice: Default arguments should be specified in the function
declaration, not in the definition, although the compiler allows it.

Problem 2: Static vs. Local Variables


#include <iostream>
using namespace std;

void fun() {
static int x = 1;
int y = 1;
x++;
y++;
cout << x << " " << y << endl;
}

int main() {
fun();
fun();
fun();
return 0;
}

Output
22
32
42

Key Points:

 x is a static variable, so its value persists across function calls.


 y is a local variable, so it is reinitialized each time the function is called.
 Execution:
o First call: x = 2, y = 2 (incremented from their initial values).
o Second call: x = 3, y = 2 (static x retains its value, but y is reinitialized).
o Third call: x = 4, y = 2.

Problem 3: Compiler-Dependent Evaluation Order


#include <iostream>
using namespace std;

void fun(int x, int y, int z) {


cout << x << " " << y << " " << z;
}

int main() {
int i = 2;
fun(++i, ++i, ++i);
return 0;
}

Output
555

Key Points:

 The output of this program is compiler-dependent due to the order of evaluation


of function arguments.
 The standard does not define whether arguments are evaluated from left to
right or right to left.
 Example outcomes:
o If evaluated left to right: x = 3, y = 4, z = 5.
o If evaluated right to left: x = 5, y = 4, z = 3.
 Best Practice: Avoid writing such code to ensure predictable behavior.

Problem 4: Recursive Function Example


#include <iostream>
using namespace std;

void fun(int x) {
if (x == 0)
return;
else {
cout << "gfg\n";
fun(x - 1);
}
}

int main() {
fun(3);
return 0;
}

Output
gfg
gfg
gfg

Key Points:

 The function fun is recursive and calls itself until the base case ( x == 0) is met.
 Execution flow:
1. fun(3) prints "gfg" and calls fun(2).
2. fun(2) prints "gfg" and calls fun(1).
3. fun(1) prints "gfg" and calls fun(0).
4. fun(0) meets the base case and returns.

Problem 5: Infinite Recursion


#include <iostream>
using namespace std;

int main() {
cout << "gfg";
main();
return 0;
}
Key Points:

 This program makes the main function call itself recursively, leading to infinite
recursion.
 There is no base case to terminate the recursion.
 Outcome:
o It keeps printing "gfg" until the stack overflows, causing a runtime error
(segmentation fault).

First Digit of a Number


Understanding the first digit of a number can be useful in various computational
problems. For instance, if you are working with large numbers and need to analyze or
manipulate their leading digits, the approach we'll discuss can come in handy.

What is the First Digit of a Number?

The first digit of a number is simply the leftmost digit in the number. For example:

 The first digit of 9768 is 9.


 The first digit of 763 is 7.
The key idea is to isolate the leftmost digit by dividing the number repeatedly by 10
until it becomes a single-digit number.

Approach to Solve the Problem

To determine the first digit of a number, the following steps are used:

1. Iterative Division by 10:


o Continuously divide the number by 10 until it becomes less than 10.
o At this point, the number is reduced to a single digit, which is the first
digit.
For example:

 Starting with 9768:


o Divide by 10 → 976.
o Divide by 10 → 97.
o Divide by 10 → 9 (stops here as it's <10).
Code Implementation

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

// Function to find the first digit of a number


int find_first_digit(int n) {
while (n >= 10) { // Loop until the number becomes a single digit
n = n / 10;
}
return n; // Return the single-digit number
}

int main() {
int n;
cin >> n; // Input the number
cout << find_first_digit(n); // Print the first digit
return 0;
}

Explanation of the Code:

1. Input Handling:
o The main() function reads an integer n as input from the user.
2. Function find_first_digit:
o A while loop is used to repeatedly divide n by 10.
o The condition n >= 10 ensures the loop continues until n becomes a
single-digit number.
3. Returning the Result:
o Once the loop ends, the single-digit number is returned as the first digit of
the input.
4. Output:
o The main() function prints the result returned by
the find_first_digit function.
Prime Factorization
Prime factorization is a mathematical process used to express a given number as a
product of its prime factors. This is a fundamental concept in mathematics and
computer science, widely used in number theory and cryptography.

What is Prime Factorization?

Prime factorization is the representation of a number as a product of prime numbers.


For example:

 The prime factorization of 50 is 2×5×5.


 The prime factorization of 20 is 2×2×5.
 For a prime number such as 13, the prime factorization is just 13.

Approach to Solve the Problem

To perform prime factorization of a number n, we follow these steps:

1. Start iterating from 2 (the smallest prime number) to n.


2. For each number i, check:
o If i is a prime number.
o If n is divisible by i.
3. If i satisfies both conditions, it is a prime factor of n. Print it and continue
dividing n by i until n is no longer divisible by i.
4. Move to the next number.
#include <iostream>
using namespace std;

// Function to check if a number is prime


bool isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false; // Return false if n is divisible by any number other than 1 and itself
}
}
return true; // Return true if n has no divisors other than 1 and itself
}

// Function to perform prime factorization


void primeFactors(int n) {
for (int i = 2; i <= n; i++) {
if (isPrime(i)) { // Check if i is prime
int x = i;
while (n % x == 0) { // Check if n is divisible by x
cout << i << " "; // Print the prime factor
x = x * i; // Multiply x by i to handle repeated factors
}
}
}
}

int main() {
int n;
cout << "Enter a number: ";
cin >> n; // Input the number to be factorized
primeFactors(n); // Call the prime factorization function
return 0;
}

Explanation of the Code

1. isPrime Function:
o This function checks if a given number n is prime by iterating from 2 to
n−1.
o If n is divisible by any number in this range, it is not a prime number.
2. primeFactors Function:
o This function iterates through all numbers from 2 to n.
o For each number i, it checks:
 If i is a prime number.
 If n is divisible by i.
o If both conditions are satisfied, i is printed as a prime factor.
o The function handles repeated factors (e.g., 2×2) by repeatedly dividing n
by i until n is no longer divisible by i.
3. main Function:
o Accepts the input n from the user.
o Calls the primeFactors function to compute and print the prime factors of
n.

Introduction to Arrays in 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++ 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++ 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.

Array declaration in C++


Array declaration in C++ is same as 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

#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;
}
Array declaration by initializing elements

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

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

Accessing Array Elements in 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.Its same as C language.
 The name of the array is also a pointer to the first element of the array.

Basics of Accessing Array Elements

An array's elements can be accessed using their indices. In C++, array indices start
from 0 and go up to size - 1.

Example 1: Accessing and Modifying Elements


#include <iostream>
using namespace std;

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

// Accessing elements
cout << arr[2] << " " << arr[0] << "\n"; // Output: 30 10

// Modifying elements
arr[2] = 50;
cout << arr[2] << "\n"; // Output: 50

return 0;
}

Output:

30 10
50

Explanation:

 The array arr has four elements.


 Accessing arr[2] fetches the third element, which is 30.
 Modifying arr[2] to 50 updates the array, and subsequent accesses
to arr[2] reflect this change.

How Does Array Indexing Work?

Array indexing works by using the address of the first element and adding an offset
based on the index. The size of the data type determines the offset.

Example 2: Understanding Indexing Internals

#include <iostream>
using namespace std;

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

// Prints the address of the first element


cout << arr << "\n";

// Accessing the third element


cout << arr[2] << "\n"; // Output: 30

return 0;
}
Output:

0x7fff89aa1610
30

Explanation:

 arr points to the address of the first element in memory.


 To access arr[2], the compiler calculates the address as:
Address of arr[2] = Address of arr[0] + (2 * sizeof(int))
 For a 4-byte integer, this would result in an address offset of 8 bytes from arr[0].

Out-of-Bounds Access in C++

In C++, there is no automatic out-of-bounds checking for arrays. Accessing an index


beyond the array size leads to undefined behavior.

Example 3: Out-of-Bounds Access


#include <iostream>
using namespace std;

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

// Accessing an out-of-bounds index


cout << arr[5] << "\n"; // Undefined behavior

return 0;
}
Explanation:

Accessing arr[5] is invalid as the array has only four elements.


The compiler does not prevent this, but the output could be random or lead to a
segmentation fault.
Key Takeaway: Always ensure that the indices used are within valid bounds.

Uninitialized Elements in Arrays

If an array is partially initialized, the uninitialized elements are set to 0 for statically
allocated arrays.

Example 4: Partially Initialized Array


#include <iostream>
using namespace std;

int main() {
int arr[4] = {10, 20};

// Accessing an uninitialized element


cout << arr[2] << "\n"; // Output: 0

return 0;
}
Output:

Explanation:

 Only the first two elements are explicitly initialized.


 The remaining elements are automatically set to 0.

Summary

1. Indexing: Array elements are accessed using indices starting from 0 to size - 1.
2. Memory Calculation: Indexing internally calculates the memory address
based on the element size.
3. No Bounds Checking: C++ does not provide automatic checks for out-of-
bounds access, leading to potential undefined behavior.
4. Uninitialized Elements: Statically declared arrays have uninitialized elements
set to 0 if partially initialized.

Array Traversal in C++


Array traversal is a fundamental operation in programming, allowing you to access,
process, or modify each element of an array. This article discusses different methods
of array traversal in C++, how to modify array elements during traversal, and the
nuances of both methods.

1. Using Normal Loops


A common way to traverse arrays in C++ is by using traditional for loops. This method
requires knowing the size of the array, which can be calculated using
the sizeof operator.

Code Example:

#include <iostream>
using namespace std;

int main() {
int arr[] = {10, 40, 30, 45};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate number of elements

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


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

return 0;
}
Output:

10 40 30 45

Explanation:

 The sizeof(arr) gives the total size of the array in bytes.


 sizeof(arr[0]) gives the size of a single element.
 Dividing the two calculates the number of elements in the array.
 A for loop iterates through indices from 0 to n-1, accessing elements using arr[i].

2. Using Range-Based for Loop

The range-based for loop simplifies array traversal by eliminating the need to
calculate the size of the array. It directly iterates over elements, making the code
cleaner and easier to write.

Code Example:

#include <iostream>
using namespace std;

int main() {
int arr[] = {10, 40, 30, 45};

for (int x : arr) {


cout << x << " ";
}

return 0;
}
Output:

10 40 30 45

Explanation:

 The loop variable x takes the value of each element in the array, one by one.
 The syntax for (int x : arr) automatically traverses all elements without needing
explicit size calculation.

3. Modifying Array Elements During Traversal

You can modify array elements during traversal. This can be done using either a
normal loop or a range-based for loop with a reference variable.

Code Examples:

Using Normal Loop:

#include <iostream>
using namespace std;

int main() {
int arr[] = {10, 40, 30};
int n = sizeof(arr) / sizeof(arr[0]);

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


arr[i] *= 2; // Modify each element to its double
}

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


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

return 0;
}

Using Range-Based Loop:

#include <iostream>
using namespace std;

int main() {
int arr[] = {10, 40, 30};

for (int &x : arr) { // Use reference (&) to avoid copying


x *= 2; // Modify each element
}

for (int x : arr) {


cout << x << " ";
}

return 0;
}
Key Points:

 In the normal loop, elements are accessed using their index.


 In the range-based loop, the reference ( &) ensures modifications are applied
directly to the original array elements rather than a copy.
Different Types of Arrays in C++
Arrays in C++ can be classified based on their size management: fixed-size
arrays and dynamic-size arrays. Understanding the distinctions between these
types helps programmers choose the right approach depending on the use case.
Below, we'll explore these arrays in detail.

1. Fixed-Size Arrays

Fixed-size arrays have a pre-defined size that remains constant throughout the
program. Once the size is decided, it cannot be altered. These arrays are memory-
efficient in specific scenarios but can lead to wastage if the allocated size exceeds
actual requirements.

Examples of Fixed-Size Arrays:

1. Local Arrays (Function Call Stack):Syntax Example:

 Created within a function and stored in the function call stack.


 Temporary in nature; their memory is automatically released once the function
execution completes.
 Commonly initialized using constants, user inputs, or variable values.
Syntax Example:

int arr[10]; // Fixed-size array of 10 elements


int n = 5;
int arr2[n]; // Variable size determined at runtime

2. Heap-Allocated Fixed-Size Arrays:

 Allocated in the heap memory using pointers.


 Memory persists even after the function execution, as long as the pointer is
valid.
 Provides flexibility to manage memory beyond the scope of a single function.
Syntax Example:

int* arr = new int[10]; // Dynamically allocated fixed-size array


delete[] arr; // Manually deallocate memory

2. Dynamic-Size Arrays

Dynamic-size arrays can grow or shrink during runtime. This makes them highly
flexible and efficient, especially in scenarios where the exact size of data is unknown
beforehand.

Advantages:

Flexible Memory Usage: Adapts to the required size without wasting memory.
Space Efficiency: Avoids over-allocation compared to fixed-size arrays.
Ease of Use: Automatic resizing saves time and reduces complexity.
Examples of Dynamic Arrays:

1. Vectors in C++ (STL):Syntax Example:

 A part of the Standard Template Library (STL).


 Automatically manages memory by resizing itself as elements are added or
removed.
Syntax Example:

#include <vector>
std::vector<int> vec; // Declare an empty dynamic array
vec.push_back(10); // Add an element
vec.pop_back(); // Remove an element

2. Dynamic Arrays Using Pointers:

 Offers manual control over memory allocation and deallocation.


 Useful when precise memory management is required.
Syntax Example:

int* arr;
int size = 10;
arr = new int[size]; // Allocate memory
// Modify elements
delete[] arr; // Deallocate memory

References in C++
A reference in C++ is a variable that acts as an alias for another variable. It is
created by using the ampersand (&) symbol during declaration. Once a reference is
initialized, it cannot be changed to refer to another variable.

Key Properties of References:

1. Must Be Initialized: A reference must be assigned a valid variable at the time


of declaration.
2. Cannot Be NULL: References cannot hold NULL values; they must always refer
to a valid variable.
3. Cannot Be Changed: After initialization, a reference cannot be made to refer
to a different variable.

Syntax of References
int x = 10; // Original variable
int &ref = x; // Reference variable pointing to 'x'

In this example:

 ref is a reference to x. Any changes made to ref will directly affect the value
of x and vice versa.
Below is the code provided for demonstrating references:

#include<iostream>
using namespace std;
int main()
{
int x = 10;
int &y = x;
cout << y << ' '; // Print value of 'y' (10, because it refers to 'x')

x += 5; // Modify 'x'
cout << y << ' '; // Print value of 'y' (15, because it still refers to 'x')

y += 5; // Modify 'y'
cout << x << ' '; // Print value of 'x' (20, because 'y' modifies 'x')

return 0;
}

Output:
10 15 20
x and y refer to the same memory location.

Any changes made to either x or y will affect the other.

Memory layout:

Variab Memory Valu


le Address e

x 0x123 20

y 0x123 20

Function Parameters & References


In C++, function parameters are variables that are used to pass data into a function
when it is called. Function parameters are defined in the function's declaration and
are used to receive the data that is passed to the function when it is called.

Function parameters can be either pass-by-value or pass-by-reference. Pass-by-value


means that the function receives a copy of the data that is passed to it, while pass-by-
reference means that the function receives a reference to the original data.

Issues with Passing by Value


When variables are passed to functions by value, the function works on a copy of the
variable, not the original. This approach has two major limitations:

1. Changes Are Not Reflected Outside the Function

 Any modifications made to the variable inside the function are not visible
outside it. This is because the function operates on a copy of the variable.
 Example:
void fun1(int x) {
x += 2;
}
int main() {
int x = 2;

fun1(x); // 'x' remains unchanged

cout << x;
// Output: 2
}

2. Performance Issues with Large Data Structures

 When large objects (e.g., strings, arrays, or custom data structures) are passed
by value, the entire object is copied. This can lead to significant memory and
time overhead.
 Example:
void fun(string s) {
// Operates on a copy of the string 's'
cout << s;
}

Solving Issues with References


Passing by reference allows a function to operate directly on the original variable.
This is done by declaring the parameter with an ampersand (&).

Changes Are Reflected Outside the Function

 The function works directly with the original variable, so any modifications are
visible outside.
#include<iostream>
using namespace std;

void fun1 (int x)


{
x += 2;
}
void fun2 (int &x)
{
x += 2;
}
int main()
{
int x = 2;
fun1(x);
cout << x << ' ';
fun2(x);
cout << x;
return 0;
}
Output:
24

Passing parameters by reference can be more efficient than pass-by-value because it


avoids the overhead of creating and copying the data. However, it is important to be
careful when using pass-by-reference, as it can lead to unintended side effects if the
function modifies the original data.

Performance issue:

The const keyword is often used with references to indicate that the function should
not modify the variable being referred to. This is especially useful when working with
large objects (like strings or data structures) that are passed by reference for
performance reasons, but the function should only read the data, not change it.

Code Example: Using const Reference


#include<iostream>
using namespace std;

void fun(const string &s) { // 's' is a constant reference


cout << s; // Only allowed to read 's', not modify it
}

int main() {
string s = "geeksforgeeks course";
fun(s);
return 0;
}

Output:
geeksforgeeks course

Range Based for Loop


The range-based for loop in C++ provides a simpler and more elegant way to iterate
over collections like arrays, vectors, or other containers. When combined with
references, it becomes even more powerful, addressing issues like element
modification and performance.

Syntax :

for (data_type variable : collection) {


// Code to execute for each element
}
 data_type: The type of the elements in the collection.
 variable: A variable to hold each element during iteration.
 collection: The array or container to iterate over.
Example Without References
#include<iostream>
using namespace std;

int main() {
int arr[] = {10, 20, 30};
for (int x : arr) { // 'x' is a copy of each element
x += 2; // Modifies the copy, not the original array
}
for (int x : arr) {
cout << x << " "; // Original array remains unchanged
}
return 0;
}

Output:
10 20 30

Problems with Normal Loop Variables

1. Cannot Change Elements:


o The loop variable (x) is a copy of each element.
o Any modifications to x do not affect the original array.
2. Performance Issues:
o For large objects (e.g., strings or vectors), copying each element can be
computationally expensive.

Solving Problems with References


By using references (&) in the loop, we can iterate directly over the elements of the
collection, avoiding unnecessary copying and allowing modifications to the original
elements.

Example With References


#include<iostream>
using namespace std;

int main() {
int arr[] = {10, 20, 30};
for (int &x : arr) {
x += 2; // Modifies the original array
}
for (int x : arr) {
cout << x << " ";
}
return 0;
}

Output:
12 22 32

Combining const with References


If the goal is only to read the elements without modifying them, you can
use const references. This ensures the safety of the data while avoiding the cost of
copying.

Example:
#include<iostream>
using namespace std;

int main() {
string arr[] = {"GFG", "C++ Course", "learning"};
for (const string &s : arr) { // 's' is a const reference
cout << s << "\n";
}
return 0;
}

Output:
GFG
C++ Course
learning

Const & R Value References


C++ references provide an efficient way to manipulate data. However, the distinction
between L-value references, R-value references, and the use of
the const keyword introduces more flexibility, especially for temporary objects or
immutable data.

In C++, you can use the const keyword to declare a reference that cannot be
modified, and you can use the && operator to declare an rvalue reference, which is a
reference to a temporary object that will be destroyed after the reference goes out of
scope.

What Are L-Values and R-Values?


 L-Values: Objects that persist beyond a single expression, such as variables or
references. You can take their address using the & operator.
int x = 10; // 'x' is an L-value
 R-Values: Temporary objects or literals that exist only during the evaluation of
an expression and cannot be referenced directly. They cannot have their
address taken.

int x = 10 + 20; // '10 + 20' is an R-value

const References
Problem with Regular References:
Regular references cannot bind to R-values, meaning you cannot reference temporary
objects directly. (e.g., literals or temporary objects):

int &x = 3; // Invalid: '3' is an R-value

Solution: Use const References

A const reference allows binding to both L-values and R-values. It ensures the
referenced object is immutable within the scope of the reference.

Example:
#include<iostream>
using namespace std;

void print(const string &s) { // 's' can bind to temporary strings


cout << s << '\n';
}

int main() {
print("Welcome to GeeksforGeeks"); // Valid: temporary string bound to 's'
return 0;
}
Output:

Welcome to GeeksforGeeks

Key Points:

 const string &s prevents modifications to the string s inside the print function.
 const references are useful for read-only access to large objects or temporary R-
values.

R-Value References (&&)


R-value references, denoted by &&, allow functions to modify temporary objects (R-
values). They provide a way to work with temporary data without unnecessary copies.

#include<iostream>
using namespace std;

void editAndPrint(string &&s) { // 's' is an R-value reference


s = "Hi, " + s; // Modifies the temporary string
cout << s << "\n";
}

int main() {
editAndPrint("Welcome to GeeksforGeeks");
return 0;
}

Output:
Hi, Welcome to GeeksforGeeks
Explanation:

 "Welcome to GeeksforGeeks" is an R-value.


 editAndPrint modifies the temporary string and avoids copying the data.

References Practice Questions in C++


Approach to solving questions involving
References in C++
When solving coding questions related to references in C++, there are a few key
things to keep in mind:

 Understand the difference between references and pointers. A reference is an


alias for an existing variable, whereas a pointer holds the memory address of a
variable.
 Remember that once a reference is initialized, it cannot be made to refer to a
different object.
 Be aware of the advantages and disadvantages of using references. For
example, references can improve code readability and make it easier to work
with large or complex data structures. However, they also can also make your
code more difficult to understand if used improperly.
 Pay attention to the problem statement and constraints. Make sure you
understand the requirements of the problem and how references can be used to
solve it.
 Write clear, readable, and well-commented code. This will help you and others
understand the logic behind your solution, and make it easier to debug if
necessary.
 Test your code thoroughly before submitting, using sample inputs as well as
edge cases. This will help you catch any bugs or errors that you might have
missed during the development process.

Question 1: Reference Assignment


#include<iostream>
using namespace std;

int main()
{
int x = 10, y = 20;
int &z = x;
z = y;
z =z + 5;
cout << x << ' ' << y << ' ' << z;
return 0;
}

Explanation:
1. Reference Declaration:
o int &z = x; declares z as a reference to x. This means that z and x refer to
the same memory location.
2. Assignment:
o z = y; assigns the value of y (which is 20) to z, and since z is a reference
to x, x now also becomes 20.
3. Modification:
o z += 5; modifies z, which is a reference to x, so x becomes 25 (20 + 5).

Output:
25 20 25

Question 2: Returning a Reference from a Function


#include<iostream>
using namespace std;

int &fun()
{
static int x = 10;
return x;
}

int main()
{
int &y = fun();
y = 20;
cout << fun();
return 0;
}
Explanation:

1. Static Variable:
o static int x = 10; ensures that x retains its value even after
the fun() function exits. If x were not static, returning a reference to a local
variable would result in undefined behavior, as the variable would go out
of scope after the function returns.
2. Returning a Reference:
o return x; returns a reference to x. Since x is static, the reference is valid
even after the function call completes.
3. Main Function:
o int &y = fun(); assigns a reference y to the value returned by fun().
Modifying y modifies x directly.
o y = 20; assigns the value 20 to x through y.
o cout << fun(); prints the modified value of x, which is now 20.

Output:
20

Question 3: R-Value References


#include<iostream>
using namespace std;
int main()
{
string s1 = "GFG ", s2 = "Courses";
string &&s3 = s1 + s2;
s3 = "Welcome to " + s3;
cout << s3 << endl;
return 0;
}

Explanation:

1. R-Value Reference:
o string &&s3 = s1 + s2; declares s3 as an r-value reference. s1 + s2 is a
temporary string, and s3 is bound to this temporary object. R-value
references allow us to modify temporary objects directly.
2. Modifying R-Value:
o s3 = "Welcome to " + s3; modifies the temporary string s3. Since s3 is an r-
value reference, this is allowed.
o The concatenation results in the string "Welcome to GFG Courses".
3. Output:
o cout << s3 << endl; prints the modified string s3.

Output:
Welcome to GFG Courses

You might also like