C++ Notes
C++ Notes
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.
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.
COMPILER VS INTERPRETER
COMPILER INTERPRETER
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.
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.
Each programming language has its own rules to define what is allowed and what
isn’t. For example:
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.
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.
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.
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++ 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.
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.
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).
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.
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:
Output:
GeeksforGeeks
Let us now understand every line and the terminologies of the above program:
1. #include <iostream>
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.
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
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++
Example:
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
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:
Variables in C++
Variables in C++ is a name given to a memory location. It is the basic unit of storage
in a program.
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.
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. 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
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
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
Primitive data types are predefined by the C++ language and include the following
categories:
a. Integer Types
b. Character Types
c. Floating-Point Types
Used to store decimal or fractional numbers.
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:
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 ;
}
Sandeep
39
M
1
68.5
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.
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 (expression)
Here:
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
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
1. Local Variables
2. Global Variables
Local Variables - Variables defined within a function or block are said to be local to
those functions.
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.
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.
#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.
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.
int main()
{
cout << x; // Error: x is not declared yet
return 0;
}
int x = 10;
extern int x;
int main()
{
cout << x;
return 0;
}
int x = 10;
Output:
10
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 (::).
10
int x = 20;
int main()
{
int x = 10;
{
int x = 30;
cout << x;
}
return 0;
}
Output:
30
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)
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.
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.
Constants are particularly useful in real-world applications where certain values must
remain unchanged. For example:
#include <iostream>
using namespace std;
int main() {
int r;
cout << "Enter the radius of the circle: ";
cin >> r;
cout << "Area of the circle is: " << PI * r * r;
return 0;
}
Before the introduction of const, the #define preprocessor directive was commonly
used to define constants.
#define var 5
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;
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.
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.
#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
Output:
5 10.5
id
Explanation:
Advantages
2. If a function returns auto, its return type can be changed without worrying about
prototype change.
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.
Example:
56, 78
Example:
Example:
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() {
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
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
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)
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;
return 0;
}
Output
isTrue? 1
isFalse? 0
#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.
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;
}
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
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.
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>
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:
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>
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.
#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.
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;
Explanation:
Variable Declarations and Initialisation:
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;
return 0;
}
Input
18
Output
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.
// Driver Code
int main()
{
string name;
int age;
// Print output
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;
return 0;
}
Input:
ABC
10
Output:
Name : ABC
Age : 10
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;
return 0;
}
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.
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.
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;
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.
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:
cout<<”\nWelcome”;
Welcome
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:
Example -
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.
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::noboolalpha: Reverts the formatting back to printing 1 for true and 0 for false.
#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:
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).
#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::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).
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:
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:
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:
#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
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.
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.
By default, only negative numbers are shown with a sign ( -). The showpos() function
explicitly displays the + sign for positive numbers, while noshowpos() disables it.
#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
1. Default Format
2. Fixed Format
Example:
For a precision of 6:
3. Scientific Format
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:
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.
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
Arithmetic Operators
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:
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
int c = a%b; // c
=2
Note: The Modulo operator(%) operator should only be used with integers.
Example:
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
int main()
{
int a = 6, b = 4;
// Logical OR operator
cout << "a || b is " << (a || b) << endl;
return 0;
}
Output
a && b is 1
a ! b is 1
!b is 0
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)
“-=”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)
“*=”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)
“/=”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)
#include <iostream>
using namespace std;
int main()
{
// Assigning value 10 to a
// using "=" operator
int 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.
1. Greater than (>) : Checks if the left operand is greater than the right operand.
Example:
2. Greater than or equal to ( >=): Checks if the left operand is greater than or
equal to the right operand.
Example:
3. Less than (<): Checks if the left operand is less than the right operand.
Example:
Example:
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
#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
10 + 20 * 30
10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30
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
4) Comma has the least precedence among all operators and should be used
carefully
int main() {
// evaluates 17 * 6 first
int num1 = 5 - 17 * 6;
return 0;
}
Output
num1 = -97
num2 = -97
num3 = -72
// a -= 6 is evaluated first
b += a -= 6;
Output
a = -5
b = -1
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
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.
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:
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:
Adding two's complement numbers (positive or negative) uses the same logic as
adding positive numbers in binary.
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
//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.
int main() {
int x = 3; // Binary: 0011
int y = 6; // Binary: 0110
3 in binary: 0011
6 in binary: 0110
AND: 0010
Output: 2
int main() {
int x = 3; // Binary: 0011
int y = 6; // Binary: 0110
3 in binary: 0011
6 in binary: 0110
OR: 0111
Output: 7
int main() {
int x = 3; // Binary: 0011
int y = 6; // Binary: 0110
3 in binary: 0011
6 in binary: 0110
XOR: 0101
Output: 5
int main() {
int x = 3; // Binary: 0000...0011
cout << (x << 1) << endl; // Shift left by 1
cout << (x << 2) << endl; // Shift left by 2
return 0;
}
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
int main() {
int x = 33; // Binary: 0000...100001
cout << (x >> 1) << endl; // Shift right by 1
cout << (x >> 2) << endl; // Shift right by 2
return 0;
}
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.
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;
}
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.
Problem Description
Solution Steps
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
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.
Problem Statement
Given an integer, the task is to find its last digit. For instance:
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
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).
Where:
Example
Code Implementation
#include <bits/stdc++.h>
using namespace std;
int main() {
// Starting number
int a = 2;
// Common difference
int d = 1;
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.
In a Geometric Progression, the Nth term can be calculated using the formula:
TN=A×R(N−1)
Where:
Example
Code Implementation
#include <bits/stdc++.h>
using namespace std;
// Common ratio
int r = 3;
return 0;
}
Output: 18
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
}
#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;
}
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:
Odd
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:
Input 1:
Enter a number: 5
Output:
Positive
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
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;
}
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;
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,
3) The default statement is optional. Even if the switch case statement do not
have a default statement,
it would run without any problem.
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:
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;
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.
Loops have a wide range of applications in programming. Some common use cases
include:
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.
int main() {
int i = 0;
while (i < 5) {
cout << "GfG\n";
i++;
}
return 0;
}
Output:
GfG
GfG
GfG
GfG
GfG
Execution Flow
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.
Syntax:
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.
int main() {
for (int i = 0; i < 3; i++) {
cout << "GfG\n";
}
return 0;
}
Explanation:
Output:
GfG
GfG
GfG
Output:
GfG 0
GfG 1
GfG 2
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.
int main() {
for (int i = 1; i <= 10; i += 2) {
cout << "GfG\n";
}
return 0;
}
Explanation:
GfG
GfG
GfG
GfG
GfG
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.
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.
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);
#include <iostream>
using namespace std;
int main() {
int i = 3;
do {
cout << "GfG\n";
i++;
} while (i < 3);
return 0;
}
Explanation:
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. 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.
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
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
#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:
Input: n = 6
Output:
Smallest Divisor: 2
Input: n = 49
Output:
Smallest Divisor: 7
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
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:
Input: n = 10, x = 3
Output:
1 2 4 5 7 8 10
Input: n = 7, x = 5
Output:
123467
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.
while(condition)
{
while(condition)
{
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)
{
}while(condition);
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter n:\n";
cin >> n;
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.
#include <bits/stdc++.h>
using namespace std;
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:
void fun() {
cout << "Fun() Called\n";
}
int main() {
cout << "Before calling fun()\n";
fun();
cout << "After calling fun()\n";
return 0;
}
Output:
Explanation:
void fun() {
cout << "Fun() Called\n";
}
int main() {
cout << "Before calling fun()\n";
fun();
fun();
cout << "After calling fun()\n";
return 0;
}
Output:
This demonstrates that a function can be called multiple times, each time executing
its logic.
A function can also take inputs (parameters) and return a result. This enhances
flexibility and reusability.
#include <iostream>
using namespace std;
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.
#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:
#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()
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.
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.
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.
main calls
fun1,main
fun1
fun1 calls
fun2,fun1,main
fun2
fun2
fun1,main
completes
fun1
main
completes
main
(Empty)
completes
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.
Instead of rewriting the same code every time, you can create dedicated functions.
For instance:
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:
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.
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:
Here:
Example Program
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
cout << getMax(a, b); // Using the function
return 0;
}
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
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:
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.
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;
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:
All default arguments must be declared after non-default arguments. This ensures
that the compiler can correctly assign values to parameters.
Incorrect Code:
Correct Code:
You can specify default values in either the declaration or the definition of the
function, but not both.
Example:
#include <iostream>
using namespace std;
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.
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;
int main() {
cout << getMax(10, 20); // Output: 20
return 0;
}
In this example:
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.
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.
Example 1
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 30, c = 5;
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;
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).
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
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 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.
#include <iostream>
using namespace std;
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.
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.
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:
int main() {
int i = 2;
fun(++i, ++i, ++i);
return 0;
}
Output
555
Key Points:
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.
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).
The first digit of a number is simply the leftmost digit in the number. For example:
To determine the first digit of a number, the following steps are used:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n; // Input the number
cout << find_first_digit(n); // Print the first digit
return 0;
}
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.
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;
}
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.
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.
#include <iostream>
using namespace std;
int main()
{
// array declaration by specifying size
int arr1[10];
return 0;
}
Array declaration by initializing elements
#include <iostream>
using namespace std;
int main()
{
// Array declaration by specifying size and initializing
// elements
int arr[6] = { 10, 20, 30, 40 };
return 0;
}
Advantages of an Array in C/C++:
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.
An array's elements can be accessed using their indices. In C++, array indices start
from 0 and go up to size - 1.
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:
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.
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40};
return 0;
}
Output:
0x7fff89aa1610
30
Explanation:
int main() {
int arr[] = {10, 20, 30, 40};
return 0;
}
Explanation:
If an array is partially initialized, the uninitialized elements are set to 0 for statically
allocated arrays.
int main() {
int arr[4] = {10, 20};
return 0;
}
Output:
Explanation:
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.
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
return 0;
}
Output:
10 40 30 45
Explanation:
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};
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.
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:
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 40, 30};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 40, 30};
return 0;
}
Key Points:
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.
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:
#include <vector>
std::vector<int> vec; // Declare an empty dynamic array
vec.push_back(10); // Add an element
vec.pop_back(); // Remove an element
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.
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:
x 0x123 20
y 0x123 20
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;
cout << x;
// Output: 2
}
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;
}
The function works directly with the original variable, so any modifications are
visible outside.
#include<iostream>
using namespace std;
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.
int main() {
string s = "geeksforgeeks course";
fun(s);
return 0;
}
Output:
geeksforgeeks course
Syntax :
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
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
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
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.
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):
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;
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.
#include<iostream>
using namespace std;
int main() {
editAndPrint("Welcome to GeeksforGeeks");
return 0;
}
Output:
Hi, Welcome to GeeksforGeeks
Explanation:
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
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
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