Programming Lanugages
Programming Lanugages
Programming Lanugages
C if...else
C for Loop
C while Loop
C break and continue
C switch...case
C Programming goto
Control Flow Examples
3. Functions & Recursion: Actual & Formal Arguments, Parameter Passing techniques,
Scoping
Programming Functions
C User-defined Functions
C Function Types
C Recursion
C Storage Class
C Function Examples
4. Concept of Pointers: Introduction, Pointer & Array, pointer & Function, Dynamic
Memory allocation
C Programming Arrays
C Multi-dimensional Arrays
C Arrays & Function
C Programming Pointers
C Pointers & Arrays
C Pointers And Functions
C Memory Allocation
Array & Pointer Examples
C Programming String
C String Functions
C String Examples
C Structure
C Struct & Pointers
C Struct & Function
C Unions
C struct Examples
7. File handling
C Files Input/Output
C Files Examples
8. Additional Topics
C Enumeration
C Preprocessors
C Standard Library
C Programming Examples
Simple Program
/* main function
void main () /*# include<stdio.h> is a statement which tells the compiler to insert
/*program statment
printf(“enter the value of a”); /*conio.h is s C header file used mostly by MS-DOS compilers
scanf(%d”,&b);
c=a+b;
printf(“addition=%d”,c);
1. Int main() by the preprocessor before the programs passed on for the compiler…..so
actually C program can never run without a main()
2. Clrscr() is a predefine function by using this function we can clear the data from consle
(Monitor)
3. Printf is for writing output
4. Scanf is for reading input
5. “%d” is format specifiers “%d is simply the way of allocating some space are memory to
fill some data run time.
6. Data type int= “%d” , float= “%f” (decimal)
7. “&” is used only before variable to get its address (“&” a will give the address of a)
8. G
9.
10. etch is actually a standard input library function in C language it can be used to hold
program execution, which is to wait until the user enters a character.
11. “;” is a terminators
C programming is a general-purpose programming language developed in the early 1970s
by Dennis Ritchie at Bell Labs. It is a low-level language commonly used for system
programming, such as operating systems, device drivers, embedded systems, and other
applications requiring high performance and efficient memory management.
Advantages of C Language
Simple
Portable
Structured programming language
Fast and Efficient
Extensible
Helps understand the fundamentals of Computer Theorie
#include <stdio.h>
int main() {
return 0;
Command Description
Any content inside “/* */” will not be used for compilation
/*_some_comments_*/
and execution.
1. Writing the code: In this step, we write the source code for our program using a text
editor or an IDE. For example, let's say we want to write a simple program that prints the
message "Hello, world!" to the console. Here is what the code might look like:
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
2. Compiling the code: Once it has been written, we need to compile it using a C compiler. For
example, we might use the GCC compiler on a Linux system. We would run the following command
from the terminal: gcc -o hello_world hello_world.c
3. Linking the code: In this step, the C compiler may link our code with any necessary libraries or
other code modules. Our simple "Hello, world!" program requires no additional libraries, so this step
is relatively straightforward.
4. Running the program: With our program compiled and linked, we can now run it. On a
Linux system, we would run the following command from the terminal:./hello_worldThis would
execute the hello_world binary and print the message "Hello, world!" to the console.
5. Input and output: In our "Hello, world!" program, there is no input required, and the only
output is the message printed to the console.
6. Memory management: Our simple program does not require dynamic memory allocation or
deallocation, so memory management is not a concern.
7. Debugging and testing: Finally, we want to test and debug our program to ensure it is
working correctly. For a simple program like this, we might manually run it and verify that the output
is correct. For more complex programs, we might use debugging tools like gdb or automated testing
frameworks to help identify and fix issues.
Character set
A character set is a set of alphabets, letters and some special characters that
are valid in C language.
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits
0 1 2 3 4 5 6 7 8 9
Special Characters
, < > . _
( ) ; $ :
% [ ] # ?
- \ ~ +
C Keywords
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase.
Here is a list of all keywords allowed in ANSI C.
C Keywords
do if static while
All these keywords, their syntax, and application will be discussed in their
respective topics. However, if you want a brief overview of these keywords
without going further, visit List of all keywords in C programming.
C Identifiers
Identifier refers to name given to entities such as variables, functions,
structures etc.
int money;
double accountBalance;
Variables
To indicate the storage area, each variable should be given a unique name
(identifier). Variable names are just the symbolic representation of a memory
location. For example:
char ch = 'a';
// some code
ch = 'l';
1. A variable name can only have letters (both uppercase and lowercase letters),
digits and underscore.
Note: You should always try to give meaningful names to variables. For
example: firstName is a better variable name than fn .
C is a strongly typed language. This means that the variable type cannot be
changed once it is declared. For example:
Here, the type of number variable is int . You cannot assign a floating-point
(decimal) value 5.5 to this variable. Also, you cannot redefine the data type of
the variable to double . By the way, to store the decimal values in C, you need
to declare its type to either double or float .
Visit this page to learn more about different types of data a variable can store.
Literals
Literals are data used for representing fixed values. They can be used directly
in the code. For example: 1 , 2.5 , 'c' etc.
Here, 1 , 2.5 and 'c' are literals. Why? You cannot assign different values to
these terms.
1. Integers
octal (base 8)
For example:
2. Floating-point Literals
-2.0
0.0000234
-0.22E-5
3. Characters
4. Escape Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
For example: \n is used for a newline. The backslash \ causes escape from
the normal way the characters are handled by the compiler.
5. String Literals
Constants
If you want to define a variable whose value cannot be changed, you can use
the const keyword. This will create a constant. For example,
You can also define a constant using the #define preprocessor directive. We
will learn about it in C Macros tutorial.
C Data Types
int myVar;
Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.
Basic types
Here's a table containing commonly used types in C programming for quick
access.
char 1 %c
float 4 %f
Type Size (bytes) Format Specifier
double 8 %lf
signed char 1 %c
unsigned char 1 %c
Integers are whole numbers that can have both zero, positive and negative
values but no decimal values. For example, 0 , -5 , 10
int id;
The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states
from -2147483648 to 2147483647 .
float salary;
double price;
char
Keyword char is used for declaring character type variables. For example,
void
void is an incomplete type. It means "nothing" or "no type". You can think of
void as absent.
For example, if a function is not returning anything, its return type should
be void .
If you need to use a large number, you can use a type specifier long . Here's
how:
long a;
long long b;
long double c;
Here variables a and b can store integer values. And, c can store a floating-
point number.
If you are sure, only a small integer ( [−32,767, +32,767] range) will be used,
you can use short .
short d;
You can always check the size of a variable using the sizeof() operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;
In C, signed and unsigned are type modifiers. You can alter the data storage of
a data type by using them:
signed - allows for storage of both positive and negative numbers
unsigned - allows for storage of only positive numbers
For example,
// valid codes
unsigned int x = 35;
int y = -35; // signed int
int z = 36; // signed int
Here, the variables x and num can hold only zero and positive values because
we have used the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -
bool type
Enumerated type
Complex types
Example 1: C Output
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Run Code
Output
C Programming
All valid C programs must contain the main() function. The code execution
begins from the start of the main() function.
The printf() is a library function to send formatted output to the screen. The
function prints the string inside quotations.
To use printf() in our program, we need to include stdio.h header file using
the #include <stdio.h> statement.
The return 0; statement inside the main() function is the "Exit status" of the
program. It's optional.
Output
Number = 5
We use %d format specifier to print int types. Here, the %d inside the
quotations will be replaced by the value of testInteger .
Output
number1 = 13.500000
number2 = 12.400000
Output
character = a
Output
Enter an integer: 4
Number = 4
return 0;
}
Run Code
Output
We use %f and %lf format specifier for float and double respectively.
Output
Enter a character: g
You entered g
When a character is entered by the user in the above program, the character
itself is not stored. Instead, an integer value (ASCII value) is stored.
And when we display that value using %c text format, the entered character is
displayed. If we use %d to display the character, it's ASCII value is printed.
Output
Enter a character: g
You entered g.
ASCII value is 103.
Here's how you can take multiple inputs from the user and display them.
#include <stdio.h>
int main()
{
int a;
float b;
Output
%d for int
%f for float
%c for char
Here's a list of commonly used C data types and their format specifiers.
int %d
char %c
float %f
double %lf
unsigned int %u
signed char %c
unsigned char %c
C Comments
In programming, comments are hints that a programmer can add to make
their code easier to read and understand. For example,
#include <stdio.h>
int main() {
Hello World
Types of Comments
There are two ways to add comments in C:
1. Single-line Comments in C
In C, a single line comment starts with // . It starts and ends in the same line.
For example,
#include <stdio.h>
int main() {
return 0;
}
Output
Age: 25
In the above example, // create integer variable and // print the age
Here, code before // are executed and code after // are ignored by the
compiler.
2. Multi-line Comments in C
In C programming, there is another type of comment that allows us to
comment on multiple lines at once, they are multi-line comments.
#include <stdio.h>
int main() {
int age;
Output
Multi line comment: ctrl + shift + / (windows) and cmd + shift + / (mac)
Use of Comments in C
1. Make Code Easier to Understand
If we write comments on our code, it will be easier to understand the code in
the future. Otherwise you will end up spending a lot of time looking at our own
code and trying to understand it.
Comments are even more important if you are working in a group. It makes it
easier for other developers to understand and use your code.
#include <stdio.h>
int main() {
int age;
// double height;
return 0;
}
Run Code
Age = 25
Now later on, if we need height again, all you need to do is remove the
forward slashes. And, they will now become statements not comments.
Note: Comments are not and should not be used as a substitute to explain
poorly written code. Always try to write clean, understandable code, and then
use comments as an addition.
In most cases, always use comments to explain 'why' rather than 'how' and
you are good to go.
C Programming Operators
An operator is a symbol that operates on a value or a variable. For
example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).
* multiplication
/ division
Operator Meaning of Operator
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Run Code
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The modulo operator % computes the remainder. When a=9 is divided by b=4 ,
a/b = 2.5
a/d = 2.5
c/b = 2.5
c/d = 2
return 0;
}
Run Code
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can
also be used as postfixes like a++ and a-- . Visit this page to learn more about
how increment and decrement operators work when used as postfix.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
= a=b a=b
Operator Example Same as
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Run Code
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
C Relational Operators
== Equal to 5 == 3 is evaluated to 0
return 0;
}
Run Code
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
C Logical Operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Run Code
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
b) is 1 (true).
(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c <
b) are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b)
is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0
(false).
C Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof is a unary operator that returns the size of data (constants,
variables, array, structure, etc).
Example 6: sizeof Operator
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}
Run Code
Output
C if...else Statement
C if Statement
The syntax of the if statement in C programming is:
if (test expression)
{
// code
}
How if statement works?
If the test expression is evaluated to true, statements inside the body of if are
executed.
If the test expression is evaluated to false, statements inside the body
of if are not executed.
Working of if
Statement
Example 1: if statement
// Program to display a number if it is negative
#include <stdio.h>
int main() {
int number;
return 0;
}
Run Code
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
When the user enters -2, the test expression number<0 is evaluated to true.
Hence, You entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
The if statement is easy.
When the user enters 5, the test expression number<0 is evaluated to false and
the statement inside the body of if is not executed
C if...else Statement
The if statement may have an optional else block. The syntax of
the if..else statement is:
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
Working of
if...else Statement
Example 2: if...else statement
// Check whether an integer is odd or even
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
return 0;
}
Run Code
Output
Enter an integer: 7
7 is an odd integer.
When the user enters 7, the test expression number%2==0 is evaluated to false.
Hence, the statement inside the body of else is executed.
C if...else Ladder
The if...else statement executes two different codes depending upon
whether the test expression is true or false. Sometimes, a choice has to be
made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test expressions and
execute different statements.
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
//checks if the two integers are equal.
if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
return 0;
}
Run Code
Output
Nested if...else
It is possible to include an if...else statement inside the body of
another if...else statement.
Example 4: Nested if...else
This program given below relates two integers using either < , > and = similar
to the if...else ladder's example. However, we will use a
nested if...else statement to solve this problem.
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Run Code
Result: 2 < 4
If the body of an if...else statement has only one statement, you do not need
to use brackets {} .
For example, this code
if (a > b) {
printf("Hello");
}
printf("Hi");
is equivalent to
if (a > b)
printf("Hello");
printf("Hi");
C for Loop
In programming, a loop is used to repeat a block of code until the specified
condition is met.
1. for loop
2. while loop
3. do...while loop
We will learn about for loop in this tutorial. In the next tutorial, we will learn
about while and do...while loop.
for Loop
The syntax of the for loop is:
This process goes on until the test expression is false. When the test
expression is false, the loop terminates.
To learn more about test expression (when the test expression is evaluated to
true and false), check out relational and logical operators.
for loop Flowchart
int main() {
int i;
Output
1 2 3 4 5 6 7 8 9 10
1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body
of for loop is executed. This will print the 1 (value of i ) on the screen.
3. The update statement ++i is executed. Now, the value of i will be 2. Again,
the test expression is evaluated to true, and the body of for loop is executed.
This will print 2 (value of i ) on the screen.
4. Again, the update statement ++i is executed and the test expression i < 11 is
evaluated. This process goes on until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for loop terminates.
#include <stdio.h>
int main()
{
int num, count, sum = 0;
return 0;
}
Run Code
Output
The value entered by the user is stored in the variable num . Suppose, the user
entered 10.
The count is initialized to 1 and the test expression is evaluated. Since the test
expression count<=num (1 less than or equal to 10) is true, the body of for loop
is executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2.
Again, the test expression is evaluated. Since 2 is also less than 10, the test
expression is evaluated to true and the body of the for loop is executed.
Now, sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false), and the
loop terminates.
Then, the value of sum is printed on the screen.
1. for loop
2. while loop
3. do...while loop
In the previous tutorial, we learned about for loop. In this tutorial, we will learn
about while and do..while loop.
while loop
The syntax of the while loop is:
while (testExpression) {
// the body of the loop
}
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
}
return 0;
}
Run Code
Output
1
2
3
4
5
do...while loop
The do..while loop is similar to the while loop with one important difference.
The body of do...while loop is executed at least once. Only then, the test
expression is evaluated.
The syntax of the do...while loop is:
do {
// the body of the loop
}
while (testExpression);
The body of do...while loop is executed once. Only then, the testExpression is
evaluated.
If testExpression is true, the body of the loop is executed
again and testExpression is evaluated once more.
This process goes on until testExpression becomes false.
If testExpression is false, the loop ends.
Flowchart of do...while Loop
#include <stdio.h>
int main() {
double number, sum = 0;
printf("Sum = %.2lf",sum);
return 0;
}
Run Code
Output
Here, we have used a do...while loop to prompt the user to enter a number.
The loop works as long as the input number is not 0 .
The do...while loop executes at least once i.e. the first iteration runs without
checking the condition. The condition is checked only after the first iteration
has been executed.
do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
The break statement is almost always used with if...else statement inside
the loop.
Working
of break in C
int main() {
int i;
double number, sum = 0.0;
return 0;
}
Run Code
Output
continue;
The continue statement is almost always used with the if...else statement.
Working of
Continue in C
Example 2: continue statement
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, it's not added to the result
#include <stdio.h>
int main() {
int i;
double number, sum = 0.0;
return 0;
}
Run Code
Output
In this program, when the user enters a positive number, the sum is calculated
using sum += number; statement.
When the user enters a negative number, the continue statement is executed
and it skips the negative number from the calculation.
C switch Statement
The switch statement allows us to execute one code block among many
alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax
of the switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
Notes:
If we do not use the break statement, all statements after the matching label
are also executed.
The default clause inside the switch statement is optional.
switch Statement Flowchart
switch Statement
Flowchart
Example: Simple Calculator
// Program to create a simple calculator
#include <stdio.h>
int main() {
char operation;
double n1, n2;
switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
return 0;
}
Run Code
Output
Enter an operator (+, -, *, /): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
The - operator entered by the user is stored in the operation variable. And,
two operands 32.5 and 12.4 are stored in variables n1 and n2 respectively.
Since the operation is - , the control of the program jumps to
C goto Statement
The goto statement allows us to transfer control of the program to the
specified label .
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the goto statement is encountered, the control
of the program jumps to label: and starts executing the code.
Working of goto Statement
#include <stdio.h>
int main() {
jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
Run Code
Output
1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53
The use of goto statement may lead to code that is buggy and hard to follow.
For example,
one:
for (i = 0; i < number; ++i)
{
test += i;
goto two;
}
two:
if (test > 5) {
goto three;
}
... .. ...
Also, the goto statement allows you to do bad stuff such as jump out of the
scope.
That being said, goto can be useful sometimes. For example: to break from
nested loops.
If you think the use of goto statement simplifies your program, you can use it.
That being said, goto is rarely useful and you can create any C
program without using goto altogether.
Here's a quote from Bjarne Stroustrup, creator of C++, "The fact that 'goto'
can do anything is exactly why we don't use it."
C Functions
A function is a block of code that performs a specific task.
Suppose, you need to create a program to create a circle and color it. You can
create two functions to solve this problem:
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Types of function
There are two types of function in C programming:
The sqrt() function calculates the square root of a number. The function is
defined in the math.h header file.
Visit standard library functions in C programming to learn more.
User-defined function
You can also create functions as per your need. Such functions created by the
user are known as user-defined functions.
How user-defined function works?
#include <stdio.h>
void functionName()
... .. ...
... .. ...
int main()
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
void functionName()
And, the compiler starts executing the codes inside functionName() .
The control of the program jumps back to the main() function once code inside
the function definition is executed.
Working of C Function
3. A large program can be divided into smaller modules. Hence, a large project
can be divided among many programmers.
C User-defined functions
A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are
known as user-defined functions. For example:
Suppose, you need to create a circle and color it depending upon the radius
and color. You can create two functions to solve this problem:
createCircle() function
color() function
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
return 0;
}
Function prototype
A function prototype is simply the declaration of a function that specifies
function's name, parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may
later be used in the program.
Syntax of function prototype
In the above example, int addNumbers(int a, int b); is the function prototype
which provides the following information to the compiler:
1. name of the function is addNumbers()
Calling a function
Control of the program is transferred to the user-defined function by calling it.
The type of arguments passed to a function and the formal parameters must
match, otherwise, the compiler will throw an error.
In the above example, the value of the result variable is returned to the main
function. The sum variable in the main() function is assigned this value.
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in
the function prototype and function definition must match.
Visit this page to learn more on passing arguments and returning value from a
function.
The output of all these programs below is the same, and we have created a
user-defined function in each example. However, the approach we have taken
in each example is different.
void checkPrimeNumber();
int main() {
checkPrimeNumber(); // argument is not passed
return 0;
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
Run Code
3 is a prime number.
The checkPrimeNumber() function takes input from the user, checks whether it is
a prime number or not, and displays it on the screen.
The empty parentheses in checkPrimeNumber(); inside the main() function
indicates that no argument is passed to the function.
The return type of the function is void . Hence, no value is returned from the
function.
int main() {
int n, i, flag = 0;
// no argument is passed
n = getInteger();
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
// returns integer entered by the user
int getInteger() {
int n;
return n;
}
Run Code
5 is a prime number.
int main() {
int n;
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
Run Code
int main() {
int n, flag;
if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
int i;
return 0;
}
Run Code
C Recursion
A function that calls itself is known as a recursive function. And, this technique
is known as recursion.
How recursion works?
void recurse()
... .. ...
recurse();
... .. ...
int main()
... .. ...
recurse();
... .. ...
}
Working of
Recursion
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
Output
Initially, the sum() is called from the main() function with number passed as an
argument.
Suppose, the value of n inside sum() is 3 initially. During the next function call,
2 is passed to the sum() function. This process continues until n is equal to 0.
When n is equal to 0, the if condition fails and the else part is executed
returning the sum of integers ultimately to the main() function.
Sum of Natural Numbers
Advantages and Disadvantages of Recursion
C Storage Class
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the
scope, visibility and lifetime of a variable.
1. automatic
2. external
3. static
4. register
Local Variable
The variables declared inside a block are automatic or local variables. The
local variables exist only inside the block in which it is declared.
Let's take an example.
#include <stdio.h>
int main(void) {
When you run the above program, you will get an error undeclared identifier
i. It's because i is declared inside the for loop block. Outside of the block, it's
undeclared.
Let's take another example.
int main() {
int n1; // n1 is a local variable to main()
}
void func() {
int n2; // n2 is a local variable to func()
}
This means you cannot access the n1 variable inside func() as it only exists
inside main() . Similarly, you cannot access the n2 variable inside main() as it
only exists inside func() .
Global Variable
Variables that are declared outside of all functions are known as external or
global variables. They are accessible from any function inside the program.
int main()
{
++n;
display();
return 0;
}
void display()
{
++n;
printf("n = %d", n);
}
Run Code
Output
n = 7
Suppose, a global variable is declared in file1 . If you try to use that variable in
a different file file2 , the compiler will complain. To solve this problem,
keyword extern is used in file2 to indicate that the external variable is
declared in another file.
Register Variable
The register keyword is used to declare register variables. Register variables
were supposed to be faster than local variables.
However, modern compilers are very good at code optimization, and there is a
rare chance that using register variables will make your program faster.
Unless you are working on embedded systems where you know how to
optimize code for the given application, there is no use of register variables.
Static Variable
A static variable is declared by using the static keyword. For example;
static int i;
The value of a static variable persists until the end of the program.
Output
6 11
During the first function call, the value of c is initialized to 1. Its value is
increased by 5. Now, the value of c is 6, which is printed on the screen.
During the second function call, c is not initialized to 1 again. It's because c is
a static variable. The value c is increased by 5. Now, its value will be 11,
which is printed on the screen.
C Arrays
Arrays in C
An array is a variable that can store multiple values. For example, if you want
to store 100 integers, you can create an array for it.
int data[100];
dataType arrayName[arraySize];
For example,
float mark[5];
Suppose you declared an array mark as above. The first element is mark[0] ,
Declare an Array
Few keynotes:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first
element.
If the size of an array is n , to access the last element, the n-1 index is used. In
this example, mark[4]
Here, we haven't specified the size. However, the compiler knows its size is 5
as we are initializing it with 5 elements.
Initialize an Array
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
#include <stdio.h>
int main() {
int values[5];
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3
Here, we have used a for loop to take 5 inputs from the user and store them
in an array. Then, using another for loop, these elements are displayed on the
screen.
#include <stdio.h>
int main() {
return 0;
}
Run Code
Output
int testArray[10];
Multidimensional arrays
In this tutorial, you learned about arrays. These arrays are called one-
dimensional arrays.
In the next tutorial, you will learn about multidimensional arrays (array of an
array).
C Multidimensional Arrays
In C programming, you can create an array of arrays. These arrays are known
as multidimensional arrays. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You
can think the array as a table with 3 rows and each row has 4 columns.
Two dimensional Array
float y[2][4][3];
Initialization of a 2d array
Initialization of a 3d array
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Output
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
if (j == 1)
printf("\n");
}
return 0;
}
Run Code
Output
Sum Of Matrix:
2.2 0.5
-0.9 25.0
Example 3: Three-dimensional array
// C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Run Code
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
int main() {
int ageArray[] = {2, 8, 4, 12};
Output
Here, we have passed array parameters to the display() function in the same
way we pass variables to a function.
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
return sum;
}
Run Code
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as
an argument.
result = calculateSum(num);
This informs the compiler that you are passing a one-dimensional array to the
function.
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
return 0;
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Notice the parameter int num[2][2] in the function prototype and function
definition:
// function prototype
void displayNumbers(int num[2][2]);
For example,
C Pointers
Pointers are powerful features of C and C++ programming. Before we learn
pointers, let's learn about addresses in C programming.
Address in C
If you have a variable var in your program, &var will give you its address in the
memory.
We have used address numerous times while using the scanf() function.
scanf("%d", &var);
Here, the value entered by the user is stored in the address of var variable.
Let's take a working example.
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
Output
var: 5
address of var: 2686778
Note: You will probably get a different address when you run the above code.
C Pointers
Pointers (pointer variables) are special variables that are used to store
addresses rather than values.
Pointer Syntax
int* p;
int *p1;
int * p2;
int* pc, c;
c = 5;
pc = &c;
To get the value of the thing pointed by the pointers, we use the * operator.
For example:
int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc); // Output: 5
Here, the address of c is assigned to the pc pointer. To get the value stored in
that address, we used *pc .
Note: In the above example, pc is a pointer, not *pc . You cannot and should
not do something like *pc = &c ;
By the way, * is called the dereference operator (when working with pointers).
It operates on a pointer and gives the value stored in that pointer.
int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1
int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1
int* pc, c, d;
c = 5;
d = -15;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Output
Address of c: 2686784
Value of c: 22
Address of c: 2686784
Value of c: 2
Explanation of the program
1. int* pc, c;
2. c = 22;
This assigns 22 to the variable c . That is, 22 is stored in the memory location
of variable c .
3. pc = &c;
4. c = 11;
This assigns 11 to variable c .
5. *pc = 2;
This change the value at the memory location pointed by the pointer pc to 2.
int c, *pc;
#include <stdio.h>
int main() {
int c = 5;
int *p = &c;
printf("%d", *p); // 5
return 0;
}
It's because
int *p = &c;
is equivalent to
int *p:
p = &c;
In both cases, we are creating a pointer p (not *p ) and assigning &c to it.
To avoid this confusion, we can use the statement like this:
int* p = &c;
C Arrays
C Pointers
Relationship Between Arrays and Pointers
An array is a block of sequential data. Let's write a program to print addresses
of array elements.
#include <stdio.h>
int main() {
int x[4];
int i;
return 0;
}
Output
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448
From the above example, it is clear that &x[0] is equivalent to x . And, x[0] is
equivalent to *x .
Similarly,
...
#include <stdio.h>
int main() {
return 0;
}
Enter 6 numbers: 2
3
4
4
12
4
Sum = 29
#include <stdio.h>
int main() {
return 0;
}
*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2
And, printing *(ptr+1) gives us the fourth element. Similarly, printing *(ptr-
To accept these addresses in the function definition, we can use pointers. It's
because pointers are used to store addresses. Let's take an example:
int main()
{
int num1 = 5, num2 = 10;
num1 = 10
num2 = 5
The address of num1 and num2 are passed to the swap() function
using swap(&num1, &num2); .
When *n1 and *n2 are changed inside the swap() function, num1 and num2 inside
the main() function are also changed.
Inside the swap() function, *n1 and *n2 swapped. Hence, num1 and num2 are also
swapped.
Notice that swap() is not returning anything; its return type is void .
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
Run Code
Since ptr and p pointers both have the same address, *p inside main() is also
11.
C Dynamic Memory Allocation
As you know, an array is a collection of a fixed number of values. Once the
size of an array is declared, you cannot change it.
Sometimes the size of the array you declared may be insufficient. To solve
this issue, you can allocate memory manually during run-time. This is known
as dynamic memory allocation in C programming.
C malloc()
The name "malloc" stands for memory allocation.
Example
The above statement allocates 400 bytes of memory. It's because the size
of float is 4 bytes. And, the pointer ptr holds the address of the first byte in
the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized,
whereas the calloc() function allocates memory and initializes all bits to zero.
Syntax of calloc()
Example:
ptr = (float*) calloc(25, sizeof(float));
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't
get freed on their own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr .
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
return 0;
}
Run Code
Output
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
Output
Syntax of realloc()
Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
free(ptr);
return 0;
}
Run Code
Output
Enter size: 2
Addresses of previously allocated memory:
26855472
26855476
C Programming Strings
In C programming, a string is a sequence of characters terminated with a null
character \0 . For example:
char s[5];
String Declaration in C
char c[100];
c = "C programming"; // Error! array type is not assignable.
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output
Also notice that we have used the code name instead of &name with scanf() .
scanf("%s", name);
This is because name is a char array, and we know that array names decay to
pointers in C.
Thus, the name in scanf() already points to the address of the first element in
the string, which is why we don't need to use & .
How to read a line of text?
You can use the fgets() function to read a line of string. And, you can
use puts() to display the string.
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output
Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string
It's because gets() allows you to input any length of characters. Hence, there
might be a buffer overflow.
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
#include <stdio.h>
int main(void) {
char name[] = "Harry Potter";
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}
String Manipulations In C
Programming Using Library
Functions
You need to often manipulate strings according to the need of a problem.
Most, if not all, of the time string manipulation can be done manually but, this
makes programming complex and large.
To solve this, C supports a large number of string handling functions in
the standard library "string.h" .
#include <string.h>
Note: You have to include the code below to run string handling functions.
gets() and puts()
Functions gets() and puts() are two string functions to take string input from
the user and display it respectively as mentioned in the previous chapter.
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Note: Though, gets() and puts() function handle strings, both these functions
are defined in "stdio.h" header file.
C struct
In C programming, a struct (or structure) is a collection of variables (can be of
different types) under a single name.
Define Structures
Before you can create structure variables, you need to define its data type. To
define a struct, the struct keyword is used.
Syntax of struct
struct structureName {
dataType member1;
dataType member2;
...
};
For example,
struct Person {
char name[50];
int citNo;
float salary;
};
Here, a derived type struct Person is defined. Now, you can create variables of
this type.
Create struct Variables
When a struct type is declared, no storage or memory is allocated. To
allocate memory of a given structure type and work with it, we need to create
variables.
Here's how we create structure variables:
struct Person {
// code
};
int main() {
struct Person person1, person2, p[20];
return 0;
}
struct Person {
// code
} person1, person2, p[20];
In both cases,
1. . - Member operator
2. -> - Structure pointer operator (will be discussed in the next tutorial)
Suppose, you want to access the salary of person2 . Here's how you can do it.
person2.salary
Example 1: C structs
#include <stdio.h>
#include <string.h>
int main() {
return 0;
}
Run Code
Output
Notice that we have used strcpy() function to assign the value to person1.name .
This is because name is a char array (C-string) and we cannot use the
assignment operator = with it after we have declared the string.
Finally, we printed the data of person1 .
Keyword typedef
We use the typedef keyword to create an alias name for data types. It is
commonly used with structures to simplify the syntax of declaring variables.
For example, let us look at the following code:
struct Distance{
int feet;
float inch;
};
int main() {
struct Distance d1, d2;
}
int main() {
distances d1, d2;
}
Example 2: C typedef
#include <stdio.h>
#include <string.h>
int main() {
return 0;
}
Run Code
Output
Here, we have used typedef with the Person structure to create an alias person .
Now, we can simply declare a Person variable using the person alias:
Nested Structures
You can create structures within a structure in C programming. For example,
struct complex {
int imag;
float real;
};
struct number {
struct complex comp;
int integers;
} num1, num2;
Suppose, you want to set imag of num2 variable to 11. Here's how you can do it:
num2.comp.imag = 11;
struct complex {
int imag;
float real;
};
struct number {
struct complex comp;
int integer;
} num1;
int main() {
return 0;
}
Run Code
Output
Imaginary Part: 11
Real Part: 5.25
Integer: 6
Why structs in C?
Suppose you want to store information about a person: his/her name,
citizenship number, and salary. You can create different
variables name , citNo and salary to store this information.
What if you need to store information of more than one person? Now, you
need to create different variables for each information per
person: name1 , citNo1 , salary1 , name2 , citNo2 , salary2 , etc.
A better approach would be to have a collection of all related information
under a single name Person structure and use it for every person.
C structs and Pointers
Before you learn about how pointers can be used with structs, be sure to
check these tutorials:
C Pointers
C struct
C Pointers to struct
Here's how you can create pointers to structs.
struct name {
member1;
member2;
.
.
};
int main()
{
struct name *ptr, Harry;
}
int main()
{
struct person *personPtr, person1;
personPtr = &person1;
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
Run Code
Now, you can access the members of person1 using the personPtr pointer.
By the way,
int main()
{
struct person *ptr;
int i, n;
printf("Displaying Information:\n");
for(i = 0; i < n; ++i)
printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);
return 0;
}
Run Code
C structures
C functions
User-defined Function
Here's how you can pass structures to a function
#include <stdio.h>
struct student {
char name[50];
int age;
};
// function prototype
void display(struct student s);
int main() {
struct student s1;
return 0;
}
Output
Displaying information
Name: Bond
Age: 13
#include <stdio.h>
struct student
{
char name[50];
int age;
};
// function prototype
struct student getInformation();
int main()
{
struct student s;
s = getInformation();
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nRoll: %d", s.age);
return 0;
}
struct student getInformation()
{
struct student s1;
return s1;
}
Run Code
#include <stdio.h>
typedef struct Complex
{
float real;
float imag;
} complex;
int main()
{
complex c1, c2, result;
return 0;
}
void addNumbers(complex c1, complex c2, complex *result)
{
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}
Run Code
Output
result.real = 4.5
result.imag = -5.6
C Unions
A union is a user-defined type similar to structs in C except for one key
difference.
Structures allocate enough space to store all their members, whereas unions
can only hold one member value at a time.
union car
{
char name[50];
int price;
};
union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2, *car3;
return 0;
}
union car
{
char name[50];
int price;
} car1, car2, *car3;
In both cases, union variables car1 , car2 , and a union pointer car3 of union
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Output
size of union = 32
size of structure = 40
#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;
int main() {
j.salary = 12.3;
Output
Salary = 0.0
Number of workers = 100
C File Handling
A file is a container in computer storage devices used for storing data.
If you have to enter a large number of data, it will take a lot of time to enter
them all.
However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
You can easily move your data from one computer to another without any
changes.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain
text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the
least security and takes bigger storage space.
2. Binary files
File Operations
In C, you can perform four major operations on files, either text or binary:
3. Closing a file
FILE *fptr;
Opening a file - for creation and edit
Opening a file is performed using the fopen() function defined in
the stdio.h header file.
The syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode");
For example,
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram .
The first function creates a new file named newprogram.txt and opens it for
writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the
file.
Now let's suppose the second binary file oldprogram.bin exists in the
location E:\cprogram . The second function opens the existing file for reading in
binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the
file.
Opening Modes in Standard I/O
Mod
Meaning of Mode During Inexistence of file
e
Mod
Meaning of Mode During Inexistence of file
e
Open for append in binary mode. If the file does not exist, it will be
ab
Data is added to the end of the file. created.
Open for both reading and writing If the file does not exist,
rb+
in binary mode. fopen() returns NULL.
w+ Open for both reading and writing. If the file exists, its contents are
overwritten.
If the file does not exist, it will be
Opening Modes in Standard I/O
Mod
Meaning of Mode During Inexistence of file
e
created.
Open for both reading and If the file does not exist, it will be
a+
appending. created.
Open for both reading and If the file does not exist, it will be
ab+
appending in binary mode. created.
Closing a File
The file (both text and binary) should be closed after reading/writing.
fclose(fptr);
They are just the file versions of printf() and scanf() . The only difference is
that fprintf() and fscanf() expects a pointer to the structure FILE.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
return 0;
}
This program takes a number from the user and stores in the file program.txt .
After you compile and run this program, you can see a text
file program.txt created in C drive of your computer. When you open the file,
you can see the integer you entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
fscanf(fptr,"%d", &num);
This program reads the integer present in the program.txt file and prints it onto
the screen.
If you successfully created the file from Example 1, running this program will
get you the integer you entered.
Other functions like fgetchar() , fputc() etc. can be used in a similar way.
To write into a binary file, you need to use the fwrite() function. The functions
take four arguments:
1. address of data to be written in the disk
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
The first parameter takes the address of num and the second parameter takes
the size of the structure threeNum .
Since we're only inserting one instance of num , the third parameter is 1 . And,
the last parameter *fptr points to the file we're storing the data.
Finally, we close the file.
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
In this program, you read the same file program.bin and loop through the
records one by one.
In simple terms, you read one threeNum record of threeNum size from the file
pointed by *fptr into the structure num .
This will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek() .
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
The first parameter stream is the pointer to the file. The second parameter is
the position of the record to be found, and the third parameter specifies the
location where the offset starts.
Whence Meaning
SEEK_CUR Starts the offset from the current location of the cursor in the file.
Example 5: fseek()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
This program will start reading the records from the file program.bin in the
reverse order (last to first) and prints it.
C Files Examples
To understand all programs on this page, you should have the knowledge of
the following topics.
C Arrays
C Pointers
Array and Pointer Relation
File I/O
C File Examples
1. C program to read name and marks of n number of students and store
them in a file.
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fclose(fptr);
return 0;
}
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
fclose(fptr);
return 0;
}
#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);
C enums
In C programming, an enumeration type (also called enum) is a data type that
consists of integral constants. To define enums, the enum keyword is used.
By default, const1 is 0, const2 is 1 and so on. You can change default values of
enum elements during declaration (if necessary).
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};
Enumerated Type Declaration
When you define an enum type, the blueprint for the variable is created.
Here's how you can create variables of enum types.
Here, the value of false is equal to 0 and the value of true is equal to 1.
#include <stdio.h>
int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}
Output
Day 4
#include <stdio.h>
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;
int main()
{
card = club;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}
Output
enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4
} button;
Suppose you are designing a button for Windows application. You can set
flags ITALICS , BOLD and UNDERLINE to work with text.
There is a reason why all the integral constants are a power of 2 in the above
pseudocode.
// In binary
ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100
Since the integral constants are a power of 2, you can combine two or more
flags at once without overlapping using bitwise OR | operator. This allows you
to choose two or more flags at once. For example,
#include <stdio.h>
enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4
};
int main() {
int myDesign = BOLD | UNDERLINE;
// 00000001
// | 00000100
// ___________
// 00000101
printf("%d", myDesign);
return 0;
}
Output
When the output is 5, you always know that bold and underline is used.
Here, we have added italics to our design. Note, only code for italics is written
inside the if statement.
You can accomplish almost anything in C programming without using
enumerations. However, they can be pretty handy in certain situations.
Working of C Preprocessor
#define PI 3.14
#include <stdio.h>
Here, stdio.h is a header file. The #include preprocessor directive replaces the
above line with the contents of stdio.h header file.
That's the reason why you need to use #include <stdio.h> before you can use
functions like scanf() and printf() .
You can also create your own header file containing function declaration and
include it in your program using this preprocessor directive.
#include "my_header.h"
#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);
printf("Area=%.2f",area);
return 0;
}
#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)
int main() {
float radius, area;
return 0;
}
Visit this page to learn more about macros and #define preprocessor.
Conditional Compilation
In C programming, you can instruct the preprocessor whether to include a
block of code or not. To do so, conditional directives can be used.
Uses of Conditional
to exclude certain code from the program but to keep it as a reference for
future purposes
To use conditional, #ifdef , #if , #defined , #else and #elif directives are used.
#ifdef Directive
#ifdef MACRO
// conditional codes
#endif
Here, the conditional codes are included in the program only if MACRO is
defined.
#if expression
// conditional codes
#endif
#if expression
conditional codes if expression is non-zero
#else
conditional if expression is 0
#endif
You can also add nested conditional to your #if...#else using #elif
#if expression
// conditional codes if expression is non-zero
#elif expression1
// conditional codes if expression is non-zero
#elif expression2
// conditional codes if expression is non-zero
#else
// conditional if all expressions are 0
#endif
#defined
Predefined Macros
Here are some predefined macros in C programming.
Macro Value
The following program outputs the current time using __TIME__ macro.
#include <stdio.h>
int main()
{
printf("Current time: %s",__TIME__);
}
Output
If you want to use the printf() function, the header file <stdio.h> should be
included.
#include <stdio.h>
int main()
{
printf("Catch me if you can.");
}
Run Code
If you try to use printf() without including the stdio.h header file, you will get
an error.
To compute the square root of a number, you can use the sqrt() library
function. The function is defined in the math.h header file.
#include <stdio.h>
#include <math.h>
int main()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);
C++
C Hello World Program
To begin with, the “Hello World” program is the first step towards learning any
programming language and also one of the simplest programs you will learn. All one
needs to do is display the message “Hello World” on the screen. Let’s look at the
program and try to understand the terminologies involved in it.
C Program to Print “Hello World”
The following C program displays “Hello World” in the output.
C
// main function -
int main()
printf("Hello World");
return 0;
Output
Hello World
C
#include <stdio.h>
#include <stdlib.h>
// Driver code
int main()
char ch;
double a, b;
while (1) {
// to exit
if (ch == 'x')
exit(0);
// For Addition
case '+':
break;
// For Subtraction
case '-':
break;
// For Multiplication
case '*':
break;
// For Division
case '/':
break;
default:
printf(
printf("\n");
Output
Enter an operator (+, -, *, /), if want to exit press x: +
Enter two first and second operand: 7 8
7.0 + 8.0 = 15.0
Enter an operator (+, -, *, /), if want to exit press x: -
Enter two first and second operand: 8 9
8.0 - 9.0 = -1.0
Enter an operator (+, -, *, /), if want to exit press x: *
Enter two first and second operand: 8 7
8.0 * 7.0 = 56.0
Enter an operator (+, -, *, /), if want to exit press x: /
Enter two first and second operand: 8 3
8.0 / 3.0 = 2.7
Enter an operator (+, -, *, /), if want to exit press x: x
Complexity Analysis
In this article, we are creating a multiplication table in c which is a basic program for
printing tables in c. We are printing multiplication tables of the number up to a given
range. We will use the concepts of looping and using a 2-D array to print a Multiplication
Table.
Multiplication Table
A multiplication table is a table that shows the multiples of a number. A multiplication
table is created by multiplying a constant number from 1 to a given range of numbers in
repetition order.
Input:
num = 5
range = 10
Output:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
C
#include <stdio.h>
int mul;
mul = num * i;
printf("\n");
// Driver code
int main()
// Multiplication table
// Multiplication table
int num = 5;
print_table(range, num);
return 0;
Output
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Time Complexity: O(n), as only for loop is required.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
2. Using loops and a 2-D array
Algorithm:
Take the input of the number and the range of the multiplication table.
Now use a for loop(variable “k”)is used to traverse the 2-D array, it iterates through
0 to the range.
The first column stores the number (i.e arr[k][0] = num) .
The second column stores the value to be multiplied (i.e arr[k][1] = k+1) .
The third column stores the product (i.e arr[k][2] = arr[k][1] * arr[k][0] ) .
Then use another loop to print the multiplication table.
C
#include <stdio.h>
// table.
row = range;
col = 3;
// Creating a 2-D array to calculate and store the
// Multiplication Table .
int arr[row][col];
arr[k][0] = num;
// column.
arr[k][1] = k + 1;
// column.
}
// For loop to print the Multiplication table
arr[i][2]);
printf("\n");
// Driver code
int main()
// Multiplication table.
// Multiplication table.
int num = 5;
// Calling the Function.
print_table(range, num);
return 0;
Output
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Time Complexity: O(n).
Auxiliary Space: O(row *col), as a 2-D array is used.
LCM of Two Numbers in C
In this article, we will learn how to write a C program to find the LCM of two numbers.
LCM (Least Common Multiple) of two numbers is the smallest positive number that can
be divided by both numbers without leaving a remainder. For example, the LCM of 15
and 25 is 75.
Algorithm to Find LCM in C
Find the maximum of the two numbers and store them in a variable max.
Run a loop and check if max is divisible by both numbers.
if (max % x == 0 && max % y == 0)
If the condition is true, it means that max is the LCM of the two numbers.
If the condition is false, increment max by 1 and continue the loop to check the next
number.
C Program To Find LCM of Two Numbers
C
// two numbers
#include <stdio.h>
// Driver code
int main()
{
max = (x > y) ? x : y;
// is divisible by x and y
while (1) {
max);
break;
++max;
return 0;
Output
The LCM of 15 and 25 is 75.
Complexity Analysis
C++
#include <iostream>
if (b == 0)
return a;
int main()
cout << "LCM of " << a << " and " << b << " is "
return 0;
Output
LCM of 15 and 20 is 60
Complexity Analysis
In this article, we will see how to check Armstrong number in the c program. We can
implement two logic for checking Armstrong numbers, one for 3-digit numbers and the
second one for more than 3 digits.
C
// of Digits
#include <stdio.h>
// Driver code
int main()
int n = 153;
int temp = n;
int p = 0;
while (n > 0) {
n = n / 10;
// or not.
if (temp == p) {
else {
return 0;
Output:
Yes. It is Armstrong No.
Time Complexity: O(logn)
Auxiliary Space: O(1)
C Program for Armstrong Number of n Digits
The idea is to first count the number of digits (or find the order). Let the number of digits
be n. For every digit r in input number x, compute rn. If the sum of all such values is equal
to n, then return true, else false.
C
// using Functions
#include <stdio.h>
#include <math.h>
// Function to calculate
int order(int x)
int n = 0;
while (x) {
n++;
x = x / 10;
}
return n;
// number or not
int isArmstrong(int x)
int n = order(x);
while (temp) {
}
// If satisfies Armstrong condition
if (sum == x)
return 1;
else
return 0;
// Driver Program
int main()
int x = 153;
if (isArmstrong(x) == 1)
printf("True\n");
else
printf("False\n");
x = 1253;
if (isArmstrong(x) == 1)
printf("True\n");
else
printf("False\n");
return 0;
Output:
true
false
Time Complexity: O(logx*log(logx))
Auxiliary Space: O(1)
In this article, we will see how to check Armstrong number in the c program. We can
implement two logic for checking Armstrong numbers, one for 3-digit numbers and the
second one for more than 3 digits.
C
#include <stdio.h>
// Driver code
int main()
int n = 153;
int temp = n;
int p = 0;
while (n > 0) {
n = n / 10;
// or not.
if (temp == p) {
else {
return 0;
Output:
Yes. It is Armstrong No.
Time Complexity: O(logn)
Auxiliary Space: O(1)
C Program for Armstrong Number of n Digits
The idea is to first count the number of digits (or find the order). Let the number of digits
be n. For every digit r in input number x, compute rn. If the sum of all such values is equal
to n, then return true, else false.
C
#include <stdio.h>
#include <math.h>
// Function to calculate
int order(int x)
int n = 0;
while (x) {
n++;
x = x / 10;
return n;
}
// Function to check whether the
// number or not
int isArmstrong(int x)
int n = order(x);
while (temp) {
if (sum == x)
return 1;
else
return 0;
// Driver Program
int main()
int x = 153;
if (isArmstrong(x) == 1)
printf("True\n");
else
printf("False\n");
x = 1253;
if (isArmstrong(x) == 1)
printf("True\n");
else
printf("False\n");
return 0;
Output:
true
false
Time Complexity: O(logx*log(logx))
Auxiliary Space: O(1)
C Program to Print Armstrong Numbers
Between 1 to 1000
Armstrong numbers are those numbers in which the sum of digits raised to the power of a
number of digits in that number will be equal to the number itself. Here will see how to
build a C Program to Display Armstrong numbers between 1 to 1000.
Example:
153
1 3 + 53 + 33
1 + 125 + 27 = 153
Approach 1:
1. Count the number of digits in the number.
2. Then calculate the sum of digits raised to the power of the number of digits in that
number.
3. Check whether it is equal to the number, if yes then print it.
C
#include <stdio.h>
int main()
printf(
num = i;
while (num != 0) {
num /= 10;
count++;
num = i;
sum = pow(num % 10, count)
if (sum == i) {
count = 0;
Output
All Armstrong number between 1 and 1000 are:
1 2 3 4 5 6 7 8 9 153 370 371 407
Time Complexity: O(n * k) where n is the range of numbers to be checked (1 to 1000 in
this case) and k is the maximum number of digits in any number in the range (3 in this
case). This is because the loop runs for each number in the range and for each number,
we calculate the sum of its digits raised to the power of k.
Space Complexity: O(1) as we are only using a constant amount of extra space for
variables to store the count, sum, and current number being checked.
Approach 2:
All one-digit numbers are Armstrong numbers.
C
// C Program to Display Armstrong
#include <stdio.h>
#include <math.h>
int main()
num = i;
if (num <= 9)
else
if (sum == i)
Output
All Armstrong number between 1 and 1000 are:
1 2 3 4 5 6 7 8 9 153 370 371 407
#include <stdio.h>
int main()
i, num2, c;
// Iterating the for loop using
num1 = i;
num2 = i;
while (num1 != 0) {
++c;
while (num2 != 0) {
n = num2 % 10;
int pow=1;
for(int i=1;i<=c;i++)
pow= pow*n;
arm = arm + (pow);
if (arm == i) {
printf("%d\n", i);
arm = 0;
c = 0;
return 0;
Output
1
153
370
371
407
2. Using pow() function
C
// C program to demonstrate an
#include <math.h>
#include <stdio.h>
// Driver code
int main()
arm = 0, i, num2, c;
// given intervals
num1 = i;
num2 = i;
// Finding the number of digits
while (num1 != 0) {
++c;
while (num2 != 0) {
n = num2 % 10;
// it is a armstrong number
if (arm == i) {
printf("%d\n", i);
}
arm = 0;
c = 0;
return 0;
Output
1
153
370
371
407
#include <stdio.h>
int main()
int rows;
scanf("%d", &rows);
// rows
printf("\n");
}
return 0;
Output :
Number of rows: 5
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
2. Inverted Half Pyramid of Numbers
An inverted half-pyramid pattern of numbers is 180° reversed version of half pyramid
pattern.
Pyramid Example:
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
C Program to Print Inverted Half Pyramid Pattern of Numbers
C
#include <stdio.h>
int main()
{
int rows;
scanf("%d", &rows);
printf("\n");
return 0;
Output :
Number of rows: 5
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
3. Full Pyramid Pattern of Numbers
A full pyramid pattern of numbers is similar to an equilateral triangle.
Pyramid Example:
1
2 2 2
3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
C Program to Print Full Pyramid Pattern of Numbers
C
#include <stdio.h>
int main()
int rows;
scanf("%d", &rows);
printf(" ");
printf("\n");
return 0;
Output :
Number of rows: 5
1
2 2 2
3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
4. Full Pyramid of Numbers in 180 Degree
This pattern can be printed by combining half pyramid pattern and an inverted half-
pyramid pattern.
Pyramid Example:
1
22
333
4444
55555
4444
333
22
1
C Program to Print Full Pyramid of Numbers in 180 Degree
C
#include <stdio.h>
void printPattern(int n)
printf("%d", i);
printf("\n");
printf("%d", i);
printf("\n");
// Driver Code
int main()
int n = 8;
printPattern(n);
return 0;
Output
1
22
333
4444
55555
666666
7777777
88888888
7777777
666666
55555
4444
333
22
1
#include <stdio.h>
int main() {
int n = 5;
printf(" ");
// Print asterisks
if (k == 1 || k == 2 * i - 1 || i == n) {
printf("*");
} else {
printf(" ");
}
// Move to the next line after each row
printf("\n");
return 0;
Output
*
* *
* *
* *
*********
int main() {
int n = 5;
printf(" ");
printf("*");
printf("\n");
printf(" ");
printf("*");
printf("\n");
return 0;
Output
*
***
*****
*******
*********
*******
*****
***
*
FAQs on “print pyramid in c”
Q1: What is a pyramid pattern in C?
A pyramid pattern is a triangular pattern formed using characters, typically asterisks (*),
printed in increasing or decreasing order.
Q2: How do you print a pyramid pattern in C?
To print a pyramid pattern in C, you can use nested for loops.
The outer loop controls the number of rows.
The inner loop controls the number of characters to print in each row.
You can use conditional statements to determine the increasing or decreasing pattern.
Q3: What are the different types of pyramid patterns in C?
There are various types of pyramid patterns in C, including:
Right-angled pyramid
Inverted pyramid
Centered pyramid
Hollow pyramid
Diamond pyramid
Approach:
The approach is very simple. We just execute a nested loop, and only print characters
when the inner loop is executed after that just change the line.
Example:
C
#include <stdio.h>
// Driver code
int main()
int n = 6;
printf("*");
printf("\n");
return 0;
Output
*
**
***
****
*****
******
Time Complexity: O(n2)
Auxiliary Space: O(1), No extra Space is used.
C Program For Printing Inverted Pyramid
Here, we will see how to print an inverted pyramid using a C program. Below are the
examples:
Input: 8
Output:
***************
*************
***********
*********
*******
*****
***
*
Input: 5
Output:
*********
*******
*****
***
*
Method 1:
The pattern would be divided into three parts:
1. A for loop will be used to print the blank spaces
2. A for loop will be used to print the triangle from the left-hand side
3. A for loop will be used to print the rest of the triangle, making the exact pattern
Algorithm:
1. Initialize variables i, j, and space for rows, columns, and blank spaces, respectively.
2. The number of rows here is 8, the user can take any number.
3. Initialize a for loop that will work as the main loop in printing the pattern and drive the
other loops inside it.
4. Initialize a for loop that will print the blank spaces inside the main loop.
5. Now, in order to print the star pattern, we will first print the half pyramid as shown
below. To do that, we will initialize a for loop with the condition given as 2 * i – 1,
because the number of stars is odd.
6. After it, we’ll use another for loop to print the rest of the pattern.
Below is the C program to print an inverted pyramid pattern:
C
// C program to print
// inverted pyramid
// pattern
#include <stdio.h>
// Driver code
int main()
for (space = 0;
printf(" ");
printf("* ");
printf("* ");
printf("\n");
return 0;
Output
* * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Time Complexity: O(n2)
Auxiliary Space: O(1)
Method 2:
Two for loops will be used:
1. A for loop will be used to print the blank spaces
2. A for loop will be used to print the stars
Algorithm:
1. Initialize variables i, j, and rows.
2. The number of rows here is 8, the user can take any number.
3. Initialize a for loop that will work as the main loop in printing the pattern and drive
the other loops inside it.
4. Initialize a for loop that will print the blank spaces inside the main loop and will run
from 1 to i.
5. Run a for loop from 1 to rows * 2 – (i * 2 – 1), to print the stars.
6. Move to the next line with the help of the new line character.
Below is the C program to print an inverted pyramid pattern:
C
// C program to print
// inverted pyramid
// pattern
#include <stdio.h>
// Driver code
int main()
int i, j, rows = 8;
{
printf(" ");
for (j = 1;
j++)
printf("*");
printf("\n");
return 0;
Output
***************
*************
***********
*********
*******
*****
***
*
Time Complexity: O(n2)
Auxiliary Space: O(1)
C Program to Print Number Pattern
The idea of pattern based programs is to understand the concept of nesting of for loops
and how and where to place the alphabets / numbers / stars to make the desired pattern.
Write a program to print the pattern of numbers in the following manner using for loop
1
232
34543
4567654
567898765
In almost all types of pattern programs, two things that you must take care:
1. No. of lines
2. If the pattern is increasing or decreasing per line?
Implementation
C
int main()
gap = n - 1;
num = j;
printf(" ");
gap--;
printf("%d", num);
num++;
num--;
num--;
printf("%d", num);
num--;
printf("\n");
return 0;
Output
1
232
34543
4567654
567898765
Here, we will build a C Program To Print Character Pyramid Pattern using 2 approaches
i.e.
1. Using for loop
2. Using while loop
Input:
rows = 5
Output:
A
B B
C C C
D D D D
E E E E E
#include <stdio.h>
int main()
{
int i, j;
int rows = 5;
printf("\n");
character++;
return 0;
Output
A
B B
C C C
D D D D
E E E E E
Time complexity: O(R*R)
Here R is given no of rows.
Auxiliary space: O(1)
As constant extra space is used.
Approach 2: Printing pattern by converting a given number into a character
Assign any number to one variable for the printing pattern. The first for loop is used to
iterate the number of rows and the second for loop is used to repeat the number of
columns. After entering into the loop convert the given number into character to print the
required pattern based on the number of columns.
Example:
C
#include <stdio.h>
int main()
int i, j;
int rows = 5;
// given a number
// pattern
printf("\n");
number++;
return 0;
Output
A
B B
C C C
D D D D
E E E E E
Time complexity: O(R*R)
Here R is given no of rows.
Auxiliary space : O(1)
As constant extra space is used.
#include <stdio.h>
int main()
int i = 1, j = 0;
int rows = 5;
// given a character
while (j <= i - 1) {
j++;
printf("\n");
character++;
j = 0;
i++;
return 0;
Output
A
B B
C C C
D D D D
E E E E E
Time complexity: O(R*R)
Here R is given no of rows.
Auxiliary space : O(1)
As constant extra space is used.
Example:
C
#include <stdio.h>
int main()
int i = 1, j = 0;
int rows = 5;
// given a number
while (j <= i - 1) {
// pattern
j++;
printf("\n");
number++;
j = 0;
i++;
return 0;
Output
A
B B
C C C
D D D D
E E E E E
Time complexity: O(R*R) where R is given no of rows
Auxiliary space : O(1)
Here, we will see how to print continuous character patterns using a C program. Below
are the examples:
Input: rows = 5
Output:
A
BC
DEF
GHIJ
KLMNO
Input: rows = 3
Output:
A
BC
DEF
There are 2 ways to print continuous character patterns in C:
1. Using for loop.
2. Using while loop.
Let’s discuss each of these in detail.
C
// character
#include <stdio.h>
int main()
{
int i, j;
// Number of rows
int rows = 3;
// number rows
{
// Printing character to get
printf("%c ",character);
character++;
printf("\n");
return 0;
Output
A
B C
D E F
Approach 2: Converting a given number into a character
1. Assign any number to one variable for the printing pattern.
2. The first for loop is used to iterate the number of rows.
3. The second for loop is used to repeat the number of columns.
4. After entering into the loop convert the given number in to character to print the
required pattern based on the number of columns and increment the character value at
each column to print a continuous character pattern.
Below is the C program to print continuous character patterns by converting numbers into
a character:
C
// number in to character
#include <stdio.h>
// Driver code
int main()
int i, j;
// Number of rows
int rows = 5;
// Given a number
// number of rows
// required pattern
// character
number++;
printf("\n");
return 0;
Output
A
B C
D E F
G H I J
K L M N O
C
#include <stdio.h>
// Driver code
int main()
int i = 1, j = 0;
// Number of rows
int rows = 5;
// Given a character
while (j <= i - 1)
j++;
// character
character++;
printf("\n");
j = 0;
i++;
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Time complexity: O(R*R) where R is given no of rows
Auxiliary space: O(1)
Approach 2: Converting a given number into a character
Below is the C program to print a continuous character pattern by converting a given
number into a character using a while loop:
C
// number in to character
#include <stdio.h>
// Driver code
int main()
int i = 1, j = 0;
// Number of rows
int rows = 5;
// Given a number
int number = 65;
while (j <= i - 1)
// required pattern
printf("%c ",character);
j++;
// character
number++;
}
printf("\n");
j = 0;
i++;
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Time complexity: O(n2) where n is given rows
Auxiliary Space: O(n)
C Program To Print Hollow Star Pyramid
Here, we will print the hollow star pyramid pattern using a C program.
Input:
n = 5
Output:
*
* *
* *
* *
***********
C
// C Program to Demonstrate
#include <stdio.h>
int main()
int i, space, n = 5, j = 0;
printf(" ");
}
// pattern
if (j == 0 || j == 2 * i)
printf("*");
else
printf(" ");
printf("\n");
printf("*");
return 0;
}
Output
*
* *
* *
* *
*********
Time Complexity: O(n^2) for given input n
Auxiliary Space: O(1)
C Program To Print Inverted Hollow Star
Pyramid
Here we will see how to print an inverted hollow star pyramid using a C program. Below
are the examples:
Input: row = 5
Output:
*********
* *
* *
* *
*
Input: row = 7
Output:
*************
* *
* *
* *
* *
* *
*
There are 2 ways to print an inverted hollow star pyramid in C:
1. Using For Loop.
2. Using While Loop.
Let’s start discussing each of these methods in detail.
C
#include <stdio.h>
printf(" ");
if (j == 1 || k == 1)
printf("*");
else if (k == last_col)
printf("*");
else
printf(" ");
printf("\n");
// Driver code
int main()
// Number of rows
int row = 7;
pattern_fun(row);
return 0;
Output
*************
* *
* *
* *
* *
* *
*
Time Complexity: O(n2), as the nested loop, is used.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Using While Loop:
Below is the C program to print an inverted hollow star pyramid using a while loop:
C
// loop
#include <stdio.h>
int j = 1;
int sp = 1;
int k = 1;
// control variable.
sp = 1;
printf(" ");
// variable.
k = 1;
printf("*");
else if (k == last_col)
printf("*");
else
printf(" ");
k++;
printf("\n");
j++;
}
// Driver code
int main()
// Number of rows
int row = 4;
pattern_fun(row);
return 0;
Output
*******
* *
* *
*
Time Complexity: O(n2), as the nested loop is used.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
C Program To Print Hollow Diamond Pattern
To print the hollow diamond pattern in C, we will use the following 2 approaches:
1. for Loop
2. while Loop
Input:
n = 5
Output:
*
* *
* *
* *
* *
* *
* *
* *
*
#include <stdio.h>
int main()
{
int n = 5, rows, columns;
printf(" ");
// print star
printf("*");
columns++) {
printf(" ");
if (rows == 1) {
printf("\n");
else {
printf("*\n");
printf(" ");
}
// print star
printf("*");
columns++) {
printf(" ");
if (rows == 1) {
printf("\n");
else {
printf("*\n");
return 0;
Output
*
* *
* *
* *
* *
* *
* *
* *
*
#include <stdio.h>
int main()
printf(" ");
columns--;
// print star
printf("*");
columns = 1;
printf(" ");
columns++;
if (rows == 1) {
printf("\n");
}
else {
printf("*\n");
rows++;
rows = n - 1;
columns = n;
printf(" ");
columns--;
// print star
printf("*");
columns = 1;
while (columns < (rows - 1) * 2) {
printf(" ");
columns++;
if (rows == 1) {
printf("\n");
else {
printf("*\n");
rows--;
return 0;
Output
*
* *
* *
* *
* *
* *
* *
* *
*
Time complexity: O(n2) for given input n
Auxiliary space: O(1) as it is using constant space for variables
C Program To Print Diamond Pattern
Here, we will see how to print a full diamond shape pyramid using the C program. Below
are the examples:
Input: 6
Output:
*
**
***
****
*****
******
******
*****
****
***
**
*
Input: 8
Output:
*
**
***
****
*****
******
*******
********
********
*******
******
*****
****
***
**
*
Approach:
1. The first step is to print the upper part of the diamond using three nested loops.
1. The first loop handles the number of rows.
2. The Second loop is for the initial space before the stars.
3. The third loop print the stars.
2. Now Repeat again steps 1, 2, and 3 in reverse order to print the lower part of the
diamond.
Below is the C program to print full diamond shape pyramid:
C
#include <stdio.h>
void printDiamond(int n)
int space = n - 1;
// of rows
for (int i = 0; i < n; i++)
printf(" ");
printf("* ");
printf("\n");
space--;
space = 0;
// run a loop till number of rows
printf(" ");
printf("* ");
printf("\n");
space++;
// Driver code
int main()
printDiamond(8);
return 0;
Output
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n*n) since here we are traversing the rows and columns of a grid
for printing spaces ‘ ‘ and star ‘*’.
Auxiliary Space: O(1), No extra Space is used.
Pascal Triangle Program in C
Pascal’s Triangle is a pattern in which the first row consists of a single number 1, and
each row begins and ends with the number 1. The numbers in between are obtained by
adding the two numbers directly above them in the previous row.
In this article, we will see how to print Pascal’s triangle in C programming language.
Pascal’s Triangle is a triangular array of binomial coefficients in which the nth row
contains binomial coefficients nC0, nC1, nC2, ……. nCn.
n
Cr can be represented as C(n,r) and this represents the nth row’s rth element in Pascal’s
pyramid. The idea is to calculate C(n, r) using C(n, r-1). It can be calculated in O(1) time
using the following formula:
This is an efficient way to calculate the binomial coefficients using the values from the
previous row.
#include <stdio.h>
void printPascal(int n)
printf(" ");
int coef = 1;
// is always 1
printf("%4d", coef);
printf("\n");
}
// Driver code
int main()
int n = 5;
printPascal(n);
return 0;
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Complexity Analysis
Here we will build a C program to print Floyd’s Triangle Pyramid pattern. Floyd’s
Triangle is a triangular array of natural numbers where the nth row contains n elements.
There are 8 methods to cover all variations of Floyd’s Triangles
1. Floyd’s triangle using for loop.
2. Floyd’s triangle using while loop.
3. Floyd’s triangle using recursion.
4. Reverse Floyd’s triangle using for loop.
5. Star Floyd’s triangle using for loop.
6. Alphabets Floyd’s triangle using for loop.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
a
b c
d e f
g h i j
*
* *
* * *
* * * *
#include <stdio.h>
void floyd(int n)
int i, j = 1;
if (i == (j * (j + 1)) / 2) {
printf("\n");
j++;
}
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Time Complexity: O(n2)
Auxiliary Space: O(1)
2. Floyd’s triangle using while loop
C
#include <stdio.h>
void floyd(int n)
int i = 1, j = 1;
// condition for number of element
if (i == (j * (j + 1)) / 2) {
printf("\n");
j++;
i++;
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Time Complexity: O(n2)
Auxiliary Space: O(1)
3. Floyd’s triangle using recursion
C
// Using recursion
#include <stdio.h>
int row = 1, i = 1;
void floyd(int n)
// base condition
if (n == 0)
return;
row++;
printf("\n");
floyd(n - 1);
}
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Time Complexity: O(n2)
Auxiliary Space: O(n) for call stack, because using recursion
4. Reverse Floyd’s triangle using for loop
C++
#include <iostream>
void reverse_floyd(int n)
while (i > 0) {
n--;
printf("\n");
int main()
reverse_floyd(6);
return 0;
Output:
21 20 19 18 17 16
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
Time Complexity: O(n2)
Auxiliary Space: O(1)
5. Star Floyd’s triangle using for loop
C++
#include <stdio.h>
void floyd(int n)
int i, j = 1;
printf("* ");
if (i == (j * (j + 1)) / 2) {
printf("\n");
j++;
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
Time Complexity: O(n2)
Auxiliary Space: O(1)
6. Alphabets Floyd’s triangle using for loop
C
#include <stdio.h>
void alpha_floyd(int n)
int k = 'a';
printf("\n");
}
int main()
alpha_floyd(6);
return 0;
Output:
a
b c
d e f
g h i j
k l m n o
p q r s t u
Time Complexity: O(n2)
Auxiliary Space: O(1)
C Program To Print Reverse Floyd’s Pattern
Here we will develop a C Program To Print The Reverse Floyd pattern. Given the value
of row(number of rows), we need the approach of looping and using Nested Loop to
print this pattern.
Input:
row = 5
Output:
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
Algorithm:
Take the Input of row value for the Reverse Floyd pattern.
Then we need to calculate the max value by Max Value = row * (row + 1) / 2 .
The Outer Loop used to control the rows iterates from row to 1.
The Inner Loop used to control the column iterates from 1 to the current row.
Example:
C
// of floyd's triangle
#include <stdio.h>
// of numbers.
num--;
int main()
Reverse_Floyd(row);
return 0;
Output:
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
Time Complexity: O(n2), as a nested loop, is used.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
C Program – Functions
C Program To Check Prime Number By
Creating a Function
Prime numbers have only 2 factors, 1 and themselves. For example, 2,3, 5, 7, 11,… are
the first 5 prime numbers. Here we will build a C program to check prime numbers by
creating a function.
// for loop
#include <stdio.h>
int i;
// not
if (number % i != 0)
continue;
else
return 1;
return 0;
// Driver code
int main()
res = primenumber(num);
if (res == 0)
else
Output
7 is a prime number
Below is the C program to check whether a number is prime or not using for loop:
C
#include <stdio.h>
int i;
// number or not
if (number % i == 0)
return 0;
return 1;
}
// Driver code
int main()
res = primenumber(num);
if (res == 1)
else
return 0;
Output
4 is not a prime number
3. Using While Loop
Below is the C program to check whether a number is prime or not using a while
loop:
C
// while loop
#include <stdio.h>
// not
int i = 2;
{
if (number % i == 0)
return 0;
else
i++;
return 1;
// Driver code
int main()
prime = primenumber(num);
if (prime == 1)
printf("%d is a prime number", num);
else
return 0;
Output
7 is a prime number
Prime numbers have only 2 factors, 1 and themselves. For example, 2,3, 5, 7, 9,… are the
first 5 prime numbers. Here we will build a C program to display prime numbers between
two intervals using functions using 2 approaches, for loop and while loop.
Example
Input: num1 = 2, num2 = 10
Output: Prime numbers between 2 and 10 are: 2 3 5 7
Explanation: The prime numbers between the given intervals 2(starting limit) and
10(ending limit) are 2 3 5 and 7
Below is the C program to display prime numbers between two intervals using functions
and for loop:
C
// loop in a function
#include <stdio.h>
// prime number
int i, f = 1;
// given intervals
if (number % i == 0)
f = 0;
break;
}
}
return f;
// Driver code
int main()
num1, num2);
// it is a prime number
f = checkPrimeNumber(j);
if (f == 1)
return 0;
Output
Prime numbers between 2 and 10 are: 2 3 5 7
Below is the C program to display prime numbers between two intervals using functions
and while loop:
C
#include <stdio.h>
int i;
// given intervals
// is prime number
if (number % i == 0) {
return 0;
}
}
return 1;
// Driver code
int main()
num1, num2);
if (isPrime(num1))
{
// printing the result
num1++;
return 0;
Output
The prime numbers between 2 to 10 are: 2, 3, 5, 7,
In this article, we will learn to write a C program to find the roots of the quadratic
equation.
Quadratic Equation is polynomial equations that have a degree of two, which implies that
the highest power of the function is two. The quadratic equation is represented by ax2 +
bx + c where a, b, and c are real numbers and constants, and a ≠ 0. The root of the
quadratic equations is a value of x that satisfies the equation.
How to Find Quadratic Equation Roots?
The Discriminant is the quantity that is used to determine the nature of roots:
Discriminant(D) = b2 - 4ac;
Based on the nature of the roots, we can use the given formula to find the roots of the
quadratic equation.
1. If D > 0, Roots are real and different
// a quadratic equation
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// equation ax*2 + bx + x
// If a is 0, then equation is
if (a == 0) {
printf("Invalid");
return;
int d = b * b - 4 * a * c;
if (d > 0) {
printf("Roots are real and different\n");
else if (d == 0) {
else // d < 0
sqrt_val / (2 * a));
// Driver code
int main()
// Function call
findRoots(a, b, c);
return 0;
Output
Roots are real and different
4.000000
3.000000
Complexity Analysis
Prime numbers are numbers that have only 2 factors, 1 and themselves. For example, 2,
3, 5, 7, 9, 11, etc are some of the first prime numbers. Here we will see whether a number
can be expressed as the sum of two prime numbers using a C program.
Example
Input: 7
Output: Yes
Explanation: 7 can be expressed as sum of 2 and 5 which are prime
Input: 11
Output: No
Explanation: There are no two prime numbers such that their sum is 11
Approach
The idea is to loop from 2 to N and check if N-i and i are prime Below is the C program
to check whether a number can be expressed as the sum of two prime numbers:
C
#include <stdio.h>
int isPrime(int n)
int i, isPrime = 1;
isPrime = 0;
else {
if (n % i == 0) {
isPrime = 0;
break;
return isPrime;
// Driver code
int main()
{
int n = 7, i, flag = 0;
// condition for i to be a
// prime number
if (isPrime(i) == 1) {
// be a prime number
if (isPrime(n - i) == 1) {
printf("Yes\n");
return 0;
printf("No\n");
return 0;
Output
Yes
The complexity of the method above
Time Complexity: O(N2)
Auxiliary Space: O(1)
C Program to Find Sum of Natural Numbers
using Recursion
Natural numbers include all positive integers from 1 to infinity. There are multiple
methods to find the sum of natural numbers and here, we will see how to find the sum of
natural numbers using recursion.
Example
Input : 5
Output : 15
Explanation : 1 + 2 + 3 + 4 + 5 = 15
Input : 10
Output : 55
Explanation : 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Approach
Given a number n,
To calculate the sum, we will use a recursive function recSum(n).
BaseCondition: If n<=1 then recSum(n) returns the n.
Recursive call: return n + recSum(n-1).
Program to find the sum of Natural Numbers using
Recursion
Below is the implementation using recursion:
C
#include <stdio.h>
// natural numbers
int recSum(int n)
// Base condition
if (n <= 1)
return n;
// Recursive call
// Driver code
int main()
int n = 10;
return 0;
Output
Sum = 55
The complexity of the above method
Time complexity: O(n).
Auxiliary space: O(n).
GCD of Two Numbers in C
GCD stands for Greatest Common Divisor and is also known as HCF (Highest Common
Factor). The GCD of two numbers is the largest positive integer that completely divides
both numbers without leaving a remainder.
In this article, we will learn to calculate the GCD of two numbers in the C programming
language.
#include <math.h>
#include <stdio.h>
result--;
// return gcd of a nd b
return result;
int main()
return 0;
Output
GCD of 98 and 56 is 14
Complexity Analysis
Write a program to reverse a stack using recursion, without using any loop.
Example:
Input: elements present in stack from top to bottom 1 2 3 4
Output: 4 3 2 1
Input: elements present in stack from top to bottom 1 2 3
Output: 3 2 1
Recommended Practice
Reverse a Stack
Try It!
3
4
After all calls of reverse, 4 will be passed to function insert at bottom, after that 4
will pushed to the stack when stack is empty
Then 3 will be passed to function insert at bottom , it will check if the stack is empty
or not if not then pop all the elements back and insert 3 and then push other elements
back.
Then 2 will be passed to function insert at bottom , it will check if the stack is empty
or not if not then pop all the elements back and insert 2 and then push other elements
back.
4
Then 1 will be passed to function insert at bottom , it will check if the stack is empty
or not if not then pop all the elements back and insert 1 and then push other elements
back.
4
3
C
// C program to reverse a
#include <stdio.h>
#include <stdlib.h>
struct sNode {
char data;
struct sNode* next;
};
// Function Prototypes
if (isEmpty(*top_ref))
push(top_ref, item);
else {
// Hold all items in Function Call
insertAtBottom(top_ref, item);
// Call Stack
push(top_ref, temp);
// insertAtBottom()
if (!isEmpty(*top_ref)) {
reverse(top_ref);
insertAtBottom(top_ref, temp);
}
}
// Driver Code
int main()
push(&s, 4);
push(&s, 3);
push(&s, 2);
push(&s, 1);
printf("
print(s);
reverse(&s);
printf("
print(s);
return 0;
// Function to check if
// allocate node
printf("Stack overflow
");
exit(0);
new_node->data = new_data;
new_node->next = (*top_ref);
(*top_ref) = new_node;
}
// Function to pop an item from stack
char res;
if (*top_ref == NULL) {
printf("Stack overflow
");
exit(0);
else {
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
// Function to print a
// linked list
printf("
");
top = top->next;
Output
Original Stack
1 2 3 4
Reversed Stack
1 2 3 4
Time Complexity: O(N2).
Auxiliary Space: O(N) use of Stack
Power of a Number in C
In this article, we will learn how to write a C program to calculate the power of a number
(xn). We may assume that x and n are small and overflow doesn’t happen.
C
#include <stdio.h>
// calculate pow(x, n)
long power(int x, unsigned n)
// Initialize result to 1
pow = pow * x;
return pow;
// Driver code
int main(void)
int x = 2;
unsigned n = 3;
// Function call
printf("%d", result);
return 0;
Output
8
Complexity Analysis
C
#include <stdio.h>
const int M = 3;
const int N = 3;
int i, j;
int main()
print(arr);
return 0;
Output
1 2 3 4 5 6 7 8 9
2) When only second dimension is available globally (either as a macro or as a
global constant).
C
#include <stdio.h>
const int N = 3;
int i, j;
}
int main()
print(arr, 3);
return 0;
Output
1 2 3 4 5 6 7 8 9
The above method is fine if second dimension is fixed and is not user specified. The
following methods handle cases when second dimension can also change.
3) If compiler is C99 compatible
From C99, C language supports variable sized arrays to be passed simply by specifying
the variable dimensions (See this for an example run)
C
#include <stdio.h>
{
int i, j;
int main()
int m = 3, n = 3;
print(m, n, arr);
return 0;
Output
1 2 3 4 5 6 7 8 9
If compiler is not C99 compatible, then we can use one of the following methods to pass
a variable sized 2D array.
4) Using a single pointer
In this method, we must typecast the 2D array when passing to function.
C
#include <stdio.h>
int i, j;
int main()
int m = 3, n = 3;
return 0;
Output
1 2 3 4 5 6 7 8 9
5) Using the concept of pointer to an array
C
#include <stdio.h>
const int M = 3;
int i, j;
int main()
print(arr);
return 0;
Output
1 2 3 4 5 6 7 8 9
In this article, we will see how to find the largest element in the array using a C++
program.
The brute force approach to find the maximum element in an array is to compare each
element with all other elements in the array. But we can optimize it by assuming an
element as maximum and start traversing the array. If we find any element greater than
the assumed max, we assume that element as the new max.
Recommended Practice
Help A Thief!!!
Try It!
Algorithm
1. Create a variable max to store the maximum element so far.
2. Initialize max with the element on the first index of the array.
3. Run a loop from the second index to traverse the array.
4. Compare the variable max with the current element and check,
1. If the current element is greater than max(max less than current element), update
max with the current element.
5. After the loop, variable max will hold the maximum element in the array.
C Program to Find the Largest Number in an Array
C
// arr[] of size n
#include <stdio.h>
// in arr[] of size n
int i;
max = arr[i];
return max;
// Driver code
int main()
return 0;
Output
Largest in given array is 9808
Complexity Analysis
Time complexity: O(N), to traverse the Array completely.
Auxiliary Space: O(1), as only an extra variable is created, which will take O(1)
space.
C Program For Maximum and Minimum of an
Array
Given an array of size N. The task is to find the maximum and the minimum element of
the array using the minimum number of comparisons.
Examples:
Input: arr[] = {3, 5, 4, 1, 9}
Output: Minimum element is: 1
Maximum element is: 9
Input: arr[] = {22, 14, 8, 17, 35, 3}
Output: Minimum element is: 3
Maximum element is: 35
Recommended Practice
Max Min
Try It!
First of all, how do we return multiple values from a function? We can do it either using
structures or pointers.
We have created a structure named pair (which contains min and max) to return multiple
values.
struct pair {
int min;
int max;
};
C
#include<stdio.h>
struct pair
int min;
int max;
};
int i;
/*If there is only one element then return it as min and max both*/
if (n == 1)
{
minmax.max = arr[0];
minmax.min = arr[0];
return minmax;
and max*/
minmax.max = arr[0];
minmax.min = arr[1];
else
minmax.max = arr[1];
minmax.min = arr[0];
}
for (i = 2; i<n; i++)
minmax.max = arr[i];
minmax.min = arr[i];
return minmax;
int main()
int arr_size = 6;
struct pair minmax = getMinMax (arr, arr_size);
getchar();
Output:
Minimum element is 1
Maximum element is 3000
Time Complexity: O(n)
Auxiliary Space: O(1) as no extra space was needed.
In this method, the total number of comparisons is 1 + 2(n-2) in the worst case and 1 + n
– 2 in the best case.
In the above implementation, the worst case occurs when elements are sorted in
descending order and the best case occurs when elements are sorted in ascending order.
Maximum and minimum of an array using the tournament
method:
Divide the array into two parts and compare the maximums and minimums of the two
parts to get the maximum and the minimum of the whole array.
Pair MaxMin(array, array_size)
if array_size = 1
return element as both max and min
else if arry_size = 2
one comparison to determine max and min
return that pair
else /* array_size > 2 */
recur for max and min of left half
recur for max and min of right half
one comparison determines true max of the two candidates
one comparison determines true min of the two candidates
return the pair of max and min
Below is the implementation of the above approach:
C
#include <stdio.h>
struct pair {
int min;
int max;
};
int mid;
if (low == high) {
minmax.max = arr[low];
minmax.min = arr[low];
return minmax;
}
if (high == low + 1) {
minmax.max = arr[low];
minmax.min = arr[high];
else {
minmax.max = arr[high];
minmax.min = arr[low];
return minmax;
minmax.min = mml.min;
else
minmax.min = mmr.min;
minmax.max = mml.max;
else
minmax.max = mmr.max;
return minmax;
int arr_size = 6;
getchar();
Output
Minimum element is 1
Maximum element is 3000
Time Complexity: O(n)
Auxiliary Space: O(log n) as the stack space will be filled for the maximum height of the
tree formed during recursive calls same as a binary tree.
Total number of comparisons: let the number of comparisons be T(n). T(n) can be written
as follows:
Algorithmic Paradigm: Divide and Conquer
T(n) = T(floor(n/2)) + T(ceil(n/2)) + 2
T(2) = 1
T(1) = 0
If n is a power of 2, then we can write T(n) as:
T(n) = 2T(n/2) + 2
After solving the above recursion, we get
T(n) = 3n/2 -2
Thus, the approach does 3n/2 -2 comparisons if n is a power of 2. And it does more than
3n/2 -2 comparisons if n is not a power of 2.
C
#include<stdio.h>
struct pair
int min;
int max;
};
maximum */
if (n%2 == 0)
minmax.max = arr[0];
minmax.min = arr[1];
else
minmax.min = arr[0];
minmax.max = arr[1];
maximum */
else
minmax.min = arr[0];
minmax.max = arr[0];
{
if(arr[i] > minmax.max)
minmax.max = arr[i];
minmax.min = arr[i+1];
else
minmax.max = arr[i+1];
minmax.min = arr[i];
return minmax;
}
/* Driver program to test above function */
int main()
int arr_size = 6;
getchar();
Output:
Minimum element is 1
Maximum element is 3000
Time Complexity: O(n)
Auxiliary Space: O(1) as no extra space was needed.
C++ language
C++ Hello World Program
Below is the C++ program to print Hello World.
C++
#include <iostream>
// program begins
int main()
return 0;
Output
Hello World
C++
// as output
#include <iostream>
// Driver code
int main()
string name;
return 0;
Output:
Input in C++
The cin object in 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.
Program 1:
Below is the C++ program to implement cin object to take input from the user:
C++
// cin object
#include <iostream>
int main()
int i;
cin >> i;
// Print output
cout << i;
return 0;
Input:
Output:
Note: Multiple inputs can also be taken using the extraction operators(>>) with cin.
Program 2:
Below is the C++ program to implement multiple inputs from the user:
C++
#include <iostream>
// Driver Code
int main()
string name;
int age;
return 0;
Input:
Output:
The given task is to take an integer as input from the user and print that integer in C++
language. In this article, we will learn how to read and print an integer value.
In the below program, the syntax and procedures to take the integer as input from the user
is shown in C++ language.
Standard Input Stream
The user enters an integer value when asked.
This value is taken from the user with the help of the cin method. The cin method, in
C++, reads the value from the console into the specified variable.
Syntax:
cin >> variableOfXType;
Here,
>> is the extraction operator and 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.
For an integer value, the X is replaced with the type int. The syntax of the cin method
becomes as follows then:
cin >> variableOfIntType;
This entered value is now stored in the variableOfIntType. Now to print this
value, cout method is used.
Standard Output Stream
The cout method, in C++, prints the value passed as the parameter to it, on the console
screen.
Syntax:
cout << variableOfXType;
Here,
<< is the insertion operator.
The data needed to be displayed on the screen is inserted in the standard output stream
(cout) using the insertion operator (<<).
For an integer value, the X is replaced with the type int. The syntax of cout() method
becomes as follows then:
cout << variableOfIntType;
Hence, the integer value is successfully read and printed.
Below is the C++ program to read and print an integer value:
C++
#include <iostream>
// Driver code
int main()
int num;
return 0;
Output
Enter the integer: 10
Entered integer is: 10
Add Two Numbers in C++
The addition of two numbers is a simple task in C++ that can be done using the
arithmetic addition operator (+). But there are many other ways to find the sum of two
numbers in C++. In this article, we will discuss 7 different ways to add two numbers in
C++.
1. Using Addition Operator
Here simply use the addition operator between two numbers and print the sum of the
number.
sum = A + B
C++
#include <iostream>
// of two number
return A + B;
// Driver Code
int main()
int A = 4, B = 11;
// Function call
return 0;
Output
sum = 15
Time complexity: O(1)
Auxiliary Space: O(1)
2. Using the Subtraction Operator
Here simply use the subtraction operator between two numbers, two times so that minus-
minus multiplies and produce the + operator, and return the sum of the numbers.
sum = A - (-B)
C++
#include <iostream>
// of two number
return A - (-B);
// Driver Code
int main()
int A = 4, B = 11;
// Function call
return 0;
Output
sum = 15
Time complexity: O(1)
Auxiliary Space: O(1)
3. Using the Increment and Decrement Operators
Here use the increment/decrement operator to add two numbers. Decrement a number by
one till it becomes zero and increment another number by one, return the second number.
while(B > 0){
A++;
B--;
}
C++ Program to Add Two Numbers Using the Increment and Decrement
Operators
C++
// increment/decrement operator
#include <iostream>
// of two number
// When A is positive
while (A > 0) {
A--;
B++;
// When A is negative
while (A < 0) {
A++;
B--;
}
// Return sum of A and B
return B;
// Driver Code
int main()
int A = 4, B = 11;
// Function call
return 0;
Output
sum = 15
Time Complexity: O(N), where N is the min(A,B)
Auxiliary Space: O(1)
4. Using printf() method
Here “%*s” specifier print the value of a variable, the value of the variable times,
and printf() method return how many character print on the screen.
printf("%*s%*s", A, "", B, "");
C++
#include <iostream>
// of two number
// Driver Code
int main()
int A = 4, B = 11;
// Function call
return 0;
Output
sum = 15
Time complexity: O(1)
Auxiliary Space: O(1)
5. Using Half Adder Method
A sum of two bits can be obtained by performing Bitwise XOR(^) of the two bits. Carry
bit can be obtained by performing Bitwise AND(&) of two bits. This is simple Half
Adder logic that can be used to add 2 single bits. We can extend this logic to integers.
Algorithm
C++ Program to Add Two Numbers Using the Half Adder Method
C++
#include <iostream>
// of two number
while (B != 0) {
A = A ^ B;
B = carry << 1;
return A;
// Driver Code
int main()
{
int A = 4, B = 11;
// Function call
return 0;
Output
sum = 15
Time complexity: O(log n)
Auxiliary Space: O(1)
6. Using Exponential and Logarithm
The idea is to find the exponential of the given two numbers and print the logarithmic of
the result.
printf("%g\n", log(exp(A) * exp(B)));
C++
#include <bits/stdc++.h>
// of two number
// Driver Code
int main()
int A = 4, B = 11;
// Function call
return 0;
Output
sum = 15
Time complexity: O(log n)
Auxiliary Space: O(1)
7. Using Recursion
Algorithm
#include <iostream>
// of two number
// Base Case
if (!A)
return B;
// Recursive Call
else
// Driver Code
int main()
{
int A = 4, B = 11;
// Function call
return 0;
Output
sum = 15
Time complexity: O(log n)
Auxiliary Space: O(log n)
Explanation
(A & B) << 1: This expression calculates the bitwise AND of A and B and then left-
shifts the result by one position. This is done to carry over the bits that are set in both
A and B.
A ^ B: This expression calculates the bitwise XOR of A and B. This is done to
perform the addition without carrying.
The recursive call addTwoNumber((A & B) << 1, A ^ B); keeps adding the numbers
until A becomes zero (base case). At each recursive step, the function calculates the
carry bits and the non-carry bits separately and recursively calls itself with the new
values.
C++ Program to Swap Two Numbers
Swapping numbers is the process of interchanging their values. In this article, we will
learn algorithms and code to swap two numbers in the C++ programming language.
1. Swap Numbers Using a Temporary Variable
We can swap the values of the given two numbers by using another variable to
temporarily store the value as we swap the variables’ data. The below algorithm shows
how to use the temporary variable to swap values.
Algorithm
#include <bits/stdc++.h>
// Driver code
int main()
int a = 2, b = 3;
cout << "Before swapping a = " << a << " , b = " << b
<< endl;
// temporary variable
int temp;
temp = a;
a = b;
b = temp;
cout << "After swapping a = " << a << " , b = " << b
<< endl;
return 0;
Output
Before swapping a = 2 , b = 3
After swapping a = 3 , b = 2
Complexity Analysis
// variable
#include <bits/stdc++.h>
// Driver code
int main()
int a = 2, b = 3;
cout << "Before swapping a = " << a << " , b = " << b
<< endl;
// applying algorithm
b = a + b;
a = b - a;
b = b - a;
cout << "After swapping a = " << a << " , b = " << b
<< endl;
return 0;
Output
Before swapping a = 2 , b = 3
After swapping a = 3 , b = 2
Complexity Analysis
Syntax of swap()
swap(a, b);
where a and b are the two numbers.
C++ Program to Swap Two Numbers Using the Inbuilt swap() Function.
C++
// function
#include <bits/stdc++.h>
// Driver code
int main()
int a = 5, b = 10;
cout << "Before swapping a = " << a << " , b = " << b
<< endl;
swap(a, b);
cout << "After swapping a = " << a << " , b = " << b
<< endl;
return 0;
Output
Before swapping a = 5 , b = 10
After swapping a = 10 , b = 5
In this article, we will learn to write a C++ program to find the size of int, float, double,
and char. It is important to know the size of different data types especially when working
with large datasets to optimize memory usage.
The size of a variable can be determined using sizeof() operator in C++. The syntax of
size of operator is:
sizeof(dataType);
To find the size of the four datatypes:
1. The four types of variables are defined as integerType, floatType, doubleType, and
charType.
2. The size of the variables is calculated using the sizeof() operator.
C++ Program to Find the Size of a Data Types
C++
#include <iostream>
int main()
{
int integerType;
char charType;
float floatType;
double doubleType;
<< "\n";
cout << "Size of char is: " << sizeof(charType) << "\n";
<< "\n";
// Calculate and Print
<< "\n";
return 0;
Output
Size of int is: 4
Size of char is: 1
Size of float is: 4
Size of double is: 8
Complexity Analysis
-2,147,483,648 to
int 4 %d
2,147,483,647
-2,147,483,648 to
long int 4 %ld
2,147,483,647
2.22507e-308 to
double 8 %lf
1.79769e+308
Here, we will see how to multiply two floating-point numbers using the C++ program.
Floating point numbers are numbers that include both integer part and fractional parts
represented in the form of decimal and exponential values. float data type is used to store
floating point values.
For example
Input : A =1.2, B = 3.0
Output : 3.6
#include <iostream>
// Driver code
int main()
return 0;
Output
3.6
Complexity Analysis
C++
#include <bits/stdc++.h>
// to Celsius
float Conversion(float n)
// Driver code
int main()
{
float n = 40;
return 0;
Output:
4.44444
Time Complexity: O(1)
Auxiliary Space: O(1)
C++ Program To Find Simple Interest
#include<iostream>
// Driver code
int main()
// different inputs
float P = 1, R = 1, T = 1;
// Calculate simple interest
float SI = (P * T * R) / 100;
return 0;
Output:
Simple Interest: 0.01
Time complexity: O(1).
Auxiliary space: O(1).
C++ Program To Find Compound Interest
C++
#include <bits/stdc++.h>
// Driver code
int main()
{
double CI = A - principal;
return 0;
Output:
Compound interest is 1025
Time complexity: O(n), as pow() function take O(N) time.
Auxiliary space: O(1).
C++ Program To Find Area And Perimeter Of
Rectangle
A rectangle is a flat figure in a plane. It has four sides and four equal angles of 90 degrees
each. In a rectangle all four sides are not of equal length like squares, sides opposite to
each other have equal length. Both diagonals of the rectangle have equal lengths.
Examples:
Input: 4 5
Output: Area = 20
Perimeter = 18
Input: 2 3
Output: Area = 6
Perimeter = 10
Formulae :
Area of rectangle: a*b
Perimeter of rectangle: 2*(a + b)
Below is the implementation of the above topic:
C++
#include<iostream>
// Utility function
int area = a * b;
return area;
return perimeter;
// Driver code
int main()
int a = 5;
int b = 6;
areaRectangle(a, b) <<
endl;
perimeterRectangle(a, b);
return 0;
Output:
Area = 30
Perimeter = 22
Time Complexity: O(1)
Space Complexity: O(1) as no extra space has been used.
#include <iostream>
// Returns true if n is
// Driver code
int main()
int n = 101;
if (isEven(n))
else
return 0;
Output
Odd
There are many different methods using which we find the maximum or largest number
among three numbers. In this article, we will learn three such methods to find the largest
among three numbers in C++.
Example:
Input: a = 1, b = 2, c = 45
Output: The Largest Among 3 is 45
C++ Program To Find If A Character Is Vowel
Or Consonant
In English Alphabet, vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. The rest of the remaining
characters (like ‘b’, ‘c’, ‘d’, ‘f’ ….) are consonants. In this article, we will learn to write a
C++ program to check whether a character is Vowel or Consonant.
C++
#include <iostream>
void vowelOrConsonant(char x)
|| x == 'O' || x == 'U')
else
// Driver code
int main()
vowelOrConsonant('c');
vowelOrConsonant('E');
return 0;
}
Output
Consonant
Vowel
Complexity Analysis
C++
// function
#include <iostream>
#include <string>
// Driver code
int main()
if (isVowel('a'))
else
return 0;
Output
a is vowel
#include <iostream>
if (year % 400 == 0) {
return true;
return false;
// but divisible by 4
else if (year % 4 == 0) {
return true;
return false;
// Driver code
int main()
return 0;
Output
Leap Year
A year consisting of 366 days instead of the usual 365 days is a leap year. Every fourth
year is a leap year in the Gregorian calendar system. In this article, we will learn how to
write a C++ program to check leap year.
A year is a leap year if one of the following conditions is satisfied:
1. The year is a multiple of 400.
2. The year is a multiple of 4 but not a multiple of 100.
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
#include <iostream>
if (year % 400 == 0) {
return true;
return false;
// but divisible by 4
else if (year % 4 == 0) {
return true;
}
// all other years are not leap years
else {
return false;
// Driver code
int main()
return 0;
Output
Leap Year
C++ Program To Print Multiplication Table of a
Number
Recommended: Please try your approach on {IDE} first, before moving on to the
solution.
Algorithm
The idea is to use loop to iterate the loop variable from 1 to 10 inclusively and display the
product of the given number num and loop variable in each iteration.
1. Initialize loop with loop variable i ranging from 1 to 10.
2. In each iteration, print the product: i * num.
3. Terminate loop when i > 10.
C++ Program to Display Multiplication Tables up to 10
C++
// of a number
#include <iostream>
// Driver code
int main()
int n = 5;
cout << n << " * " << i << " = " <<
n * i << endl;
return 0;
}
Output
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Complexity Analysis
Time complexity: O(N), where N is the range, till which the table is to be printed.
Auxiliary space: O(1).
The above program computes the multiplication table up to 10 only.
C++ Program to Display Multiplication Table Up to a Given
Range
Instead of termination at 10, we can continue the loop to print the multiplication table up
to the given range.
C++
// over a range
#include <iostream>
int main()
// input number
int n = 8;
cout << n << " * " << i << " = " <<
n * i << endl;
return 0;
Output
8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
8 * 11 = 88
Natural numbers are those positive whole numbers starting from 1 (1, 2, 3, 4, …). In this
article, we will learn to write a C++ program to calculate the sum of the first N natural
numbers.
Algorithm
Initialize a variable sum = 0.
Run a loop from i = 1 to n.
Inside the loop, add the value of i to the current value of sum for each iteration.
sum = sum + x
After the loop, the variable sum will hold the sum of the first n natural numbers.
C++ Program to Find the Sum of Natural Numbers
C++
// n natural numbers.
#include <iostream>
// numbers
int findSum(int n)
int sum = 0;
sum = sum + i;
return sum;
}
// Driver code
int main()
int n = 5;
return 0;
Output
15
The Factorial of a non-negative integer is the multiplication of all integers smaller than or
equal to n. For example, the factorial of 6 is 6*5*4*3*2*1 which is 720.
Recursive Solution
Factorial can be calculated using the following recursive formula.
n! = n * (n-1)!
n! = 1 if n = 0 or n = 1
Below is the C++ program to find the factorial of a number using a recursive
solution:
C++
// of given number
#include <iostream>
// given number
if (n == 0)
return 1;
// Driver code
int main()
int num = 5;
Output
Factorial of 5 is 120
In this article, we will learn to write a C++ program to reverse a number. Reversing the
digits of a number means changing the order of the digits of the number so that the last
digit becomes the first digit, the second last digit becomes the second digit, and so on.
The number upon reversing read the same as reading the original number backward.
For example, if the number num is 12548, the reverse of the number num is 84521.
Algorithm to Reverse Digits of a Number
Let us assume the number to be reversed is num and the reversed number will be stored
in rev_num.
Initialize rev_num = 0.
Run a loop till num > 0.
The rightmost digit of num can be obtained by performing modulo by 10 (num %
10).
Now, the rightmost digit obtained is added to the reversed number by shifting its
digits one position to the left.
rev_num = rev_num*10 + num%10;
Remove the last digit from num by dividing it by 10 (num = num / 10).
After the loop, return rev_num which holds the reverse of digits of the number num.
C++ Program to Reverse a Number
C++
// C++ program to implement
#include <bits/stdc++.h>
// Iterative function to
int rev_num = 0;
return rev_num;
// Driver code
int main()
getchar();
return 0;
Output
Reverse of num is 2654
GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is
the largest number that exactly divides both numbers. In this article, we will learn to
write a C++ program to find the GCD of two numbers.
Recommended PracticeLCM And GCDTry It!
C++
#include <bits/stdc++.h>
break;
result--;
return result;
// Driver code
int main()
cout << "GCD of " << a << " and " << b
<< " is "
return 0;
}
// This code is contributed by Suruchi
Kumari
Output
GCD of 98 and 56 is 14
Algorithm
C++
// of two numbers
#include <iostream>
// gcd of a and b
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
// Driver code
int main()
cout << "GCD of " << a << " and " << b
<< " is "
return 0;
Output
GCD of 98 and 56 is 14
Explanation
a = 98 and b = 56
a > b so put a = a - b and b remains the same.
So a = 98 - 56 = 42 and b = 56.
Now b > a so b = b - a and a is same b= 56-42 = 14 & a= 42.
42 is 3 times 14
HCF is 14.
Complexity Analysis
Syntax
__gcd(num1, num2)
where num1 and num2 are the two numbers.
C++ Program to Find the GCD of Two Numbers Using Inbuilt Functions
C++
// __gcd() function
#include <algorithm>
#include <iostream>
Output
gcd(10, 20) = 10
LCM (Least Common Multiple) of two numbers is the smallest number that is divisible
by both numbers. For example, the LCM of 15 and 20 is 60, and the LCM of 15 and 25 is
75. In this article, we will learn to write a C++ program to find the LCM of two numbers.
We can find the LCM of two numbers in C++ using two methods:
1. LCM of Two Numbers Using Simple Method
Algorithm
Initialize two integers a and b with the two numbers for which we want to find the
LCM.
Initialize a variable max with the maximum of a and b.
Run an infinite loop. Inside the loop, check if max is completely divisible by a and b,
it means that max is the LCM of a and b.
Else, increment max by 1 and continue the loop to check the next number.
C++
// while loop
#include <iostream>
// Driver code
int main()
// large number
max_num = (a > b) ? a : b;
while (flag) {
<< max_num;
break;
++max_num;
return 0;
}
Output
LCM of 15 and 20 is 60
Complexity Analysis
Syntax
lcm(num1, num2);
where num1 and num2 are the two numbers.
Note: This function is only available since C++17.
C++
#include <iostream>
#include <numeric>
using namespace std;
int main()
return 0;
Output
LCM(10,20) = 20
Complexity Analysis
C++
// C++ program to find LCM
// of two numbers
#include <iostream>
// gcd of a and b
if (b == 0)
return a;
// two numbers
int main()
cout << "LCM of " << a << " and " << b
<< " is "
return 0;
Complexity Analysis
Time Complexity: O(log(min(a,b))
Auxiliary Space: O(log(min(a,b))
C++ Program to Check Whether a Number is
Palindrome or Not
Given an integer, write a function that returns true if the given number is palindrome, else
false. For example, 12321 is palindrome, but 1451 is not palindrome.
Recommended PracticeSum of Digit is Pallindrome or notTry It!
Let the given number be num. A simple method for this problem is to first reverse digits
of num, then compare the reverse of num with num. If both are same, then return true,
else false.
Following is an interesting method inspired from method#2 of this post. The idea is to
create a copy of num and recursively pass the copy by reference, and pass num by value.
In the recursive calls, divide num by 10 while moving down the recursion tree. While
moving up the recursion tree, divide the copy by 10. When they meet in a function for
which all child calls are over, the last digit of num will be ith digit from the beginning
and the last digit of copy will be ith digit from the end.
C++
// palindrome or not
#include <iostream>
// digit
// of "return num
}
// A recursive function to find
// contains address of a
// copy of num.
if (oneDigit(num))
return false;
*dupNum /= 10;
// from end
// palindrome or not
// make it positive
if (num < 0)
num = -num;
// Driver code
int main()
int n = 12321;
n = 12;
n = 88;
n = 8999;
isPal(n) ? cout << "Yes":
return 0;
Output:
Yes
No
Yes
No
Time complexity: O(log(n))
Auxiliary space: O(1).
C++ Program to check Prime Number
A prime is a natural number greater than 1 that has no positive divisors other than 1 and
itself. For example, 5 is prime but 10 is not prime. In this article, we will learn how to
write a C++ program to check whether a number is prime or not.
Algorithm to Check Prime Numbers in C++
Run a loop from 2 to n/2 using a variable i.
Inside the loop, check whether n is divisible by i using the modulo operator ( n % i ==
0 ).
If n is not divisible by i, it means n is a prime number.
If n is divisible by i, it means n has divisors other than 1 and itself, and thus, it is not a
prime number.
Prime Number Program in C++
Below is the C++ program to check if a number is a prime number or not.
C++
#include <bits/stdc++.h>
// Corner case
if (n <= 1)
return false;
if (n % i == 0)
return false;
return true;
// Driver code
int main()
return 0;
Output
true
false
Complexity Analysis
Time Complexity: O(n)
Auxiliary Space: O(1)
C++ Program To Find Prime Numbers Between
Given Interval
A prime number is defined as a natural number greater than 1 and is divisible by only 1
and itself. In other words, the prime number is a positive integer greater than 1 that has
exactly two factors, 1 and the number itself. The first few prime numbers are 2, 3, 5, 7,
11, 13, 17, 19, 23 . . .
Note: 1 is not either prime or composite. The remaining numbers, except for 1, are
classified as prime and composite numbers.
Given two numbers a and b as interval range, the task is to find the prime numbers in
between this interval.
Examples:
Input: a = 1, b = 10
Output: 2, 3, 5, 7
Input: a = 10, b = 20
Output: 11, 13, 17, 19
In the below program, the range of numbers is taken as input and stored in the variables
‘a’ and ‘b’. Then using for-loop, the numbers between the interval of a and b are
traversed. For each number in the for loop, it is checked if this number is prime or not. If
found prime, print the number. Then the next number in the loop is checked, till all
numbers are checked.
Below is the C++ program to implement the above approach:
C++
// given interval
#include <bits/stdc++.h>
// Driver code
int main()
int a, b, i, j, flag;
// of interval
// Take input
cin >> a;
// Ask user to enter upper value
// of interval
// Take input
cin >> b;
continue;
// if i is prime or not
flag = 1;
if (i % j == 0) {
flag = 0;
break;
if (flag == 1)
return 0;
Output
Enter lower bound of the interval: 1
Enter upper bound of the interval: 10
Prime numbers between 1 and 10 are: 2 3 5 7
The complexity of the above method
Time complexity: O((b-a)*(b/2)), a and b are the lower and upper limits.
Auxiliary space: O(1)
2. Optimized Solution
The idea is to use the fact that even numbers (except 2) are not primes.
Below is the C++ program to implement the above approach:
C++
#include <bits/stdc++.h>
int main()
int a, b, i, j;
// Take input
cin >> a;
// of interval
cin >> b;
if (a <= 2) {
a = 2;
if (b >= 2) {
a++;
}
// Making sure that a is odd before
if (a % 2 == 0)
a++;
for (i = a; i <= b; i = i + 2) {
// if i is prime or not
bool flag = 1;
if (i % j == 0) {
flag = 0;
break;
// not prime
if (flag == 1) {
if (i == 1)
continue;
else
return 0;
Output:
Enter lower bound of the interval: 1
Enter upper bound of the interval: 10
Prime numbers between 1 and 10 are: 2 3 5 7
The complexity of the above method
Time complexity: O((b-a)*(sqrt(b))).
Auxiliary space: O(1).
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than
N when N is smaller than 10 million or so.
Approach
1. Create a boolean array prime[srt to n] and initialize all its entries as true.
2. Mark prime[0] and prime[1] as false because they are not prime numbers.
3. Starting from p = srt, for each prime number p less than or equal to the square root of
n, mark all multiples of p greater than or equal to p*p as composite by setting
prime[i] to false.
4. Finally, print all prime numbers between srt and n.
Below is the C++ program to implement the above approach:
C++
#include <bits/stdc++.h>
// else true.
prime[0] = false;
prime[1] = false;
if (prime[p] == true)
prime[i] = false;
if (prime[p])
// Driver Code
int main()
int srt = 1;
return 0;
Output
2 3 5 7
A neon number is a number where the sum of digits of the square of the number is equal
to the number. The task is to check and print neon numbers in a range.
Examples:
Input: 9
Output: Neon Number
Explanation: square is 9*9 = 81 and
sum of the digits of the square is 9.
Input: 12
Output: Not a Neon Number
Explanation: square is 12*12 = 144 and
sum of the digits of the square is 9 (1
+ 4 + 4) which is not equal to 12.
The implementation is simple, we first compute square of given number, the find sum of
digits in the square.
C++
#include <iostream>
#include <math.h>
int checkNeon(int x)
int sq = x * x;
// digits of sq
int sum_digits = 0;
while (sq != 0)
sq = sq / 10;
}
return (sum_digits == x);
// Driver Code
int main(void)
if (checkNeon(i))
Output:
1 9
Given a number x, determine whether the given number is Armstrong’s number or not.
A positive integer of n digits is called an Armstrong number of order n (order is a
number of digits) if:
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Examples:
Input: 153
Output: Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input: 120
Output: No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input: 1253
Output: No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input: 1634
Output: Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
Recommended PracticeArmstrong NumbersTry It!
1. Simple Approach
The idea is to first count the number of digits (or find the order). Let the number of digits
be n. For every digit r in input number x, compute rn. If the sum of all such values is equal
to n, then return true, else false.
Below is the C++ program to implement the above approach:
C++
// or not
#include <bits/stdc++.h>
if (y == 0)
return 1;
if (y % 2 == 0)
// Function to calculate
int order(int x)
int n = 0;
while (x) {
n++;
x = x / 10;
return n;
// or not
bool isArmstrong(int x)
int n = order(x);
while (temp) {
// If satisfies Armstrong
// condition
// Driver code
int main()
int x = 153;
x = 1253;
Output:
true
false
The complexity of the above method
Time Complexity: O(log2 n) + O((log10 n)*(log2 d)), where n is the number to be checked
and d is the number of digits in the input number.
Space Complexity: O(log2 d), where d is the number of digits.
2. Efficient Approach
C++
#include <iostream>
// Driver code
int main()
{
int n = 153;
int temp = n;
int p = 0;
// Function to calculate
while (n > 0) {
n = n / 10;
if (temp == p) {
else {
return 0;
Output:
Yes. It is Armstrong No.
The complexity of the above method
Time Complexity: The time complexity of the given program is O(d), where ‘d’ is the
number of digits in the input number ‘n’. This is because the while loop runs for ‘d’
iterations, performing constant time operations in each iteration.
Auxiliary Space: The space complexity of the program is O(1) because only a few integer
variables are being used and no additional space is required for arrays, lists, or other
data structures.
3. Find the nth Armstrong Number
Examples:
Input: 9
Output: 9
Input: 10
Output : 153
Below is the C++ program to find the nth Armstrong number:
C++
// Armstrong Number
#include <bits/stdc++.h>
#include <math.h>
// Armstrong Number
int NthArmstrong(int n)
int count = 0;
num = i;
if (i == sum)
count++;
if (count == n)
return i;
// Driver code
int main()
{
int n = 12;
return 0;
Output:
371
Here, we will see how to print Armstrong numbers between 1 to 1000 using a C++
program.
Armstrong Number
A number “N” is an Armstrong number if “N” is equal to the sum of all N’s digits raised
to the power of the number of digits in N.
Example:
There are 2 ways to find all the Armstrong numbers between 1 to 1000 in C++:
1. Using the Brute-force approach.
2. Using the optimized solution.
Let’s start discussing each of these in detail.
C++
// approach
#include <bits/stdc++.h>
// a number.
int count = 0;
while (num > 0)
num /= 10;
count++;
return count;
// or not
{
int curr = num_temp % 10;
num_temp /= 10;
if (sum == num)
return true;
else
return false;
// Driver code
int main()
if (isArmstrong(num))
return 0;
Output
Armstrong numbers between 1 to 1000 : 1 2 3 4 5 6 7 8 9 153 370 371
407
Time Complexity: O(n*d), where d is the order of a number and n is the range(1, 1000).
Auxiliary Space: O(1).
2. Using Optimized Solution
The idea here is to directly print the numbers less than or equal to 9 since they are already
Armstrong numbers and then use an optimized approach to check the rest numbers if they
are Armstrong numbers then print them else return false.
Below is a C++ program to find Armstrong numbers between 1 to 1000 using an
optimized solution:
C++
// solution
#include <bits/stdc++.h>
// Driver code
int main()
if (num <= 9)
else
(ord2 * ord2 *
ord2) +
(ord3 * ord3 *
ord3));
if (total_sum == num)
return 0;
The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the
recurrence relation
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1.
Given a number n, print n-th Fibonacci Number.
Examples:
Input : n = 2
Output : 1
Input : n = 9
Output : 34
Recommended Practice
#include <bits/stdc++.h>
int fib(int n)
if (n <= 1)
return n;
int main()
{
int n = 9;
getchar();
return 0;
Output
34
Time Complexity: Exponential, as every function calls two other functions.
If the original recursion tree were to be implemented then this would have been the tree
but now for n times the recursion function is called
Original tree for recursion
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)
Optimized tree for recursion for code above
fib(5)
fib(4)
fib(3)
fib(2)
fib(1)
Extra Space: O(n) if we consider the function call stack size, otherwise O(1).
Method 2: (Use Dynamic Programming)
We can avoid the repeated work done in method 1 by storing the Fibonacci numbers
calculated so far.
C++
#include<bits/stdc++.h>
class GFG{
public:
int fib(int n)
// 1 extra to handle
// case, n = 0
int i;
f[0] = 0;
f[1] = 1;
}
return f[n];
};
// Driver code
int main ()
GFG g;
int n = 9;
return 0;
Output
34
Time complexity: O(n) for given n
Auxiliary space: O(n)
Method 3: (Space Optimized Method 2)
We can optimize the space used in method 2 by storing the previous two numbers only
because that is all we need to get the next Fibonacci number in series.
C++
#include<bits/stdc++.h>
int fib(int n)
int a = 0, b = 1, c, i;
if( n == 0)
return a;
c = a + b;
a = b;
b = c;
return b;
}
// Driver code
int main()
int n = 9;
return 0;
Output
34
Time Complexity: O(n)
Extra Space: O(1)
Method 4: Using power of the matrix {{1, 1}, {1, 0}}
This is another O(n) that relies on the fact that if we n times multiply the matrix M =
{{1,1},{1,0}} to itself (in other words calculate power(M, n)), then we get the (n+1)th
Fibonacci number as the element at row and column (0, 0) in the resultant matrix.
The matrix representation gives the following closed expression for the Fibonacci
numbers:
C++
#include<bits/stdc++.h>
// back to F[][]
// result in F[][]
int F[2][2] = { { 1, 1 }, { 1, 0 } };
if (n == 0)
return 0;
power(F, n - 1);
return F[0][0];
F[0][1] * M[1][0];
F[0][1] * M[1][1];
int z = F[1][0] * M[0][0] +
F[1][1] * M[1][0];
F[1][1] * M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
int i;
int M[2][2] = { { 1, 1 }, { 1, 0 } };
// matrix to {{1,0},{0,1}}
for(i = 2; i <= n; i++)
multiply(F, M);
// Driver code
int main()
int n = 9;
return 0;
Output
34
Time Complexity: O(n)
Extra Space: O(1)
#include <bits/stdc++.h>
int fib(int n)
if (n == 0)
return 0;
power(F, n - 1);
return F[0][0];
if(n == 0 || n == 1)
return;
power(F, n / 2);
multiply(F, F);
if (n % 2 != 0)
multiply(F, M);
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
// Driver code
int main()
int n = 9;
cout << fib(9);
getchar();
return 0;
Output
34
Time Complexity: O(Logn)
Extra Space: O(Logn) if we consider the function call stack size, otherwise O(1).
Method 6: (O(Log n) Time)
Below is one more interesting recurrence formula that can be used to find n’th Fibonacci
Number in O(Log n) time.
If n is even then k = n/2:
F(n) = [2*F(k-1) + F(k)]*F(k)
Putting m = n in equation(1).
F2n-1 = Fn2 + Fn-12
Putting m = n in equation(2)
C++
#include <bits/stdc++.h>
int fib(int n)
// Base cases
if (n == 0)
return 0;
if (n == 1 || n == 2)
if (f[n])
return f[n];
// if n is odd, else 0.
: (2*fib(k-1) + fib(k))*fib(k);
return f[n];
int main()
int n = 9;
return 0;
Output
34
Time complexity: O(Log n), as we divide the problem in half in every recursive call.
Method 7: (Another approach(Using Binet’s formula))
In this method, we directly implement the formula for the nth term in the Fibonacci
series.
Fn = {[(√5 + 1)/2] ^ n} / √5
Note: Above Formula gives correct result only upto for n<71. Because as we move
forward from n>=71 , rounding error becomes significantly large . Although , using
floor function instead of round function will give correct result for n=71 . But after from
n=72 , it also fails.
Example: For N=72 , Correct result is 498454011879264 but above formula gives
498454011879265.
C++
#include<iostream>
#include<cmath>
int fib(int n) {
// Driver Code
int main ()
{
int n = 9;
return 0;
Output
34
Time Complexity: O(logn), this is because calculating phi^n takes logn time
Auxiliary Space: O(1)
Method 8: DP using memoization(Top down approach)
We can avoid the repeated work done in method 1 by storing the Fibonacci numbers
calculated so far. We just need to store all the values in an array.
C++
#include <bits/stdc++.h>
int dp[10];
int fib(int n)
if (n <= 1)
return n;
if (dp[n - 1] != -1)
else
if (dp[n - 2] != -1)
else
// memoization
// Driver Code
int main()
int n = 9;
getchar();
return 0;
Output
34
C++ Program To Find Sum of Fibonacci
Numbers at Even Indexes Upto N Terms
Given a positive integer N, the task is to find the value of F2 + F4 + F6 +………+ F2n upto
N terms where Fi denotes the i-th Fibonacci number.
The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……
Examples:
Input: n = 5
Output: 88
N = 5, So the fibonacci series will be generated from 0th term upto 10th term:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
Sum of elements at even indexes = 0 + 1 + 3 + 8 + 21 + 55
Input: n = 8
Output: 1596
0 + 1 + 3 + 8 + 21 + 55 + 144 + 377 + 987 = 1596.
Method-1: This method includes solving the problem directly by finding all Fibonacci
numbers till 2n and adding up the only the even indices. But this will require O(n) time
complexity.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
int calculateEvenSum(int n)
if (n <= 0)
return 0;
fibo[0] = 0, fibo[1] = 1;
// Initialize result
int sum = 0;
if (i % 2 == 0)
sum += fibo[i];
return sum;
// Driver code
int main()
// Get n
int n = 8;
endl;
return 0;
Output:
Even indexed Fibonacci Sum upto 8 terms: 1596
Time complexity: O(N).
Auxiliary space: O(N).
Method-2:
It can be clearly seen that the required sum can be obtained thus:
2 ( F2 + F4 + F6 +………+ F2n ) = (F1 + F2 + F3 + F4 +………+ F2n) – (F1 – F2 + F3 – F4 +
………+ F2n)
Now the first term can be obtained if we put 2n instead of n in the formula given here.
Thus F1 + F2 + F3 + F4 +………+ F2n = F2n+2 – 1.
The second term can also be found if we put 2n instead of n in the formula given here
Thus, F1 – F2 + F3 – F4 +………- F2n = 1 + (-1)2n+1F2n-1 = 1 – F2n-1.
So, 2 ( F2 + F4 + F6 +………+ F2n)
= F2n+2 – 1 – 1 + F2n-1
= F2n+2 + F2n-1 – 2
= F2n + F2n+1 + F2n+1 – F2n – 2
= 2 ( F2n+1 -1)
Hence, ( F2 + F4 + F6 +………+ F2n) = F2n+1 -1 .
So in order to find the required sum, the task is to find only F2n+1 which requires O(log n)
time.( Refer to method 5 or method 6 in this article.
Below is the implementation of the above approach:
C++
// C++ Program to find even indexed
#include <bits/stdc++.h>
int f[MAX] = { 0 };
int fib(int n)
// Base cases
if (n == 0)
return 0;
if (n == 1 || n == 2)
return (f[n] = 1);
if (f[n])
return f[n];
n / 2);
fib(k - 1) * fib(k -
1)) :
(2 * fib(k - 1) +
fib(k)) *
fib(k);
return f[n];
}
// Fibonacci Sum
int calculateEvenSum(int n)
// Driver code
int main()
// Get n
int n = 8;
endl;
return 0;
Output:
Even indexed Fibonacci Sum upto 8 terms: 1596
Given two numbers base and exponent, the C++ or C pow() function finds x raised to the
power of y i.e. x y. Basically in C/C++, the exponent value is calculated using the pow()
function. The pow() function is used to calculate the power of a number in C/C++. It
takes double as input and returns double as output.
We have to use #include <math.h> in C/C++ to use that pow() function in our C/C++
program.
Syntax of pow() Function
double pow (double x, double y);
pow() Function Parameters
This method takes only two arguments:
x: floating point base value
y: floating point power value
pow() Function Return Value
The power function returns the floating point value of x raised to the power y ( x y ).
Example of pow() Function
Input: 2.0, 5.0
Output: 32.00
Explanation: pow(2.0, 5.0) executes 2.0 raised to the power 5.0, which
equals 32
Input: 5.0, 2.0
Output: 25.00
Explanation: pow(5.0, 2.0) executes 5.0 raised to the power 2.0, which
equals 25
C
C++
// C program to illustrate
// power function
#include <math.h>
#include <stdio.h>
int main()
printf("%.2lf", result);
return 0;
}
Output
5882.79
Time Complexity: O(log(n))
Auxiliary Space: O(1)
Working of pow() Function with Integers
The pow() function takes ‘double’ as the argument and returns a ‘double’ value. This
function does not always work for integers. One such example is pow(5, 2). When
assigned to an integer, it outputs 24 on some compilers and works fine for some other
compilers. But pow(5, 2) without any assignment to an integer outputs 25.
One another way can be using the round function to assign it to some integer type.
This is because 52 (i.e. 25) might be stored as 24.9999999 or 25.0000000001 because
the return type is double. When assigned to int, 25.0000000001 becomes 25 but
24.9999999 will give output 24.
To overcome this and output the accurate answer in integer format, we can add 1e-9
or 0.000000001 to the result and typecast it to int e.g (int)(pow(5, 2)+1e-9) will give
the correct answer(25, in the above example), irrespective of the compiler.
C++
C
// power function
#include <bits/stdc++.h>
using namespace std;
int main()
int a, b;
// integer result
a = (int)(pow(5, 2) + 0.5);
b = round(pow(5,2));
return 0;
Output
25
25
Examples:
Input : n = 10
Output: 1 2 5 10
Input: n = 100
Output: 1 2 4 5 10 20 25 50 100
Input: n = 125
Output: 1 5 25 125
Note that this problem is different from finding all prime factors.
Recommended Practice
A Naive Solution would be to iterate all the numbers from 1 to n, checking if that
number divides n and printing it. Below is a program for the same:
C++
#include <iostream>
void printDivisors(int n)
if (n % i == 0)
// Driver code
int main()
{
printDivisors(100);
return 0;
Output:
The divisors of 100 are:
1 2 4 5 10 20 25 50 100
Time Complexity : O(n)
Auxiliary Space : O(1)
Can we improve the above solution?
If we look carefully, all the divisors are present in pairs. For example if n = 100, then the
various pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10)
Using this fact we could speed up our program significantly.
We, however, have to be careful if there are two equal divisors as in the case of (10, 10).
In such case, we’d print only one of them.
Below is an implementation for the same:
C++
#include <math.h>
void printDivisors(int n)
if (n % i == 0)
if (n / i == i)
else
// Driver code
int main()
printDivisors(100);
return 0;
Output:
The divisors of 100 are:
1 100 2 50 4 25 5 20 10
C++
// switch statement
#include <iostream>
// Driver code
int main()
char op;
// i.e. +, -, *, /
switch (op) {
// If user enter +
case '+':
break;
// If user enter -
case '-':
// If user enter *
case '*':
break;
// If user enter /
case '/':
break;
default:
}
// switch statement ends
return 0;
Input
+
2
2
Output
4
Complexity Analysis
Here we will build a C++ Program To Print Right Half Pyramid Pattern with the
following 2 approaches:
1. Using for loop
2. Using while loop
Input:
rows = 5
Output:
*
* *
* * *
* * * *
* * * * *
#include <iostream>
int main()
int rows = 5;
return 0;
Output
*
* *
* * *
* * * *
* * * * *
Time complexity: O(n2)
Here n is number of rows.
Space complexity: O(1)
As constant extra space is used.
C++
#include <iostream>
int main()
int i = 0, j = 0;
int rows = 5;
while (j <= i) {
j++;
j = 0;
i++;
return 0;
Output
*
* *
* * *
* * * *
* * * * *
Time complexity: O(n2) where n is number of rows
Space complexity: O(1)
C++ Program To Print Left Half Pyramid
Pattern
Here, we will build a C++ program to print the left half of pyramid pattern using 2
approaches i.e.
1. Using for loop
2. Using while loop
1. Using for loop
Input:
rows = 5
Output:
*
**
***
****
*****
First, for loop is used to identify the number of rows and the second for loop is used to
identify the number of columns. Here the values will be changed according to the first for
loop. If j is greater than i then it will print the output otherwise print the space.
C++
#include <iostream>
int rows = 5;
else {
return 0;
Output
*
**
***
****
*****
Time complexity: O(n2)
Here n is number of rows.
Auxiliary Space: O(1)
As constant extra space is used.
C++
#include <iostream>
int main()
int i = 0, j = 0, sp = 0;
int rows = 5;
// the loop
sp++;
// from starting
sp = 0;
j++;
j = 0;
i++;
return 0;
Output
*
* *
* * *
* * * *
* * * * *
Time complexity: O(n2) where n is number of rows
Space complexity: O(1)
C++ Program To Print Number Pattern
Here, we will see a C++ program to print the 3 different number patterns. There are 3
number patterns covered using for loop and while loop with their respective explanation.
3 Different Number Patterns:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
1
12
123
1234
12345
Pattern 1:
Input: n = 5
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Using for loop:
The first for loop is used to iterate the number of rows and the second for loop is used to
repeat the number of columns. Then print the number and increment the number to print
the next number.
C++
#include <iostream>
int main()
// of columns
number++;
return 0;
}
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Time Complexity: O(n2)
Auxiliary Space: O(1)
The while loops check the condition until the condition is false. If the condition is true
then enter into the loop and execute the statements.
C++
#include <iostream>
int main()
int number = 1;
columns++;
columns = 0;
rows++;
return 0;
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Time Complexity: O(n2)
Auxiliary Space: O(1)
Pattern 2:
Input: n = 5
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Using for loop:
The first for loop is used to iterate the number of rows and the second for loop is used to
repeat the number of columns. Then print the row number to get the required output.
C++
#include <iostream>
int main()
// of rows
return 0;
Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Time Complexity: O(n2)
Auxiliary Space: O(1)
The while loops check the condition until the condition is false. If the condition is true
then enter into the loop and execute the statements.
C++
#include <iostream>
int main()
columns++;
columns = 0;
rows++;
return 0;
Output
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Time Complexity: O(n2)
Auxiliary Space: O(1)
Pattern 3:
Input: n = 5
Output:
1
12
123
1234
12345
Using for loop:
The first for loop is used to iterate the number of rows and the second for loop is used to
repeat the number of columns. Then print the column number to get the required output.
C++
#include <iostream>
int main()
{
int rows, columns, n = 5;
// number of columns
return 0;
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Time Complexity: O(n2)
Auxiliary Space: O(1)
The while loops check the condition until the condition is false. If condition is true then
enter into loop and execute the statements.
C++
#include <iostream>
int number = 1;
columns++;
}
columns = 1;
rows++;
return 0;
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Time Complexity: O(n2)
Auxiliary Space: O(1)
C++ Program To Print Inverted Pyramid
Here we will build a C++ Program To Print Inverted Pyramid using 3 different
approaches:
1. Half Inverted Using “*”
2. Half Inverted Using Numbers
3. Full Inverted Pyramid using ” * “
1. Program to print inverted half Triangle using ” * “
Input:
n=4
Output:
* * * *
* * *
* *
*
As we can observe from the given example the number of printed rows is equal to the
given input n and the number of printed columns is decreasing from n to 1. Therefore we
run the outer for loop from n to 1 and the inner for loop from 1 to row number
Example:
C++
#include <bits/stdc++.h>
#include <iostream>
int main()
int n = 4;
return 0;
Output
* * * *
* * *
* *
*
Time complexity: O(n2)
Here n is number of rows.
Space complexity: O(1)
As constant extra space is used.
#include <bits/stdc++.h>
#include <iostream>
int main()
return 0;
Output
1 2 3 4
1 2 3
1 2
1
Time complexity: O(n2)
Here n is number of rows.
Space complexity: O(1)
As constant extra space is used.
#include <bits/stdc++.h>
#include <iostream>
int main()
{
int n=5;
return 0;
Output
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Time complexity: O(n2) for given input n
Space complexity: O(1)
C++ Program To Print Triangle Pattern
Here we will see how to print triangle patterns using a C++ program. There are 4 patterns
discussed here:
1. Right Triangle.
2. Inverted Right Triangle.
3. Equilateral Triangle.
4. Inverted Equilateral Triangle.
5. Inverted Mirrored Right Triangle.
Let’s start discussing each of these in detail.
1. Right Triangle
Below are the examples for the right triangle:
Input: 4
Output:
*
**
***
****
Input: 5
Output:
*
**
***
****
*****
In the above pattern, it can be observed that
ith row has i elements
Below is the C++ program to print the right triangle:
C++
// C++ program to print
// right triangle
#include <iostream>
// Driver code
int main()
int n = 5;
return 0;
Output
*
* *
* * *
* * * *
* * * * *
Time Complexity: O(n^2)
Auxiliary Space: O(1)
2. Inverted Right Triangle
Below are the examples of inverted right triangles:
Input: 5
Output:
*****
****
***
**
*
Input: 6
Output:
******
*****
****
***
**
*
In this example, it can be observed that if there are a total of n rows in the triangle then:
ith row has n-i+1 elements
Below is the C++ program to print an inverted right triangle:
C++
// right triangle
#include <iostream>
using namespace std;
// Driver code
int main()
int n = 5;
return 0;
Output
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Another Approach:
C++
#include <bits/stdc++.h>
int main()
int n = 5;
return 0;
}
Output
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n^2)
Auxiliary Space: O(1)
3. Equilateral Triangle
Below are examples of an equilateral triangle:
Input: 5
Output:
*
**
***
****
*****
Input: 6
Output:
*
**
***
****
*****
******
In this example, it can be observed that if there are n rows in the pattern then:
ith row has i elements and has (n – i) leading spaces
Below is the C++ program to print an equilateral triangle:
C++
#include <iostream>
// Driver code
int main()
int n = 5;
// and i elements
// i elements
for (int j = 1; j <= i; j++)
return 0;
Output
*
* *
* * *
* * * *
* * * * *
Time Complexity: O(n^2)
Auxiliary Space: O(1)
4. Inverted Equilateral Triangle
Below are examples of an inverted equilateral triangle:
Input: 5
Output:
*****
****
***
**
*
Input: 6
Output:
******
*****
****
***
**
*
It can be observed if there are n rows in the pattern then:
ith row has n-i+1 elements and i-1 leading spaces
Below is the C++ program to print an inverted equilateral triangle:
C++
#include <iostream>
// Driver code
int main()
int n = 5;
// leading spaces
return 0;
Output
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Another Approach:
C++
#include <bits/stdc++.h>
int main()
{
int n = 5;
return 0;
Output
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n^2)
Auxiliary Space: O(1)
5. Inverted Mirrored Right Triangle
Below are the examples of inverted mirrored right triangles:
Input: 5
Output:
*****
****
***
**
*
Input: 6
Output:
******
*****
****
***
**
*
It can be observed if there are n rows in the pattern then:
ith row has n-i+1 elements and 2*(i-1) leading spaces
Below is the C++ program to print an inverted mirrored right triangle:
C++
#include <iostream>
// Driver code
int main()
int n = 5;
// ith row has n-i+1 elements
// leading spaces
return 0;
Output
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n^2)
Auxiliary Space: O(1)
C++ Program To Print Number Without
Reassigning
Here, we will build a C++ program to print the number pattern without Reassigning using
2 approaches i.e.
1. Using for loop
2. Using while loop
1. Using for loop
Input:
n = 5
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
The first for loop is used to iterate the number of rows and the second for loop is used to
repeat the number of columns. Then print the number and increment the number to print
the next number.
C++
#include <iostream>
// of columns
number++;
return 0;
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
C++
#include <iostream>
int main()
int number = 1;
columns++;
// number
number++;
columns = 0;
// incrementing rows value
rows++;
return 0;
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Here we will build a C++ Program To Print Character patterns using 2 Approaches i.e.
1. Using for loop
2. Using while loop
Printing 1 character pattern in C++ using different approaches.
C++
#include <iostream>
int main()
int i, j;
int rows = 5;
// taking first character of alphabet
// pattern
character++;
return 0;
Output
A
B B
C C C
D D D D
E E E E E
Approach 2:
Printing pattern by converting given number into character.
Assign any number to one variable for the printing pattern. The first for loop is used to
iterate the number of rows and the second for loop is used to repeat the number of
columns. After entering into the loop convert the given number into character to print the
required pattern based on the number of columns.
C++
int main()
int i, j;
int rows = 5;
// given a number
// converting number in to
character
// pattern
number++;
return 0;
}
Output
A
B B
C C C
D D D D
E E E E E
C++
#include <iostream>
int i = 1, j = 0;
int rows = 5;
// given a character
while (j <= i - 1) {
// printing character to get
the required
// pattern
j++;
character++;
j = 0;
i++;
return 0;
Output
A
B B
C C C
D D D D
E E E E E
Approach 2:
Printing pattern by converting given number into character using while loop.
C++
#include <iostream>
int main()
int i = 1, j = 0;
int rows = 5;
// given a number
while (j <= i - 1) {
// converting number in to
character
// pattern
j++;
}
C++
#include <iostream>
int main()
int i, j;
int rows = 5;
// taking first character of alphabet
// pattern
character++;
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Approach 2:
Printing pattern by converting given number into
character.
Assign any number to one variable for the
printing pattern. The first for loop is used to
iterate the number of rows and the second for
loop is used to repeat the number of columns.
After entering into the loop convert the given
number into character to print the required
pattern based on the number of columns and
increment the character value at each column to
print a continuous character pattern.
C++
#include <iostream>
int main()
int i, j;
int rows = 5;
// given a number
// converting number in to
character
// pattern
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Approach 1:
C++
#include <iostream>
int main()
int i = 1, j = 0;
int rows = 5;
// given a character
while (j <= i - 1) {
// pattern
j++;
character++;
j = 0;
i++;
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Approach 2:
Printing pattern by converting given number into
character using while loop.
C++
// C++ program to print continuous
// number in to character
#include <iostream>
int main()
int i = 1, j = 0;
int rows = 5;
// given a number
while (j <= i - 1) {
// converting number in to
character
// pattern
j++;
number++;
j = 0;
i++;
return 0;
Output
A
B C
D E F
G H I J
K L M N O
aracter
number++;
j = 0;
i++;
return 0;
Output
A
B B
C C C
D D D D
E E E E E
Here we will build a C++ Program To Print Continuous Character patterns using 2
different methods i.e:
1. Using for loops
2. Using while loops
Input:
rows = 5
Output:
A
B C
D E F
G H I J
K L M N O
C++
#include <iostream>
int main()
int i, j;
int rows = 5;
// taking first character of alphabet
// pattern
character++;
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Approach 2:
Printing pattern by converting given number into character.
Assign any number to one variable for the printing pattern. The first for loop is used to
iterate the number of rows and the second for loop is used to repeat the number of
columns. After entering into the loop convert the given number into character to print the
required pattern based on the number of columns and increment the character value at
each column to print a continuous character pattern.
C++
#include <iostream>
int main()
int i, j;
int rows = 5;
// given a number
// converting number in to
character
// pattern
number++;
}
cout << "\n";
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Approach 1:
The while loops check the condition until the condition is false. If the condition is true
then it enters into the loop and executes the statements.
C++
#include <iostream>
int main()
int i = 1, j = 0;
int rows = 5;
// given a character
while (j <= i - 1) {
// pattern
j++;
character++;
}
j = 0;
i++;
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Approach 2:
Printing pattern by converting given number into character using while loop.
C++
// number in to character
#include <iostream>
int main()
int i = 1, j = 0;
int rows = 5;
// given a number
while (j <= i - 1) {
// converting number in to
character
// pattern
j++;
number++;
}
cout << "\n";
j = 0;
i++;
return 0;
Output
A
B C
D E F
G H I J
K L M N O
Given a number n, write a program to print a diamond shape with 2n-1 rows.
Examples :
Input: 5
Output:
C++
#include <bits/stdc++.h>
void printDiamond(int n)
{
int space = n - 1;
space--;
}
// Repeat again in reverse order
space = 0;
// Print i stars
// Driver code
int main()
printDiamond(5);
return 0;
// by rathbhupendra
Output
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Given the value of R(number of rows), write a C++ program to print the Inverted Hollow
Pyramid using stars and white spaces.
Examples:
Input: R = 5
Output:
*********
* *
* *
* *
*
Input: R = 10
Output:
*******************
* *
* *
* *
* *
* *
* *
* *
* *
*
Algorithm:
At first, take the number of rows as input.
The next step is to implement the nested loop to print this pattern.
A space-maintaining variable(sp) is required to maintain the space at the beginning.
Calculate the last column by Last Column = (length _of_row * 2 – (2 * Current_row
– 1))
Print star( “*” ) at the first column and last column and proceed to the next row.
Below is the C++ program to implement the above approach:
C++
#include <bits/stdc++.h>
void print_patt(int R)
for(int sp = 1;
sp <= i - 1 ; sp++)
}
// Iterating from ith column to
if(i == 1)
else if(j == 1)
else
cout << " ";
// Driver code
int main()
// Number of rows
int R = 5;
print_patt(R);
return 0;
Output
*********
* *
* *
* *
*
Here, we will build a C++ program to print the hollow star pyramid diamond shape
pattern that can be achieved with two approaches i.e.
1. Using for Loop
2. Using while loop
Input:
n = 5
Output:
*
* *
* *
* *
* *
* *
* *
* *
*
int main()
// print star
columns++) {
if (rows == 1) {
else {
}
// print star
columns++) {
if (rows == 1) {
else {
return 0;
Output
*
* *
* *
* *
* *
* *
* *
* *
*
Time complexity: O(n2) for given input n
Auxiliary Space: O(1)
2. Using while loop:
C++
#include <iostream>
int main()
columns--;
// print star
columns = 1;
columns++;
if (rows == 1) {
else {
cout << "*\n";
rows++;
rows = n - 1;
columns = n;
columns--;
// print star
columns = 1;
columns++;
if (rows == 1) {
else {
rows--;
return 0;
Output
*
* *
* *
* *
* *
* *
* *
* *
*
Time complexity: O(rows*columns)
Auxiliary Space: O(1)
C++ Program For Pascal’s Triangle
Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that
takes an integer value n as input and prints first n lines of the Pascal’s triangle. Following
are the first 6 rows of Pascal’s Triangle.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Recommended Practice
Pascal Triangle
Try It!
C++
// C++ code for Pascal's Triangle
#include <iostream>
// See https://www.geeksforgeeks.org/space-
and-time-efficient-binomial-coefficient/
// n lines of Pascal's
// Triangle
void printPascal(int n)
// print entries in it
// number
cout <<"\n";
// See https://www.geeksforgeeks.org/space-
and-time-efficient-binomial-coefficient/
int res = 1;
if (k > n - k)
k = n - k;
res *= (n - i);
res /= (i + 1);
return res;
// Driver program
int main()
int n = 7;
printPascal(n);
return 0;
Output :
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
Auxiliary Space: O(1)
Time complexity of this method is O(n^3). Following are optimized methods.
Method 2( O(n^2) time and O(n^2) extra space )
If we take a closer at the triangle, we observe that every entry is sum of the two values
above it. So we can create a 2D array that stores previously generated values. To generate
a value in a line, we can use the previously stored values from array.
C++
#include <bits/stdc++.h>
int arr[n][n];
// print integer(s) in it
if (line == i || i == 0)
arr[line][i] = 1;
else
arr[line - 1]
[i];
// Driver code
int main()
int n = 5;
printPascal(n);
return 0;
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
This method can be optimized to use O(n) extra space as we need values only from
previous row. So we can create an auxiliary array of size n and overwrite values.
Following is another method uses only O(1) extra space.
Method 3 ( O(n^2) time and O(1) extra space )
This method is based on method 1. We know that ith entry in a line number line is
Binomial Coefficient C(line, i) and all lines start with value 1. The idea is to
calculate C(line, i) using C(line, i-1). It can be calculated in O(1) time using the
following.
C++
#include <bits/stdc++.h>
void printPascal(int n)
C = C * (line - i) / i;
}
cout<<"\n";
// Driver code
int main()
int n = 5;
printPascal(n);
return 0;
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
C++
#include <bits/stdc++.h>
using namespace std;
// Initializing count to 1.
int count = 1;
// number of column.
// of numbers
count += 1;
// Driver Code
int main()
int row = 5;
print_patt(row);
return 0;
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Time Complexity: O(n2) as the nested loop is used.
Auxiliary Space: O(1) no extra space is required, so space is constant.
2. Using while loop
Below is the C++ program to print Floyd’s triangle using the While loop.
C++
#include <bits/stdc++.h>
// Initializing count to 1.
int count = 1;
int i = 1, j;
// The outer loop maintains
j = 1;
// number of column.
while (j <= i)
// count of numbers
count += 1;
// of inner loop.
j += 1;
i += 1;
// Driver Code
int main()
{
int row = 5;
print_patt(row);
return 0;
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Time Complexity: O(n2) as the nested loop is used.
Auxiliary Space: O(1) no extra space is required, so space is constant.
3. Using Recursion
Below is the C++ program to print Floyd’s triangle using Recursion:
C++
// using recursion
#include <bits/stdc++.h>
int count)
// returns return.
if (row <= 0)
return;
// of rows.
// of numbers
count += 1;
}
curr_row += 1;
print_patt(row - 1,
curr_row, count);
// Driver Code
int main()
int curr_row = 1;
int count = 1;
int row = 5;
return 0;
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Time Complexity: O(n2).
Auxiliary Space: O(n) as a recursive approach is used.
C++ Program To Print Reverse Floyd’s
Triangle
Floyd’s triangle is a triangle with first natural numbers. Task is to print reverse of Floyd’s
triangle.
Examples:
Input: 4
Output:
10 9 8 7
6 5 4
3 2
1
Input: 5
Output:
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
C++
// of Floyd's triangle
#include <bits/stdc++.h>
void printReverseFloyd(int n)
int curr_val = n * (n + 1) / 2;
}
cout << endl;
// Driver's Code
int main()
int n = 7;
printReverseFloyd(n);
return 0;
Output:
28 27 26 25 24 23 22
21 20 19 18 17 16
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
Given two numbers L and R, the task is to find the prime numbers between L and R.
Examples:
Input: L = 1, R = 10
Output: 2 3 5 7
Explanation:
Prime number between the 1 and 10 are 2, 3, 5, and 7
Input: L = 30, R = 40
Output: 31 37
Approach 1:
The idea is to iterate from in the range [L, R] and check if any number in the given
range is prime or not. If yes then print that number and check for the next number till
we iterate all the numbers.
Below is the implementation of the above approach:
C
C++
#include <stdio.h>
int i, j, flag;
if (i == 1 || i == 0)
continue;
// if i is prime or not
flag = 1;
// Iterate to check if i is prime
// or not
if (i % j == 0) {
flag = 0;
break;
if (flag == 1)
// Driver Code
int main()
{
// Given Range
int L = 1;
int R = 10;
// Function Call
primeInRange(L, R);
return 0;
Output
2 3 5 7
Input: N = 11
Output: No
Simple Solution: A simple solution is to create a sieve to store all the prime numbers
less than the number N. Then run a loop from 1 to N and check whether
and are both prime or not. If yes then print Yes, else No.
Efficient solution: Apart from 2, all of the prime numbers are odd. So it is not
possible to represent a prime number (which is odd) to be written as a sum of two odd
prime numbers, so we are sure that one of the two prime number should be 2. So we
have to check whether n-2 is prime or not. If it holds we print Yes else No.
For example, if the number is 19 then we have to check whether 19-2 = 17 is a prime
number or not. If 17 is a prime number then print yes otherwise print no.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
bool isPrime(int n)
{
if (n <= 1)
return false;
if (n % i == 0)
return false;
return true;
bool isPossible(int N)
{
// if the number is prime,
return true;
else
return false;
// Driver code
int main()
int n = 13;
if (isPossible(n))
else
Output:
Yes
Natural numbers include all positive integers from 1 to infinity. It does not include
zero (0). Given a number n, find the sum of the first n natural numbers. To calculate
the sum, we will use the recursive function recur_sum().
Examples:
Input: 3
Output: 6
Explanation: 1 + 2 + 3 = 6
Input: 5
Output: 15
Explanation: 1 + 2 + 3 + 4 + 5 = 15
Below is a C++ program to find the sum of natural numbers up to n using recursion:
C++
// using recursion
#include <iostream>
// n natural numbers
int recurSum(int n)
if (n <= 1)
return n;
// Driver code
int main()
{
int n = 5;
return 0;
Output
15
Iterative Approach: The iterative approach is discussed in Set 1 of this article. Here,
we have discussed the recursive approach.
Recursive Approach: To solve this problem recursively, the algorithm changes in the
way that calls the same function recursively and multiplies the result by the
number n. Follow the steps below to solve the problem:
If n is less than equal to 2, then multiply n by 1 and store the result in a vector.
Otherwise, call the function multiply(n, factorialRecursiveAlgorithm(n – 1)) to
find the answer.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
// Initialize carry
= digits[i] * n + carry;
while (carry) {
digits.push_back(carry % 10);
return digits;
}
vector<int> factorialRecursiveAlgorithm(
long int n)
if (n <= 2) {
return multiply(
n, factorialRecursiveAlgorithm(n - 1));
// Driver Code
int main()
{
long int n = 50;
vector<int> result
= factorialRecursiveAlgorithm(n);
return 0;
Output
30414093201713378043612608166064768844377641568960512000000000000
C++
#include <bits/stdc++.h>
return;
cout << temp; // printing each stored character while recurring back
int main()
reverse(a, 0, n);
return 0;
}
Output:
skeeG rof skeeG
Write a C++ program for a given two integers x and n, write a function to compute xn.
We may assume that x and n are small and overflow doesn’t happen.
Recommended Practice
Odd Game
Try It!
Examples :
Input : x = 2, n = 3
Output : 8
Input : x = 7, n = 2
Output : 49
Program to calculate pow(x, n) using Naive Approach:
A simple solution to calculate pow(x, n) would multiply x exactly n times. We can do
that by using a simple for loop
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
// Initialize result to 1
return pow;
// Driver code
int main(void)
int x = 2;
unsigned n = 3;
// Function call
return 0;
}
Output
8
Variadic templates are class or function templates, that can take any variable(zero or
more) number of arguments. In C++, templates can have a fixed number of
parameters only that have to be specified at the time of declaration. However, variadic
templates help to overcome this issue. Douglas Gregor and Jaakko Järvi came up with
this feature for C++.
Variadic arguments are very similar to arrays in C++. We can easily iterate through
the arguments, find the size(length) of the template, can access the values by an index,
and can slice the templates too.
So basically, Variadic function templates are functions that can take multiple numbers
of arguments.
Syntax:
template(typename arg, typename... args)
return_type function_name(arg var1, args... var2)
Note: The arguments must be put inside angular brackets.
Below is an example in C++ to show how we can use a variadic function template:
CPP
#include <iostream>
using namespace std;
void print()
// all of them.
// Driver code
int main()
print(1, 2, 3.14,
"number of arguments",
return 0;
Output
1
2
3.14
Pass me any number of arguments
I will print
Given two arrays arr1[] and arr2[] of length N and M respectively, the task is to
check if the two arrays are equal or not.
Note: Arrays are said to be equal if and only if both arrays contain the same elements
and the frequencies of each element in both arrays are the same.
Examples:
Input: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {5, 4, 3, 2, 1}
Output : Equal
Explanation: As both the arrays contain same elements.
Input: arr1[] = {1, 5, 2, 7, 3, 8}, arr2[] = {8, 2, 3, 5, 7, 1}
Output : Equal
C++
#include <bits/stdc++.h>
int n, int m)
{
if (n != m)
return false;
if (arr1[i] != arr2[i])
return false;
return true;
}
// Driver Code
int main()
int arr1[] = { 1, 2, 3, 4, 5 };
int arr2[] = { 5, 4, 3, 2, 1 };
// Function call
else
return 0;
Output
Equal
Time Complexity: O(N * logN)
Auxiliary Space: O(1)
Efficient Approach: The problem can be solved efficiently
using Hashing (unordered_map),
Use hashing to count the frequency of each element of both arrays. Then traverse
through the hashtables of the arrays and match the frequencies of the elements.
Follow the below mentioned steps to solve the problem:
Check if the length of both the arrays are equal or not
Create an unordered map and store all elements and frequency of elements
of arr1[] in the map.
Traverse over arr2[] and check if count of each and every element
in arr2[] matches with the count in arr1[]. This can be done by decrementing the
frequency while traversing in arr2[].
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
int n, int m)
if (n != m)
return false;
mp[arr1[i]]++;
if (mp.find(arr2[i]) == mp.end())
return false;
// If an element of arr2[] appears
if (mp[arr2[i]] == 0)
return false;
mp[arr2[i]]--;
return true;
// Driver Code
int main()
int arr1[] = { 1, 2, 3, 4, 5 };
int arr2[] = { 4, 3, 1, 5, 2 };
int N = sizeof(arr1) / sizeof(int);
// Function call
else
return 0;
Output
Equal
Given an array, write functions to find the minimum and maximum elements in it.
Example:
C++
// C++ program to find minimum (or maximum) element
// in an array.
#include <bits/stdc++.h>
int main()
cout << "Minimum element of array: " << getMin(arr, n) << " ";
return 0;
Output:
Minimum element of array: 1
Maximum element of array: 1234
Time Complexity: O(n)
Auxiliary Space: O(1), as no extra space is used
Recursive Solution
Example:
C++
Learn Data Structures & Algorithms with GeeksforGeeks
Output:
Min of array: 1
Max of array: 1234
Time Complexity: O(n)
Auxiliary Space: O(n), as implicit stack is used due to recursion
Using Library functions:
We can use min_element() and max_element() to find minimum and maximum of
array.
Example:
C++
#include <bits/stdc++.h>
int main()
return 0;
Output:
Minimum element of array: 1
Maximum element of array: 1234
Given an array, the task is to find the average of that array. Average is the sum of the
array elements divided by the number of elements.
Examples:
Input: arr[] = {1, 2, 3, 4, 5}
Output: 3
Sum of the elements is 1+2+3+4+5 = 15
and total number of elements is 5.
So average is 15/5 = 3
Input: arr[] = {5, 3, 6, 7, 5, 3}
Output: 4.83333
Sum of the elements is 5+3+6+7+5+3 = 29
and total number of elements is 6.
So average is 29/6 = 4.83333.
1. Iterative Approach
The iterative program is easy. We need to find the sum and divide the sum by the total
number of elements.
Approach
1. Iterate each element of an array using a loop.
2. Sum up each element of the array till we reach the end of the array.
3. Divide the sum by the total number of elements and return the average.
Below is the C++ program to find the average of that array using the Iterative approach:
C++
// C++ program to calculate average
// of array elements
#include <iostream>
using namespace std;
return (double)sum / n;
}
// Driver code
int main()
{
int arr[] = { 10, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
Output
6
Given two sorted arrays, the task is to merge them in a sorted manner.
Examples:
Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8}
Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}
Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8}
Output: arr3[] = {4, 5, 7, 8, 8, 9}
Recommended: Please solve it on “PRACTICE ” first, before moving on to the
solution.
Naive Approach:
It is the brute force method to do the same. Take all the elements of arr1 and arr2 in
arr3. Then simply sort the arr3.
The implementation of above approach is:
C++
//using maps
#include<bits/stdc++.h>
// Declaring a map.
for(auto j: mp)
// Driver Code
int main()
{
// Function call
return 0;
Output
Array after merging
1 2 3 4 5 6 7 8
Method 2 (O(n1 * n2) Time and O(n1+n2) Extra Space)
1. Create an array arr3[] of size n1 + n2.
2. Copy all n1 elements of arr1[] to arr3[]
3. Traverse arr2[] and one by one insert elements (like insertion sort) of
arr3[] to arr1[]. This step take O(n1 * n2) time.
We have discussed implementation of above method in Merge two sorted
arrays with O(1) extra space
Method 3 (O(n1 + n2) Time and O(n1 + n2) Extra Space)
The idea is to use Merge function of Merge sort.
1. Create an array arr3[] of size n1 + n2.
2. Simultaneously traverse arr1[] and arr2[].
Pick smaller of current elements in arr1[] and arr2[], copy this smaller
element to next position in arr3[] and move ahead in arr3[] and the
array whose element is picked.
3. If there are remaining elements in arr1[] or arr2[], copy them also in arr3[].
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
Learn Data Structures & Algorithms with GeeksforGeeks
Output
Array after merging
1 2 3 4 5 6 7 8
Output:
Array after merging
1 2 3 4 5 6 7 8
Time Complexity : O(n1 + n2)
Auxiliary Space : O(n1 + n2)
Method 4: Using Maps (O(nlog(n) + mlog(m)) Time and O(N) Extra
Space)
1. Insert elements of both arrays in a map as keys.
2. Print the keys of the map.
Below is the implementation of above approach.
CPP
//using maps
#include<bits/stdc++.h>
{
// Declaring a map.
for(auto j: mp)
}
// Driver Code
int main()
// Function call
return 0;
Output
1 2 3 4 5 6 7 8
C++ Program to Print a 2D Array
Last Updated : 19 Jul, 2022
Here we will see how to print a 2D array using a C++ program. Below are the
examples:
Input: {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
Output: 1 2 3
456
789
Input: {{11, 12, 13},
{14, 15, 16}}
Output: 11 12 13
14 15 16
There are 2 ways to print a 2D array in C++:
1. Using for loop.
2. Using range-based for loop.
Let’s start discussing each of these methods in detail.
C++
#include <iostream>
// Driver code
int main()
const int i = 3, j = 3;
// Declaring array
{7, 8, 9}};
return 0;
Output
1 2 3
4 5 6
7 8 9
Time Complexity: O(n*m) where n and m are dimensions of the array.
Auxiliary Space: O(1)
2. Using a Range-Based for loop
Instead of using for loop, this method will use a range-based for loop. Below is the C+
+ program to print a 2D array using a range-based for loop:
C++
// C++ program to print 2D
#include <iostream>
// Driver code
int main()
const int i = 3, j = 3;
{4, 5, 6},
{7, 8, 9}};
}
cout << endl;
Output
1 2 3
4 5 6
7 8 9
Given two arrays, find common elements between these two arrays using STL in C++.
Example:
Input:
arr1[] = {1, 45, 54, 71, 76, 12},
arr2[] = {1, 7, 5, 4, 6, 12}
Output: {1, 12}
Input:
arr1[] = {1, 7, 5, 4, 6, 12},
arr2[] = {10, 12, 11}
Output: {1, 4, 12}
Approach: Common elements can be found with the help
of set_intersection() function provided in STL.
Syntax:
set_intersection (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
// C++ program to find common elements
#include <bits/stdc++.h>
int main()
int arr2[] = { 1, 7, 5, 4, 6, 12 };
// Initialise a vector
// and an iterator
v.begin());
return 0;
Output:
First Array: 1 12 45 54 71 76
Second Array: 1 4 5 6 7 12
Common elements:
1, 12,
C++ Program To Remove Duplicates From
Sorted Array
Given a sorted array, the task is to remove the duplicate elements from the array.
Examples:
Input: arr[] = {2, 2, 2, 2, 2}
Output: arr[] = {2}
new size = 1
#include <iostream>
if (n == 0 || n == 1)
return n;
int temp[n];
int j = 0;
// current element
// stored previously
arr[i] = temp[i];
return j;
// Driver code
int main()
// RemoveDuplicates() returns
n = removeDuplicates(arr, n);
return 0;
Output:
1 2 3 4 5
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 2: (Constant extra space)
Just maintain a separate index for same array as maintained for different array in
Method 1.
C++
// duplicates in-place
#include<iostream>
if (n==0 || n==1)
return n;
// unique element
int j = 0;
// Doing same as done in Method 1
// index i.e. j
arr[j++] = arr[i];
return j;
// Driver code
int main()
4, 4, 5, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// size of array.
n = removeDuplicates(arr, n);
return 0;
Output:
1 2 3 4 5
Here we will see how to remove all the occurrences of an element in an array using a
C++ program. Below are the examples:
Input: {1, 4, 3, 6, 8, 3, 9, 10, 3, 3, 7}
target=3
Output: {1, 4, 6, 8, 9, 10, 7}
Input: {12, 11, 10, 17, 12, 4, 7, 12}
target=12
Output: {11, 10, 17, 4, 7}
There are 2 ways to remove all the occurrences of an element in an array in C++:
1. Brute Force Approach.
2. Optimized Approach (In-place Shifting).
Let’s start discussing each of these methods in detail.
1. Brute-force Approach
In this method, create another array and copy all elements except the target element.
Below is the C++ program to remove all the occurrences of an element in an array
using a brute-force approach:
C++
// occurrences
#include <iostream>
int target,
int n)
{
int cnt = 0;
// target element
if(arr[i] == target)
cnt++;
int ind = 0;
if(arr[i] != target)
{
new_arr[ind] = arr[i];
ind++;
int m = (sizeof(new_arr) /
sizeof(new_arr[0]));
return;
// Driver code
int main()
{
int arr[]={1, 4, 3, 6, 8,
3, 9, 10, 3, 3, 7};
int target = 3;
int n = (sizeof(arr) /
sizeof(arr[0]));
return 0;
Output
1 4 6 8 9 10 7
Time Complexity: O(n)
Space Complexity: O(n)
2. Optimized Approach (In-place Shifting)
In this method, shift the non-target element to the left side.
1. Check whether the current element is the target element or not.
2. If it is the target element increase the cnt variable.
3. After this element, all the non-target elements will shift left with the gap of (n-
cnt).
Below is the C++ program to remove all occurrences of an element from an array
using an optimized approach:
C++
// optimized approach
#include <iostream>
int target,
int n)
int cnt = 0;
if(arr[i] != target)
{
arr[i - cnt] = arr[i];
else
cnt++;
return;
// Driver code
int main()
{
9, 10, 3, 3, 7};
int target = 3;
int n = (sizeof(arr) /
sizeof(arr[0]));
return 0;
Output
1 4 6 8 9 10 7
Given an array of integers arr[] of size N and an integer, the task is to rotate the array
elements to the left by d positions.
Examples:
Input:
arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2
Output: 3 4 5 6 7 1 2
Input: arr[] = {3, 4, 5, 6, 7, 1, 2}, d=2
Output: 5 6 7 1 2 3 4
divBlock
Rotate Array
Try It!
Approach 1 (Using temp array): This problem can be solved using the below idea:
After rotating d positions to the left, the first d elements become the last d elements of
the array
First store the elements from index d to N-1 into the temp array.
Then store the first d elements of the original array into the temp array.
Copy back the elements of the temp array into the original array
Illustration:
Suppose the give array is arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2.
First Step:
=> Store the elements from 2nd index to the last.
=> temp[] = [3, 4, 5, 6, 7]
Second Step:
=> Now store the first 2 elements into the temp[] array.
=> temp[] = [3, 4, 5, 6, 7, 1, 2]
Third Steps:
=> Copy the elements of the temp[] array into the original array.
=> arr[] = temp[] So arr[] = [3, 4, 5, 6, 7, 1, 2]
Follow the steps below to solve the given problem.
Initialize a temporary array(temp[n]) of length same as the original array
Initialize an integer(k) to keep a track of the current index
Store the elements from the position d to n-1 in the temporary array
Now, store 0 to d-1 elements of the original array in the temporary array
Lastly, copy back the temporary array to the original array
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
int temp[n];
// of temp[]
int k = 0;
temp[k] = arr[i];
k++;
}
// Storing the first d elements of array arr[]
// into temp
temp[k] = arr[i];
k++;
arr[i] = temp[i];
// Driver code
int main()
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int d = 2;
// Function calling
Rotate(arr, d, N);
PrintTheArray(arr, N);
return 0;
Output
3 4 5 6 7 1 2
Time complexity: O(N)
Auxiliary Space: O(N)
Approach 2 (Rotate one by one): This problem can be solved using the below idea:
At each iteration, shift the elements by one position to the left circularly (i.e., first
element becomes the last).
Perform this operation d times to rotate the elements to the left by d position.
Illustration:
Let us take arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2.
First Step:
=> Rotate to left by one position.
=> arr[] = {2, 3, 4, 5, 6, 7, 1}
Second Step:
=> Rotate again to left by one position
=> arr[] = {3, 4, 5, 6, 7, 1, 2}
Rotation is done by 2 times.
So the array becomes arr[] = {3, 4, 5, 6, 7, 1, 2}
Follow the steps below to solve the given problem.
Rotate the array to left by one position. For that do the following:
Store the first element of the array in a temporary variable.
Shift the rest of the elements in the original array by one place.
Update the last index of the array with the temporary variable.
Repeat the above steps for the number of left rotations required.
Below is the implementation of the above approach:
C++
// d elements
#include <bits/stdc++.h>
int p = 1;
while (p <= d) {
arr[n - 1] = last;
p++;
// Driver code
int main()
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
int d = 2;
// Function calling
Rotate(arr, d, N);
printArray(arr, N);
return 0;
Output
3 4 5 6 7 1 2
Time Complexity: O(N * d)
Auxiliary Space: O(1)
Approach 3 (A Juggling Algorithm): This is an extension of method 2.
Instead of moving one by one, divide the array into different sets where the number of
sets is equal to the GCD of N and d (say X. So the elements which are X distance
apart are part of a set) and rotate the elements within sets by 1 position to the left.
Calculate the GCD between the length and the distance to be moved.
The elements are only shifted within the sets.
We start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store
temp at the right place.
Follow the below illustration for a better understanding
Illustration:
Each steps looks like following:
C++
// d elements
#include <bits/stdc++.h>
if (b == 0)
return a;
else
/* To handle if d >= n */
d = d % n;
while (1) {
int k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
arr[j] = temp;
int main()
int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
// Function calling
leftRotate(arr, 2, n);
printArray(arr, n);
return 0;
Output
3 4 5 6 7 1 2
Time complexity : O(N)
Auxiliary Space : O(1)
Approach 4 :
(Using Collections module )
Python module have module named “collections” which provides various data
structures. One of them is “deque“.
Deque is also known as double ended queue. Module also provides different in-
built methods. One of them is “rotate”.
To know more about DEQUE, click here.
C++14
#include <bits/stdc++.h>
#include <deque>
int main() {
int d = 2;
dq.pop_front();
dq.push_back(temp);
return 0;
Output
deque([3, 4, 5, 6, 7, 1, 2])
Given an array, the task is to copy these array elements into another array in reverse
array.
Examples:
Input: array: 1 2 3 4 5
Output: 5 4 3 2 1
Input: array: 10 20 30 40 50
Output: 50 40 30 20 10
Let len be the length of original array. We copy every element original_arr[i] to
copy_arr[n-i-1] to get reverse in copy_arr[].
C++
#include <stdio.h>
int i;
// Driver code
int main()
int copied_arr[len], i, j;
printf("
printArray(original_arr, len);
// Print the copied array
printf("
printArray(copied_arr, len);
return 0;
Output:
Original array: 1 2 3 4 5
Resultant array: 5 4 3 2 1
Given two N x M matrices. Find a N x M matrix as the sum of given matrices each
value at the sum of values of corresponding elements of the given two matrices. In
this article, we will learn about the addition of two matrices.
Recommended: Please solve it on “PRACTICE” first, before moving on to the
solution.
Approach
Algorithm
// of two matrices
#include <bits/stdc++.h>
#define N 4
int i, j;
// Driver code
int main()
int A[N][N] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
int B[N][N] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
int C[N][N];
int i, j;
add(A, B, C);
return 0;
Output
Result matrix is
2 2 2 2
4 4 4 4
6 6 6 6
8 8 8 8
The below program checks if two square matrices of size 4*4 are identical or not. For
any two matrices to be equal, the number of rows and columns in both the matrix
should be equal and the corresponding elements should also be equal.
Recommended: Please solve it on “PRACTICE” first, before moving on to the
solution.
C++
// C++ Program to check if two
#include <bits/stdc++.h>
#define N 4
// returns 0
int i, j;
if (A[i][j] != B[i][j])
return 0;
return 1;
}
int main()
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
if (areSame(A, B))
else
return 0;
}
Output:
Matrices are identical
Given a 2D square matrix, find the sum of elements in Principal and Secondary
diagonals. For example, consider the following 4 X 4 input matrix.
Input:
3
1 1 1
1 1 1
1 1 1
Output:
Principal Diagonal: 3
Secondary Diagonal: 3
Method 1 (Brute Force) :
In this method, we use two loops i.e. a loop for columns and a loop for rows and in the
inner loop we check for the condition stated above:
C++
// of diagonals
#include <bits/stdc++.h>
if (i == j)
principal += mat[i][j];
if ((i + j) == (n - 1))
secondary += mat[i][j];
}
// Driver code
int main()
{5, 6, 7, 8},
{1, 2, 3, 4},
{5, 6, 7, 8}};
printDiagonalSums(a, 4);
return 0;
Output:
Principal Diagonal:18
Secondary Diagonal:18
Time Complexity: O(N*N), as we are using nested loops to traverse N*N times.
Auxiliary Space: O(1), as we are not using any extra space.
C++
// An efficient C++ program to
#include <bits/stdc++.h>
int n)
principal += mat[i][i];
// Driver code
int main()
{5, 6, 7, 8},
{1, 2, 3, 4},
{5, 6, 7, 8}};
printDiagonalSums(a, 4);
return 0;
Output :
Principal Diagonal:18
Secondary Diagonal:18
C++ Program For Boundary Elements of a
Matrix
Last Updated : 17 Jan, 2023
Input:
1 2 3
5 6 7
1 2 3
Output:
1 2 3
5 7
1 2 3
Explanation:The boundary elements of the
matrix is printed.
Recommended PracticeBoundary Elements of MatrixTry It!
Approach: The idea is simple. Traverse the matrix and check for every element if
that element lies on the boundary or not, if yes then print the element else print the
space character.
Algorithm :
1. Traverse the array from start to end.
2. Assign the outer loop to point the row and the inner row to traverse the
elements of row.
3. If the element lies in the boundary of matrix, then print the element, i.e. if the
element lies in 1st row, 1st column, last row, last column
4. If the element is not boundary element print a blank space.
Implementation:
C++
// of matrix.
#include <iostream>
if (i == 0 || j == 0 ||
i == n - 1 || j == n - 1)
else
// Driver code
int main()
{5, 6, 7, 8},
{1, 2, 3, 4},
{5, 6, 7, 8}};
printBoundary(a, 4, 4);
return 0;
Output:
1 2 3 4
5 8
1 4
5 6 7 8
Complexity Analysis:
Time Complexity: O(n*n), where n is the size of array.
This is achieved by single traversal of the matrix.
Space Complexity: O(1).
Since a constant space is needed.
Finding sum of boundary elements
Given an matrix of size n x m. Find the sum of boundary elements of the matrix.
Boundary elements are those elements which is not surrounded by elements on all
four directions, i.e. elements in first row, first column, last row and last column.
Examples:
Input:
1 2 3 4
5 6 7 8
1 2 3 4
5 6 7 8
Output: 54
Explanation:The boundary elements of the matrix
1 2 3 4
5 8
1 4
5 6 7 8
Sum = 1+2+3+4+5+8+1+4+5+6+7+8 =54
Input:
1 2 3
5 6 7
1 2 3
Output: 24
Explanation:The boundary elements of the matrix
1 2 3
5 7
1 2 3
Sum = 1+2+3+5+7+1+2+3 = 24
Approach: The idea is simple. Traverse the matrix and check for every element if
that element lies on the boundary or not, if yes then add them to get the sum of all the
boundary elements.
Algorithm :
1. Create a variable to store the sum and Traverse the array from start to end.
2. Assign the outer loop to point the row and the inner row to traverse the
elements of row.
3. If the element lies in the boundary of matrix then add the element to the sum,
i.e. if the element lies in 1st row, 1st column, last row, last column
4. print the sum.
Implementation:
C++
// of matrix.
#include <iostream>
int m, int n)
{
long long int sum = 0;
if (i == 0)
sum += a[i][j];
else if (i == m - 1)
sum += a[i][j];
else if (j == 0)
sum += a[i][j];
else if (j == n - 1)
sum += a[i][j];
return sum;
}
// Driver code
int main()
{5, 6, 7, 8},
{1, 2, 3, 4},
{5, 6, 7, 8}};
sum;
return 0;
Output:
Sum of boundary elements is 54
The below program finds the transpose of A[][] and stores the result in B[][], we can
change N for a different dimension.
C++
// of a matrix
#include <bits/stdc++.h>
#define N 4
int B[][N])
int i, j;
B[i][j] = A[j][i];
// Driver code
int main()
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int B[N][N], i, j;
transpose(A, B);
cout <<"\n";
return 0;
Output
Result matrix is
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
The complexity of the above method
Time Complexity: O(N*N) as two nested loops are running.
Space Complexity: O(N*N) as 2d array is created to store transpose.
The below program finds the transpose of A[][] and stores the result in B[][].
C++
// of a matrix
#include <bits/stdc++.h>
#define M 3
#define N 4
// of A[][] in B[][]
int i, j;
// Driver code
int main()
{2, 2, 2, 2},
{3, 3, 3, 3}};
int B[N][M], i, j;
transpose(A, B);
{
for(j = 0; j < M; j++)
return 0;
Output
Result matrix is
1 2 3
1 2 3
1 2 3
1 2 3
The complexity of the above method
Time Complexity: O(N*M) as two nested loops are running.
Space Complexity: O(N*M) as 2d array is created to store transpose.
C++
#include <bits/stdc++.h>
#define N 4
swap(A[i][j], A[j][i]);
// Driver code
int main()
{3, 3, 3, 3},
{4, 4, 4, 4}};
transpose(A);
printf("\n");
return 0;
Output
Modified matrix is
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Linked List
Stack
Queue
Tree
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Trie
Segment Tree
Disjoint Set Union
Fenwick Tree
AVL Tree
Red-Black Tree
Advanced Data Structures
90% Refund on Courses
Share Your Experience
C++ Program for Diagonally Dominant Matrix
C++ Program to check Involutory Matrix
C++ Program for Identity Matrix
C++ Program to check idempotent matrix
Find trace of matrix formed by adding Row-major and Column-major order of same matrix
C++ Program to Check horizontal and vertical symmetry in binary matrix
C++ Program to Find difference between sums of two diagonals
C++ Program to Print matrix in snake pattern
C++ Program to check if a matrix is symmetric
C++ Program for Mirror of matrix across diagonal
C++ Program for Maximum and Minimum in a square matrix.
C++ Program to Interchange Diagonals of Matrix
C++ Program to Check if a given matrix is sparse or not
Multiply Two Matrices in C++
C++ Program to Rotate a Matrix by 180 degree
C++ Program To Find Normal and Trace of a Matrix
C++ Program For Row Wise Sorting in 2D Array
C++ Program for Kronecker Product of two matrices
C++ Program to Print matrix in antispiral form
DSA to DevelopmentCourse
90% Refund on Courses
Share Your Experience
C++ Program for Diagonally Dominant Matrix
C++ Program to check Involutory Matrix
C++ Program for Identity Matrix
C++ Program to check idempotent matrix
Find trace of matrix formed by adding Row-major and Column-major order of same matrix
C++ Program to Check horizontal and vertical symmetry in binary matrix
C++ Program to Find difference between sums of two diagonals
C++ Program to Print matrix in snake pattern
C++ Program to check if a matrix is symmetric
C++ Program for Mirror of matrix across diagonal
C++ Program for Maximum and Minimum in a square matrix.
C++ Program to Interchange Diagonals of Matrix
C++ Program to Check if a given matrix is sparse or not
Multiply Two Matrices in C++
C++ Program to Rotate a Matrix by 180 degree
C++ Program To Find Normal and Trace of a Matrix
C++ Program For Row Wise Sorting in 2D Array
C++ Program for Kronecker Product of two matrices
C++ Program to Print matrix in antispiral form
DSA to DevelopmentCourse
C++
#include <iostream>
#include <cmath>
double a[MAXN][MAXN];
double determinant(int n) {
int pivot = i;
pivot = j;
if (pivot != i) {
swap(a[i], a[pivot]);
det *= -1;
if (a[i][i] == 0) {
return 0;
det *= a[i][i];
for (int j = i + 1; j < n; j++) {
return det;
int main() {
int n = 4;
{3, 0, 0, 5},
{2, 1, 4, -3},
{1, 0, 5, 0}};
return 0;
Output
Determinant of the matrix is : 30
Time Complexity: O(n!).
Explanation: The time complexity of the getCofactor() function is O(N^2) as it
involves looping through all the elements of an N x N matrix. The time complexity of
the determinantOfMatrix() function can be calculated using the following recurrence
relation:
T(N) = N*T(N-1) + O(N^3)
The first term N*T(N-1) represents the time taken to calculate the determinant of the
(N-1) x (N-1) submatrices, and the second term O(N^3) represents the time taken to
calculate the cofactors for each element in the first row of the original matrix. Using
expansion by minors, we can calculate the determinant of an NxN matrix as a sum of
determinants of (N-1)x(N-1) matrices, each of which requires O(N^2) operations to
calculate the cofactors. Therefore, the time complexity of the determinantOfMatrix()
function is O(N!), which is the worst-case scenario where the matrix is a permutation
matrix.
The display() function has a time complexity of O(N^2) as it loops through all the
elements of the matrix to print them. The overall time complexity of the program is
dominated by the determinantOfMatrix() function, so the time complexity of the
program is O(N!).
Space Complexity: O(n*n) as temp matrix has been created.
Adjoint and Inverse of a Matrix
There are various properties of the Determinant which can be helpful for solving
problems related with matrices,
In Above Method Recursive Approach is discussed. When the size of matrix is
large it consumes more stack size
In this Method We are using the properties of Determinant. In this approach we are
converting the given matrix into upper triangular matrix using determinant properties
The determinant of upper triangular matrix is the product of all diagonal elementsFor
properties on determinant go through this website
https://cran.r-project.org/web/packages/matlib/vignettes/det-ex1.html
In this approach, we are iterating every diagonal element and making all the elements
down the diagonal as zero using determinant properties
If the diagonal element is zero then we will search next non zero element in the same
column
There exist two cases
Case 1:
If there is no non-zero element. In this case the determinant of matrix is zero
Case 2:
If there exists non-zero element there exist two cases
Case a:
if index is with respective diagonal row element. Using the determinant properties we
make all the column elements down to it as zero
Case b:
Here we need to swap the row with respective to diagonal element column and
continue the case ‘a; operation
Below is the implementation of the above approach:
C++
#include<iostream>
#include<cmath>
using namespace std;
int det = 0;
int submatrix[4][4];
if(n == 1){
return matrix[0][0];
else{
int subi = 0;
int subj = 0;
continue;
submatrix[subi][subj] = matrix[i][j];
subj++;
subi++;
return det;
int main(){
{3, 0, 0, 5},
{2, 1, 4, -3},
{1, 0, 5, 0}};
int n = 4;
cout<<"Determinant: "<<det<<endl;
return 0;
Output
Determinant of the matrix is : 30
Time complexity: O(n3)
Auxiliary Space: O(n)
Steps:
Start with the given matrix and initialize the determinant to 1.
Apply elementary row operations to transform the matrix into its row echelon
form, while keeping track of the determinant.
If any row interchange operations are performed, multiply the determinant by -1.
If any row has a leading coefficient of 0, the determinant is 0 and we can stop.
The determinant is the product of the diagonal entries in the row echelon form.
Return the determinant value.
C++
// of a matrix
int det = 0;
int sign = 1;
// Base Case
if (size == 1) {
det = matrix[0][0];
else if (size == 2) {
- (matrix[0][1] * matrix[1][0]);
}
else {
if (k == i) {
continue;
cofactor[sub_i][sub_j] = matrix[j][k];
sub_j++;
sub_i++;
sub_j = 0;
sign = -sign;
delete[] cofactor[j];
delete[] cofactor;
// Driver Code
int main()
matrix[0][0] = 1;
matrix[0][1] = 0;
matrix[0][2] = 2;
matrix[0][3] = -1;
matrix[1][0] = 3;
matrix[1][1] = 0;
matrix[1][2] = 0;
matrix[1][3] = 5;
matrix[2][0] = 2;
matrix[2][1] = 1;
matrix[2][2] = 4;
matrix[2][3] = -3;
matrix[3][0] = 1;
matrix[3][1] = 0;
matrix[3][2] = 5;
matrix[3][3] = 0;
int size = 4;
delete[] matrix[i];
delete[] matrix;
return 0;
Output
Determinant = 30
Time Complexity: O(n^3) where n is the number of rows (or columns) in the
matrix.
Auxiliary Space: O(1) as the matrix is modified in-place.
Approach Name: Cofactor Expansion
Steps:
1. Define a function to calculate the determinant of a matrix using cofactor
expansion.
2. Check if the matrix is a square matrix, if not return an error message.
3. If the matrix is 1×1, return the element.
4. If the matrix is 2×2, return the determinant using the formula ad-bc.
5. If the matrix is larger than 2×2, loop through the first row of the matrix and
calculate the cofactor for each element.
6. Multiply each cofactor by its corresponding element and the sign (+/-) of the
element.
7. Add the results of step 6 to get the determinant.
C++
Output
Determinant: 30
Time Complexity: O(n!)
Auxiliary Space: O(n^2)
Approach: Using the Laplace expansion method to calculate
the determinant of a matrix.
Steps:
1. Create a function that accepts a 2D array (matrix) and its size and perform the
following steps:
Check if the matrix is square. If not, return an error message.
Check if the size of the matrix is 1. If yes, return the single value as the
determinant.
Check if the size of the matrix is 2. If yes, calculate the determinant using the
formula and return the value.
If the size of the matrix is greater than 2, implement the Laplace expansion
method recursively.
1. Choose a row or column to perform the expansion on.
2. For each element in the chosen row/column, calculate its cofactor by
removing the corresponding row and column.
3. Multiply each cofactor by its corresponding element in the row/column and
its sign (+/-).
4. Add up all the results to obtain the determinant of the matrix.
Return the determinant value.
C++
#include <iostream>
// of a matrix
int det = 0;
int sign = 1;
// Base Case
if (size == 1) {
det = matrix[0][0];
else if (size == 2) {
- (matrix[0][1] * matrix[1][0]);
else {
if (k == i) {
continue;
cofactor[sub_i][sub_j] = matrix[j][k];
sub_j++;
sub_i++;
sub_j = 0;
sign = -sign;
delete[] cofactor[j];
delete[] cofactor;
return det;
// Driver Code
int main()
matrix[0][0] = 1;
matrix[0][1] = 0;
matrix[0][2] = 2;
matrix[0][3] = -1;
matrix[1][0] = 3;
matrix[1][1] = 0;
matrix[1][2] = 0;
matrix[1][3] = 5;
matrix[2][0] = 2;
matrix[2][1] = 1;
matrix[2][2] = 4;
matrix[2][3] = -3;
matrix[3][0] = 1;
matrix[3][1] = 0;
matrix[3][2] = 5;
matrix[3][3] = 0;
int size = 4;
delete[] matrix[i];
delete[] matrix;
return 0;
Output
Determinant: 30
#include<bits/stdc++.h>
// size n x n
int sum = 0;
return sqrt(sum);
// size n x n
int sum = 0;
sum += mat[i][i];
return sum;
// Driven code
int main()
{2, 2, 2, 2, 2},
{3, 3, 3, 3, 3},
{4, 4, 4, 4, 4},
{5, 5, 5, 5, 5}};
return 0;
Output :
Trace of matrix = 15
Normal of matrix = 16
Example
Input:
mat1[][] = {{1, 2},
{3, 4}}
mat2[][] = {{5, 6},
{7, 8}}
Multiplication of two matrices:
{{1*5 + 2*7 1*6 + 2*8},
{3*5 + 4*7 3*6 + 4*8}}
Output:
{{19, 22},
{43, 50}}
Recommended: Please solve it on “PRACTICE” first, before moving on to the
solution.
#include <bits/stdc++.h>
int rslt[R1][C2];
rslt[i][j] = 0;
}
cout << rslt[i][j] << "\t";
// Driver code
int main()
// values in MACROs)
int mat1[R1][C1] = { { 1, 1 }, { 2, 2 } };
int mat2[R2][C2] = { { 1, 1, 1 }, { 2, 2, 2 } };
if (C1 != R2) {
cout << "The number of columns in Matrix-1 must "
"Matrix-2"
<< endl;
<< endl;
exit(EXIT_FAILURE);
// Function call
mulMat(mat1, mat2);
return 0;
Output
Multiplication of given two matrices is:
3 3 3
6 6 6
Output:
4 1 2
7 5 3
8 9 6
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
Recommended: Please solve it on “PRACTICE ” first, before moving on to the
solution.
The idea is to use loops similar to the program for printing a matrix in spiral form.
One by one rotate all rings of elements, starting from the outermost. To rotate a ring,
we need to do following.
1) Move elements of top row.
2) Move elements of last column.
3) Move elements of bottom row.
4) Move elements of first column.
Repeat above steps for inner ring while there is an inner ring.
Below is the implementation of above idea.
C++
#include <iostream>
#define R 4
#define C 4
// mat[][] of size R x C.
// Initially, m = R and n = C
int mat[R][C])
i - iterator */
if (row + 1 == m ||
col + 1 == n)
break;
// row
curr = mat[row][i];
mat[row][i] = prev;
prev = curr;
row++;
curr = mat[i][n-1];
mat[i][n-1] = prev;
prev = curr;
n--;
/* Move elements of last row from
if (row < m)
curr = mat[m-1][i];
mat[m-1][i] = prev;
prev = curr;
m--;
if (col < n)
curr = mat[i][col];
mat[i][col] = prev;
prev = curr;
col++;
}
// Driver code
int main()
// Test Case 1
{5, 6, 7, 8},
// Test Case 2
{4, 5, 6},
{7, 8, 9}};
*/ rotatematrix(R, C, a);
return 0;
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and
show the resulting matrix.
Examples :
Input: 3 4 5 0
2 6 1 2
2 7 1 2
2 1 1 2
Output: 2 1 1 2
2 6 1 2
2 7 1 2
3 4 5 0
Input: 9 7 5 1
2 3 4 1
5 6 6 5
1 2 3 1
Output: 1 2 3 1
2 3 4 1
5 6 6 5
9 7 5 1
The approach is very simple, we can simply swap the elements of first and last row of
the matrix inorder to get the desired matrix as output.
Below is the implementation of the approach:
C++
#include <iostream>
#define n 4
int rows = n;
int t = m[0][i];
m[rows - 1][i] = t;
}
}
// Driver code
int main()
{4, 7, 6, 5},
{3, 2, 1, 8},
{9, 9, 7, 7}};
interchangeFirstLast(m);
Output :
9 9 7 7
4 7 6 5
3 2 1 8
8 9 7 6
Given a 4 x 4 matrix, the task is to interchange the elements of first and last columns
and show the resulting matrix.
Examples:
Input:
8 9 7 6
4 7 6 5
3 2 1 8
9 9 7 7
Output:
6 9 7 8
5 7 6 4
8 2 1 3
7 9 7 9
Input:
9 7 5 1
2 3 4 1
5 6 6 5
1 2 3 1
Output:
1 7 5 9
1 3 4 2
5 6 6 5
1 2 3 1
The approach is very simple, we can simply swap the elements of first and last
column of the matrix in order to get the desired matrix as output.
Below is the implementation of the above approach:
C++
#include <iostream>
#define n 4
int t = m[i][0];
m[i][n - 1] = t;
// Driver function
int main()
{4, 7, 6, 5},
{3, 2, 1, 8},
{9, 9, 7, 7}};
interchangeFirstLast(m);
Output:
6 9 7 8
5 7 6 4
8 2 1 3
7 9 7 9
Pointers are symbolic representations of addresses. They enable programs to simulate
call-by-reference as well as to create and manipulate dynamic data structures. Iterating
over elements in arrays or other data structures is one of the main use of pointers.
The address of the variable you’re working with is assigned to the pointer variable
that points to the same data type (such as an int or string).
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data
C++
#include <bits/stdc++.h>
void geeks()
{
int var = 20;
int* ptr;
ptr = &var;
// Driver program
int main()
geeks();
return 0;
}
Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20
#include <bits/stdc++.h>
// Pass-by-Value
int square1(int n)
// main()
cout << "address of n1 in square1(): " << &n << "\n";
n *= n;
return n;
void square2(int* n)
*n *= *n;
void square3(int& n)
{
// Address of n in square3() is the same as n3 in main()
n *= n;
void geeks()
// Call-by-Value
int n1 = 8;
int n2 = 8;
square2(&n2);
cout << "Square of n2: " << n2 << "\n";
int n3 = 8;
square3(n3);
// Driver program
Output
address of n1 in main(): 0x7fffa7e2de64
address of n1 in square1(): 0x7fffa7e2de4c
Square of n1: 64
No change in n1: 8
address of n2 in main(): 0x7fffa7e2de68
address of n2 in square2(): 0x7fffa7e2de68
Square of n2: 64
Change reflected in n2: 64
address of n3 in main(): 0x7fffa7e2de6c
address of n3 in square3(): 0x7fffa7e2de6c
Square of n3: 64
Change reflected in n3: 64
In C++, by default arguments are passed by value and the changes made in the called
function will not reflect in the passed variable. The changes are made into a clone
made by the called function. If wish to modify the original copy directly (especially in
passing huge object or array) and/or avoid the overhead of cloning, we use pass-by-
reference. Pass-by-Reference with Reference Arguments does not require any clumsy
syntax for referencing and dereferencing.
Function pointers in C
Pointer to a Function
Array Name as Pointers
An array name contains the address of the first element of the array which acts like a
constant pointer. It means, the address stored in the array name can’t be changed. For
example, if we have an array named val then val and &val[0] can be used
interchangeably.
C++
#include <bits/stdc++.h>
void geeks()
// Declare an array
ptr = val;
cout << ptr[0] << " " << ptr[1] << " " << ptr[2];
// Driver program
Output
Elements of the array are: 5 10 20
If pointer ptr is sent to a function as an argument, the array val can be accessed in a
similar fashion. Pointer vs Array
Pointer Expressions and Pointer Arithmetic
A limited set of arithmetic operations can be performed on pointers which are:
incremented ( ++ )
decremented ( — )
an integer may be added to a pointer ( + or += )
an integer may be subtracted from a pointer ( – or -= )
difference between two pointers (p1-p2)
(Note: Pointer arithmetic is meaningless unless performed on an array.)
C++
#include <bits/stdc++.h>
void geeks()
// Declare an array
int* ptr;
ptr = v;
ptr++;
// Driver program
Output
Value at ptr = 0x7ffe5a2d8060
Value at *ptr = 10
Value at ptr = 0x7ffe5a2d8064
Value at *ptr = 100
Value at ptr = 0x7ffe5a2d8068
Value at *ptr = 200
Advanced Pointer Notation
Consider pointer notation for the two-dimensional numeric arrays. consider the
following declaration
int nums[2][3] = { { 16, 18, 20 }, { 25, 26, 27 } };
In general, nums[ i ][ j ] is equivalent to *(*(nums+i)+j)
This declares an array with the literal representation for “geek”, and then a pointer to
its first element is assigned to ptr. If we imagine that “geek” is stored at the memory
locations that start at address 1800, we can represent the previous declaration as:
As pointers and arrays behave in the same way in expressions, ptr can be used to
access the characters of a string literal. For example:
char x = *(ptr+3);
char y = ptr[3];
Here, both x and y contain k stored at 1803 (1800+3).
Pointers to pointers
In C++, we can create a pointer to a pointer that in turn may point to data or another
pointer. The syntax simply requires the unary operator (*) for each level of indirection
while declaring the pointer.
char a;
char *b;
char ** c;
a = ’g’;
b = &a;
c = &b;
Here b points to a char that stores ‘g’ and c points to the pointer b.
Void Pointers
This is a special type of pointer available in C++ which represents the absence of
type. Void pointers are pointers that point to a value that has no type (and thus also an
undetermined length and undetermined dereferencing properties). This means that
void pointers have great flexibility as they can point to any data type. There is a
payoff for this flexibility. These pointers cannot be directly dereferenced. They have
to be first transformed into some other pointer type that points to a concrete data type
before being dereferenced.
C++
#include <bits/stdc++.h>
if (ptrsize == sizeof(char)) {
char* ptrchar;
ptrchar = (char*)data;
(*ptrchar)++;
<< "\n";
int* ptrint;
ptrint = (int*)data;
// Increase the int stored at *ptrchar by 1
(*ptrint)++;
<< "\n";
void geek()
// Declare a character
char c = 'x';
// Declare an integer
int i = 10;
// respectively
increase(&c, sizeof(c));
cout << "The new value of c is: " << c << "\n";
increase(&i, sizeof(i));
cout << "The new value of i is: " << i << "\n";
// Driver program
Output
*data points to a char
The new value of c is: y
*data points to an int
The new value of i is: 11
Invalid pointers
A pointer should point to a valid address but not necessarily to valid elements (like for
arrays). These are called invalid pointers. Uninitialized pointers are also invalid
pointers.
int *ptr1;
int arr[10];
int *ptr2 = arr+20;
Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds of
arr so it also becomes an invalid pointer. (Note: invalid pointers do not necessarily
raise compile errors)
NULL Pointers
A null pointer is a pointer that point nowhere and not just an invalid address.
Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
int *ptr2 = NULL;
Advantages of Pointers
Pointers reduce the code and improve performance. They are used to retrieve
strings, trees, arrays, structures, and functions.
Pointers allow us to return multiple values from functions.
In addition to this, pointers allow us to access a memory location in the computer’s
memory.
reating array of pointers in C++
Last Updated : 23 Jun, 2022
C++
// Driver Code
int main()
// of size = 5
p[i] = 10 * (i + 1);
*p++;
return 0;
Output
10
11
20
30
30
20
Dynamic 2D Array of Pointers in C++: A dynamic array of pointers is basically an
array of pointers where every array index points to a memory block. This represents a
2D view in our mind. But logically it is a continuous memory block.
Syntax:
<dataType> **<Pointer name> = new <dataType> *[<size>];
Example:
int **P = new int *[4];
Note: The *(asterisk) symbol defines the level of the pointer, one * means one level
of pointers, where ** implies two levels of pointers, and so on. Also, the level of the
pointer must be the same as the dimensional array you want to create dynamically.
Approach:
Create a 1D array of pointers.
Now, create the column as array of pointers for each row as:
P[0] = new int [3];
P[1] = new int [3];
P[2] = new int [3];
P[3] = new int [3];
The 1D array of pointers are pointing to a memory block(size is mentioned).
Basically, P[0], …, P[3] are pointing to a 1D array of integers.
Accessing the array elements:
*P is equal to P[0] which is the address of the 1st row, 1st column is &P[0]
[0] = 3000.
*(P + 1) is equal to ‘P‘ is 1000 + 1(sizeof int) = 1004 and * means dereferencing.
So the value stored at the address is printed i.e., *1004 = 4000.
*(P + 1) + 2 is same as above case but +2 means (&P[1] + 2) is equal to &P[1]
[2] = 4008.
*(*(P + 1) + 2) is same as above case but that first asterisk ‘*(….)’ means
dereferencing that address. Therefore, the result is equal to the value in &P[1]
[2] = *(4008) = 54.
Below is the C++ program to illustrate the above concepts:
C++
#include <iostream>
using namespace std;
// Driver Code
int main()
int N = 3;
// of size N
int x = 1;
// For multiplying
p[i][j] = 10 * x;
// *(*(p+i)+j) = 10 * x
Output
0x158de90
10
0x158de94
11
40
90
void Pointer in C
Last Updated : 09 Jan, 2024
A void pointer is a pointer that has no associated data type with it. A void pointer can
hold an address of any type and can be typecasted to any type.
Example of Void Pointer in C
C
int main()
int a = 10;
char b = 'x';
void* p = &a;
p = &b;
C
#include <stdio.h>
int main()
int a = 10;
printf("%d", *ptr);
return 0;
Output
Compiler Error: 'void*' is not a pointer-to-object type
The below program demonstrates the usage of a void pointer to store the address of an
integer variable and the void pointer is typecasted to an integer pointer and then
dereferenced to access the value. The following program compiles and runs fine.
C
int main()
int a = 10;
// location
printf("%d", *(int*)ptr);
return 0;
Output
10
Time Complexity: O(1)
Auxiliary Space: O(1)
2. The C standard doesn’t allow pointer arithmetic with void pointers. However,
in GNU C it is allowed by considering the size of the void as 1.
Example
The below C program demonstrates the usage of a void pointer to perform pointer
arithmetic and access a specific memory location. The following program compiles
and runs fine in gcc.
C
#include <stdio.h>
int main()
// elements
int a[2] = { 1, 2 };
// array 'a' to it
printf("%d", *(int*)ptr);
return 0;
Output
2
Time Complexity: O(1)
Auxiliary Space: O(1)
References in C++
Last Updated : 30 Mar, 2023
// use of references
#include <iostream>
int main()
int x = 10;
// ref is a reference to x.
int& ref = x;
ref = 20;
x = 30;
return 0;
Output:
x = 20
ref = 30
Applications of Reference in C++
There are multiple applications for references in C++, a few of them are mentioned below:
1. Modify the passed parameters in a function
2. Avoiding a copy of large structures
3. In For Each Loop to modify all objects
4. For Each Loop to avoid the copy of objects
1. Modify the passed parameters in a function:
If a function receives a reference to a variable, it can modify the value of the variable. For
example, the following program variables are swapped using references.
Example:
C++
#include <iostream>
using namespace std;
// references
first = second;
second = temp;
// Driver function
int main()
// Variables declared
int a = 2, b = 3;
// function called
swap(a, b);
// changes can be seen
return 0;
Output
3 2
2. Avoiding a copy of large structures:
Imagine a function that has to receive a large object. If we pass it without reference, a new
copy of it is created which causes a waste of CPU time and memory. We can use references
to avoid this.
Example:
struct Student {
string name;
string address;
int rollNo;
}
// using references
#include <iostream>
#include <vector>
// Driver code
int main()
// use reference
// Printing elements
return 0;
Output
15 25 35 45
4. For Each Loop to avoid the copy of objects:
We can use references in each loop to avoid a copy of individual objects when objects are
large.
Example:
C++
// copy of objects
#include <iostream>
#include <vector>
// Driver code
int main()
// Declaring vector
"geeksforgeeks write",
"geeksforgeeks ide" };
}
return 0;
Output
geeksforgeeks practice
geeksforgeeks write
geeksforgeeks ide
References vs Pointers
Both references and pointers can be used to change the local variables of one function inside
another function. Both of them can also be used to save copying of big objects when passed
as arguments to functions or returned from functions, to get efficiency gain. Despite the
above similarities, there are the following differences between references and pointers.
1. A pointer can be declared as void but a reference can never be void For example
int a = 10;
void* aa = &a; // it is valid
void& ar = a; // it is not valid
2. The pointer variable has n-levels/multiple levels of indirection i.e. single-pointer, double-
pointer, triple-pointer. Whereas, the reference variable has only one/single level of
indirection. The following code reveals the mentioned points:
3. Reference variables cannot be updated.
4. Reference variable is an internal pointer.
5. Declaration of a Reference variable is preceded with the ‘&’ symbol ( but do not read it as
“address of”).
Example:
C++
#include <iostream>
int main()
int i = 10;
// single pointer
int* p = &i;
// double pointer
int** pt = &p;
// triple pointer
// or point to.
int a = 5;
int& S = a;
int& S0 = S;
int& S1 = S0;
return 0;
Output
i = 10 p = 0x7ffecfe7c07c pt = 0x7ffecfe7c080 ptr =
0x7ffecfe7c088
a = 5 S = 5 S0 = 5 S1 = 5
Limitations of References
1. Once a reference is created, it cannot be later made to reference another object; it cannot
be reset. This is often done with pointers.
2. References cannot be NULL. Pointers are often made NULL to indicate that they are not
pointing to any valid thing.
3. A reference must be initialized when declared. There is no such restriction with pointers.
Due to the above limitations, references in C++ cannot be used for implementing data
structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions
and can be used to implement all data structures. References being more powerful in Java is
the main reason Java doesn’t need pointers.
1. Safer: Since references must be initialized, wild references like wild pointers are unlikely
to exist. It is still possible to have references that don’t refer to a valid location (See
questions 5 and 6 in the below exercise)
2. Easier to use: References don’t need a dereferencing operator to access the value. They
can be used like normal variables. The ‘&’ operator is needed only at the time of
declaration. Also, members of an object reference can be accessed with the dot operator
(‘.’), unlike pointers where the arrow operator (->) is needed to access members.
Together with the above reasons, there are a few places like the copy constructor argument
where a pointer cannot be used. Reference must be used to pass the argument in the copy
constructor. Similarly, references must be used for overloading some operators like ++.
Exercise with Answers
Question 1 :
C++
#include <iostream>
int& fun()
{
return x;
int main()
fun() = 30;
return 0;
Output
30
Question 2
C++
#include <iostream>
return 0;
Output:
./3337ee98-ae6e-4792-8128-7c879288221f.cpp: In function 'int main()':
./3337ee98-ae6e-4792-8128-7c879288221f.cpp:8:19: error: invalid
initialization of non-const reference of type 'int&' from an rvalue of
type 'int'
cout << fun(10);
^
./3337ee98-ae6e-4792-8128-7c879288221f.cpp:4:5: note: in passing
argument 1 of 'int fun(int&)'
int fun(int& x) { return x; }
Question 3
C++
#include <iostream>
{
char* temp = str1;
str1 = str2;
str2 = temp;
int main()
swap(str1, str2);
return 0;
Output
#include <iostream>
using namespace std;
int main()
int x = 10;
Output:
./18074365-ebdc-4b13-81f2-cfc42bb4b035.cpp: In function 'int main()':
./18074365-ebdc-4b13-81f2-cfc42bb4b035.cpp:8:11: error: cannot declare
pointer to 'int&'
int&* ptr1 = ptr;
Question 5
C++
#include <iostream>
int main()
Output:
timeout: the monitored command dumped core
/bin/bash: line 1: 34 Segmentation fault timeout 15s
./372da97e-346c-4594-990f-14edda1f5021 < 372da97e-346c-4594-990f-
14edda1f5021.in
Question 6
C++
#include <iostream>
int& fun()
int x = 10;
return x;
int main()
{
fun() = 30;
return 0;
Output
Prerequisites:
Pointers in C++
Function in C++
Pointers are symbolic representations of addresses. They enable programs to simulate
call-by-reference as well as to create and manipulate dynamic data structures. Iterating
over elements in arrays or other data structures is one of the main use of pointers.
The address of the variable you’re working with is assigned to the pointer variable
that points to the same data type (such as an int or string).
Syntax:
datatype *var_name;
Address of Function: We all know that every function’s code resides in memory, so
every function has an address like all other variables in the program. The name of a
function can be used to find the address of the function. We can get the address of a
function by just writing the function’s name without parentheses in the function.
To know more about this, refer to the article – address of the function.
Function Pointer in C++
The function pointer is used to point functions, similarly, the pointers are used to
point variables.
It is utilized to save a function’s address.
The function pointer is either used to call the function or it can be sent as an
argument to another function.
Syntax:
return_type (*FuncPtr) (parameter type, ....);
Similar to the pointer used with variables we perform referencing and dereferencing
with a function pointer.
Referencing: When pointer is allocated the address of the function to be associated
with it then this process is referred to as referencing.
Dereferencing: When we use the (*)operator to get the value stored in the pointer.
Syntax:
// Declaring
return_type (*FuncPtr) (parameter type, ....);
// Referencing
FuncPtr= function_name;
// Dereferencing
data_type x=*FuncPtr;
// Function Pointer
#include <iostream>
int main()
func = multiply;
cout << "The value of the product is: " << prod << endl;
return 0;
Output
The value of the product is: 30
In the above program, we are declaring a function multiply where we are multiplying
two elements a and b, then returning the result. But, rather than directly calling the
function we are using a function pointer prod which is doing the same work for us.
#include <iostream>
const int b = 2;
// as parameter
cout << "The value of the product is: " << funcptr()
<< endl;
}
// Driver Function
int main()
print(multiply);
return 0;
Output
The value of the product is: 30
C++ Pointers
Last Updated : 25 Oct, 2022
#include <bits/stdc++.h>
void geeks()
int* ptr;
ptr = &var;
// Driver program
int main()
geeks();
return 0;
Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20
#include <bits/stdc++.h>
// Pass-by-Value
int square1(int n)
// main()
return n;
void square2(int* n)
*n *= *n;
void square3(int& n)
n *= n;
void geeks()
// Call-by-Value
int n1 = 8;
int n2 = 8;
square2(&n2);
int n3 = 8;
square3(n3);
// Driver program
Output
address of n1 in main(): 0x7fffa7e2de64
address of n1 in square1(): 0x7fffa7e2de4c
Square of n1: 64
No change in n1: 8
address of n2 in main(): 0x7fffa7e2de68
address of n2 in square2(): 0x7fffa7e2de68
Square of n2: 64
Change reflected in n2: 64
address of n3 in main(): 0x7fffa7e2de6c
address of n3 in square3(): 0x7fffa7e2de6c
Square of n3: 64
Change reflected in n3: 64
In C++, by default arguments are passed by value and the changes made in the called
function will not reflect in the passed variable. The changes are made into a clone
made by the called function. If wish to modify the original copy directly (especially in
passing huge object or array) and/or avoid the overhead of cloning, we use pass-by-
reference. Pass-by-Reference with Reference Arguments does not require any clumsy
syntax for referencing and dereferencing.
Function pointers in C
Pointer to a Function
Array Name as Pointers
An array name contains the address of the first element of the array which acts like a
constant pointer. It means, the address stored in the array name can’t be changed. For
example, if we have an array named val then val and &val[0] can be used
interchangeably.
C++
#include <bits/stdc++.h>
void geeks()
// Declare an array
int* ptr;
ptr = val;
cout << ptr[0] << " " << ptr[1] << " " << ptr[2];
// Driver program
Output
Elements of the array are: 5 10 20
If pointer ptr is sent to a function as an argument, the array val can be accessed in a
similar fashion. Pointer vs Array
Pointer Expressions and Pointer Arithmetic
A limited set of arithmetic operations can be performed on pointers which are:
incremented ( ++ )
decremented ( — )
an integer may be added to a pointer ( + or += )
an integer may be subtracted from a pointer ( – or -= )
difference between two pointers (p1-p2)
(Note: Pointer arithmetic is meaningless unless performed on an array.)
C++
// C++ program to illustrate Pointer Arithmetic
#include <bits/stdc++.h>
void geeks()
// Declare an array
int* ptr;
ptr = v;
ptr++;
// Driver program
Output
Value at ptr = 0x7ffe5a2d8060
Value at *ptr = 10
Value at ptr = 0x7ffe5a2d8064
Value at *ptr = 100
Value at ptr = 0x7ffe5a2d8068
Value at *ptr = 200
This declares an array with the literal representation for “geek”, and then a pointer to
its first element is assigned to ptr. If we imagine that “geek” is stored at the memory
locations that start at address 1800, we can represent the previous declaration as:
As pointers and arrays behave in the same way in expressions, ptr can be used to
access the characters of a string literal. For example:
char x = *(ptr+3);
char y = ptr[3];
Here, both x and y contain k stored at 1803 (1800+3).
Pointers to pointers
In C++, we can create a pointer to a pointer that in turn may point to data or another
pointer. The syntax simply requires the unary operator (*) for each level of indirection
while declaring the pointer.
char a;
char *b;
char ** c;
a = ’g’;
b = &a;
c = &b;
Here b points to a char that stores ‘g’ and c points to the pointer b.
Void Pointers
This is a special type of pointer available in C++ which represents the absence of
type. Void pointers are pointers that point to a value that has no type (and thus also an
undetermined length and undetermined dereferencing properties). This means that
void pointers have great flexibility as they can point to any data type. There is a
payoff for this flexibility. These pointers cannot be directly dereferenced. They have
to be first transformed into some other pointer type that points to a concrete data type
before being dereferenced.
C++
#include <bits/stdc++.h>
{
if (ptrsize == sizeof(char)) {
char* ptrchar;
ptrchar = (char*)data;
(*ptrchar)++;
<< "\n";
int* ptrint;
ptrint = (int*)data;
<< "\n";
void geek()
// Declare a character
char c = 'x';
// Declare an integer
int i = 10;
// respectively
increase(&c, sizeof(c));
cout << "The new value of c is: " << c << "\n";
increase(&i, sizeof(i));
cout << "The new value of i is: " << i << "\n";
// Driver program
Output
*data points to a char
The new value of c is: y
*data points to an int
The new value of i is: 11
Invalid pointers
A pointer should point to a valid address but not necessarily to valid elements (like for
arrays). These are called invalid pointers. Uninitialized pointers are also invalid
pointers.
int *ptr1;
int arr[10];
int *ptr2 = arr+20;
Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds of
arr so it also becomes an invalid pointer. (Note: invalid pointers do not necessarily
raise compile errors)
NULL Pointers
A null pointer is a pointer that point nowhere and not just an invalid address.
Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
int *ptr2 = NULL;
Advantages of Pointers
Pointers reduce the code and improve performance. They are used to retrieve
strings, trees, arrays, structures, and functions.
Pointers allow us to return multiple values from functions.
In addition to this, pointers allow us to access a memory location in the computer’s
memory.
Functions in C++
Last Updated : 26 Dec, 2023
A function is a set of statements that takes input, does some specific computation, and
produces output. The idea is to put some commonly or repeatedly done tasks together
to make a function so that instead of writing the same code again and again for
different inputs, we can call this function.
In simple terms, a function is a block of code that runs only when it is called.
Syntax:
Syntax of Function
Example:
C++
#include <iostream>
if (x > y)
return x;
else
return y;
// returns integer
int main()
return 0;
Output
m is 20
Example:
C++
// an integer
Types of Functions
Types of Function in C++
2. Pass by Reference: Both actual and formal parameters refer to the same locations,
so any changes made inside the function are reflected in the actual parameters of
the caller.
Function Definition
Pass by value is used where the value of x is not modified using the function fun().
C++
#include <iostream>
void fun(int x)
// definition of
// function
x = 30;
int main()
{
int x = 20;
fun(x);
return 0;
Output
x = 20
#include <iostream>
int main()
int x = 20;
fun(&x);
return 0;
Output
x = 30
Actual and formal arguments will be Actual and formal arguments will be
created at created at
different memory location same memory location.
3. To declare a function that can only be called without any parameter, we should use
“void fun(void)“. As a side note, in C++, an empty list means a function can only be
called without any parameter. In C++, both void fun() and void fun(void) are same.
Main Function
The main function is a special function. Every C++ program must contain a function
named main. It serves as the entry point for the program. The computer will start
running the code from the beginning of the main function.
Types of Main Functions
1. Without parameters:
CPP
// Without Parameters
2. With parameters:
CPP
// With Parameters
The reason for having the parameter option for the main function is to allow input
from the command line. When you use the main function with parameters, it saves
every group of characters (separated by a space) after the program name as elements
in an array named argv.
Since the main function has the return type of int, the programmer must always have a
return statement in the code. The number that is returned is used to inform the calling
program what the result of the program’s execution was. Returning 0 signals that there
were no problems.
C++ Recursion
When function is called within the same function, it is known as recursion in C++.
The function which calls the same function, is known as recursive function.
A function that calls itself, and doesn’t perform any task after function call, is known
as tail recursion. In tail recursion, we generally call the same function with return
statement.
Syntax:
C++
recursionfunction()
#include <iostream>
int main()
min = arr[i];
cout << "Minimum element is: " << min << "\n";
Output
Minimum element is: 10
// vary
#include <iostream>
class Cal {
public:
return a + b + c;
};
int main(void)
{
Cal C; // class object declaration.
return 0;
Output
30
55
// arguments.
#include <iostream>
int main()
return 0;
Output
r1 is : 42
r2 is : 0.6
#include <iostream>
void fun(int);
void fun(float);
void fun(float j)
int main()
fun(12);
fun(1.2);
return 0;
#include <iostream>
void fun(int);
int main()
fun(12);
return 0;
The above example shows an error “call of overloaded ‘fun(int)’ is ambiguous“. The
fun(int a, int b=9) can be called in two ways: first is by calling the function with one
argument, i.e., fun(12) and another way is calling the function with two arguments,
i.e., fun(4,5). The fun(int i) function is invoked with one argument. Therefore, the
compiler could not be able to select among fun(int i) and fun(int a,int b=9).
Function with Pass By Reference:-
C++
#include <iostream>
void fun(int);
void fun(int&);
int main()
int a = 10;
return 0;
void fun(int& b)
#include <iostream>
class Largest {
int a, b, m;
public:
void set_data();
};
void Largest::set_data()
cin >> a;
cin >> b;
void find_max(Largest t)
t.m = t.a;
else
t.m = t.b;
}
int main()
Largest l;
l.set_data();
find_max(l);
return 0;
Output
Enter the first number : 789
Enter the second number : 982
Largest number is 982
‘this’ pointer in C++
Last Updated : 09 Aug, 2019
To understand ‘this’ pointer, it is important to know how objects look at functions and
data members of a class.
1. Each object gets its own copy of the data member.
2. All-access the same function definition as present in the code segment.
Meaning each object gets its own copy of data members and all objects share a single
copy of member functions.
Then now question is that if only one copy of each member function exists and is used
by multiple objects, how are the proper data members are accessed and updated?
The compiler supplies an implicit pointer along with the names of the functions as
‘this’.
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function
calls and is available as a local variable within the body of all nonstatic
functions. ‘this’ pointer is not available in static member functions as static member
functions can be called without any object (with class name).
For a class X, the type of this pointer is ‘X* ‘. Also, if a member function of X is
declared as const, then the type of this pointer is ‘const X *’ (see this GFact)
In the early version of C++ would let ‘this’ pointer to be changed; by doing so a
programmer could change which object a method was working on. This feature was
eventually removed, and now this in C++ is an r-value.
C++ lets object destroy themselves by calling the following code :
delete this;
As Stroustrup said ‘this’ could be the reference than the pointer, but the reference was
not present in the early version of C++. If ‘this’ is implemented as a reference then,
the above problem could be avoided and it could be safer than the pointer.
Following are the situations where ‘this’ pointer is used:
1) When local variable’s name is same as member’s name
#include<iostream>
class Test
private:
int x;
public:
this->x = x;
};
int main()
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
Output:
x = 20
For constructors, initializer list can also be used when parameter name is same as
member’s name.
Test& Test::func ()
// Some processing
return *this;
When a reference to a local object is returned, the returned reference can be used
to chain function calls on a single object.
#include<iostream>
class Test
private:
int x;
int y;
public:
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
Output:
x = 10 y = 20
Exercise:
Predict the output of following programs. If there are compilation errors, then fix
them.
Question 1
#include<iostream>
class Test
private:
int x;
public:
Test(int x = 0) { this->x = x; }
};
int main()
Test obj(5);
obj.change(ptr);
obj.print();
return 0;
Question 2
#include<iostream>
class Test
private:
int x;
int y;
public:
};
int main()
Test obj;
obj.fun2();
return 0;
Question 3
#include<iostream>
private:
int x;
int y;
public:
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
Test obj1;
obj1.setX(10).setY(20);
obj1.print();
return 0;
Question 4
#include<iostream>
class Test
private:
int x;
int y;
public:
void setX(int a) { x = a; }
void setY(int b) { y = b; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
Test obj;
obj.destroy();
obj.print();
return 0;
Opaque as the name suggests is something we can’t see through. e.g. wood is opaque.
An opaque pointer is a pointer that points to a data structure whose contents are not
exposed at the time of its definition.
The following pointer is opaque. One can’t know the data contained in STest structure
by looking at the definition.
struct STest* pSTest;
It is safe to assign NULL to an opaque pointer.
pSTest = NULL;
~CImage();
// Opaque pointer
private:
void InitImageInfo();
};
Image.cpp: Code that will be shared across different endpoints. This file is used to
define the constructor and destructor of CImage class. The constructor will call the
InitImageInfo() method and the code inside this method will be written in accordance
with the Operating System on which it will work on.
// Constructor for CImage
CImage::CImage() {
InitImageInfo();
}
CImage::~CImage()
{
// Destroy stuffs here
}
Image_windows.cpp : Code specific to Windows operating System will reside in this
file.
struct SImageInfo {
// Windows specific DataSet
};
void CImage::InitImageInfo()
{
pImageInfo = new SImageInfo;
// Initialize windows specific info here
}
void CImage::Rotate()
{
// Make use of windows specific SImageInfo
}
Image_apple.cpp : Code specific to Mac Operating System will reside in this file.
struct SImageInfo {
// Apple specific DataSet
};
void CImage::InitImageInfo()
{
pImageInfo = new SImageInfo;
1. Using string::size
The method string::size returns the length of the string, in terms of bytes.
Below is the implementation of the above method:
C++
// of a string
#include <iostream>
#include <string.h>
// Driver code
int main()
// String obj
Output
13
2. Using string::length
The method string::length returns the length of the string, in terms of bytes. Both
string::size and string::length are synonyms and return the exact same value.
Below is the implementation of the above method:
C++
// of a string
#include <iostream>
#include <string.h>
// Driver code
int main()
{
// String obj
return 0;
Output
13
The C library function size_t strlen(const char *str) computes the length of the string
str up to, but not including the terminating null character.
Below is the implementation of the above method:
C++
// of a string
#include <iostream>
#include <string.h>
using namespace std;
// Driver code
int main()
// String obj
return 0;
Output
13
Using the traditional method, initialize the counter equals 0 and increment the counter
from starting of the string to the end of the string (terminating null character).
Below is the implementation of the above method:
C++
// of a string
#include <iostream>
#include <string.h>
// Driver code
int main()
// String obj
// C-style string,
int i = 0;
while (str[i])
i++;
return 0;
Output
13
5. Using Loop
To initialize the counter equals 0 and increment the counter from starting of the string
to the end of the string (terminating null character).
Below is the implementation of the above method:
C++
// of a string
#include <iostream>
#include <string.h>
using namespace std;
// Driver code
int main()
int i;
// String obj
// C-style string,
Output
13
String class stores the characters as a sequence of bytes with the functionality of
allowing access to the single-byte character. There are several ways to access
substrings and individual characters of a string. The string class supports the
following functions for this purpose:
1. operator[]
2. at()
3. substr()
4. find()
5. find_first_of()
6. find_last_of()
Let’s start discussing each of these methods in detail.
operator[]
operator[] returns the reference to the character at the position specified as the
argument.
Syntax-
char& operator[](size_t pos);
Here,
pos is the index of the character to be searched.
Below is the C++ program to implement the operator[] function-
C++
// the operator[]
#include <iostream>
// Driver code
int main()
string str("GeeksforGeeks");
return 0;
C++
// at()
#include <iostream>
// Driver code
int main()
string s("GeeksForGeeks");
return 0;
C++
#include <iostream>
// Driver code
int main()
string s("GeeksForGeeks");
return 0;
Output
eeksF
find()
find() function is used to find the first occurrence of a substring in the specified string
being called upon.
It returns the index of the first occurrence of the substring in the string.
The default value of the starting position is 0.
If the substring is not found then the function returns -1.
Syntax-
size_t find (const string& str, size_t pos = 0);
size_t find (const char* s, size_t pos = 0);
Here,
str is the substring to be searched.
s is the C-style substring to be searched.
pos is the initial position from where to start string search. The default value is 0.
Below is the C++ program to implement the find() function-
C++
#include <iostream>
// Driver code
int main()
{
string s("GeeksForGeeks");
return 0;
Output
5
Time Complexity : O(N)
Space Complexity : O(1)
find_first_of()
find_first_of() function is used to find the first character that matches any of the
characters specified in the arguments. This function takes two arguments str and pos.
Syntax-
size_t find_first_of (const string& str, size_t pos = 0) const;
Here,
str is the string with characters to search for.
pos is the position of the first character in the string to be considered for search.
Below is the C++ program to implement find_first_of() function-
C++
#include <iostream>
int main()
string s("GeeksForGeeks");
return 0;
Output
4
find_last_of()
find_last_of() function is used for finding the location of last occurrence of the
specified characters from the given string.
Syntax-
find_last_of(char ch);
find_last_of(char ch, size_t position);
Here,
ch is the character to be searched in the string.
position is the index till where the search is to be performed.
Below is the C++ program to implement find_last_of() function-
C++
#include <iostream>
// Driver code
int main()
string s("GeeksForGeeks");
return 0;
Output
12
Here, we will find out the unicode code point at a given index using a C++ program.
Input:
arr = "geEKs"
Output:
The Unicode Code Point At 0 is = 71.
The Unicode Code Point At 1 is = 101.
The Unicode Code Point At 2 is = 69.
The Unicode Code Point At 3 is = 107.
The Unicode Code Point At 4 is = 83.
Approach:
If the array/string value is increased then it is not feasible to declare an individual
variable for the index. If the string size is decreased then the fixed variables can give
Out of Bound Error. To handle these situations we will use a for loop to traverse the
given string and print the corresponding code point.
Example:
C++
// at a given index
#include <iostream>
// Driver code
int main()
{
// define input array/string
int code;
// print arr
code = arr[i];
cout <<"\n The Unicode Code Point At "<<i<< " is = " << code;
return 0;
Output
Input String = GeEkS
The Unicode Code Point At 0 is 71
The Unicode Code Point At 1 is 101
The Unicode Code Point At 2 is 69
The Unicode Code Point At 3 is 107
The Unicode Code Point At 4 is 83
Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1.
Examples:
Input: grrksfoegrrks,
c1 = e, c2 = r
Output: geeksforgeeks
Input: ratul,
c1 = t, c2 = h
Output: rahul
Traverse through the string and check for the occurrences of c1 and c2. If c1 is found
then replace it with c2 and else if c2 is found replace it with c1.
C++
// and c2 with c1
#include <bits/stdc++.h>
string replace(string s,
char c1, char c2)
int l = s.length();
if (s[i] == c1)
s[i] = c2;
s[i] = c1;
return s;
}
// Driver code
int main()
string s = "grrksfoegrrks";
return 0;
Output
geeksforgeeks
Time Complexity: O(n)
Auxiliary Space: O(n), because the program creates a copy of string s.
The approach involves iterating over the input string character by character, and
replacing the characters as required. For each character, we check if it is equal to c1 or
c2, and replace it with the other character if needed. We use two temporary strings to
keep track of the replacement characters, and finally update the input string with the
modified string. This approach involves a single pass over the input string, and hence
has a time complexity of O(n), where n is the length of the input string.
Steps:
1. Define a function replaceChar that takes a string S and two characters c1 and
c2 as input.
2. Initialize two temporary strings s1 and s2 as empty strings.
3. Iterate over the characters in the input string S.
4. For each character c in S, check if c is equal to c1 or c2.
5. If c is equal to c1, append c2 to s1 and c1 to s2.
6. If c is equal to c2, append c1 to s1 and c2 to s2.
7. If c is neither equal to c1 nor c2, append c to both s1 and s2.
8. Update the input string S with s1.
C++
#include <iostream>
#include <string>
for (char c : S) {
if (c == c1) {
s1 += c2;
s2 += c1;
} else if (c == c2) {
s1 += c1;
s2 += c2;
} else {
s1 += c;
s2 += c;
S = s1;
int main() {
string S = "Omkhaz";
return 0;
Given two strings, how to check if the two strings are equal or not.
Examples:
Input : ABCD, XYZ
Output : ABCD is not equal to XYZ
XYZ is greater than ABCD
#include <iostream>
if (s1 != s2)
cout << s1 << " is not equal to " << s2 << endl;
cout << s1 << " is greater than " << s2 << endl;
else
cout << s2 << " is greater than " << s1 << endl;
else
// Driver code
int main()
string s1("Geeks");
string s2("forGeeks");
relationalOperation(s1, s2);
string s3("Geeks");
string s4("Geeks");
relationalOperation(s3, s4);
return 0;
Output
Geeks is not equal to forGeeks
forGeeks is greater than Geeks
Geeks is equal to Geeks
Time Complexity: O(min(n,m)) where n and m are the length of the strings.
Auxiliary Space: O(max(n,m)) where n and m are the length of the strings.
This is because when string is passed in the function it creates a copy of itself in stack.
std:: Compare()
CPP
#include <iostream>
using namespace std;
int x = s1.compare(s2);
if (x != 0) {
cout << s1
if (x > 0)
cout << s1
else
cout << s2
else
// Driver Code
int main()
string s1("Geeks");
string s2("forGeeks");
compareFunction(s1, s2);
string s3("Geeks");
string s4("Geeks");
compareFunction(s3, s4);
return 0;
Output
Geeks is not equal to forGeeks
forGeeks is greater than Geeks
Geeks is equal to Geeks
Time Complexity: O(min(n,m)) where n and m are the length of the strings.
Auxiliary Space: O(max(n,m)) where n and m are the length of the strings.
This is because when string is passed in the function it creates a copy of itself in stack.
Differences between C++ Relational operators and compare() :-
1. compare() returns an int, while relational operators return boolean value i.e. either
true or false.
2. A single Relational operator is unique to a certain operation, while compare() can
perform lots of different operations alone, based on the type of arguments passed.
3. We can compare any substring at any position in a given string using compare(),
which otherwise requires the long procedure of word-by-word extraction of string
for comparison using relational operators.
Example:-
Using compare()
// Compare 3 characters from 3rd position
// (or index 2) of str1 with 3 characters
// from 4th position of str2.
if (str1.compare(2, 3, str2, 3, 3) == 0)
cout<<"Equal";
else
cout<<"Not equal";
Using Relational operator
for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++)
{
if (s1[i] != s2[j])
break;
}
if (i == 6 && j == 7)
cout << "Equal";
else
cout << "Not equal";
String Concatenation in C++
Last Updated : 15 Sep, 2023
The string is a type of data structure used for storing characters. Concatenating strings in C+
+ is one of the most discussed topics related to strings. There are multiple methods to concat
strings using user-defined methods, and a couple of methods for the concatenation of strings
using pre-defined methods. Let’s check on all of these methods.
Here,
str: String to be appended.
Below is the C++ program for string concatenation using the append() function:
C++
#include <iostream>
// Driver code
int main()
init.append(add);
cout << init << endl;
return 0;
Output
#include <iostream>
// Driver code
int main()
{
string init("this is init");
return 0;
Output
#include <string.h>
// Driver code
int main()
strcat(init, add);
return 0;
Output
#include <iostream>
// Driver code
int main()
string output;
// from init
output += init[i];
// fromt add
output += add[i];
return 0;
Output
#include <iostream>
#include <string>
// Base class
class base
protected:
string &str2) = 0;
};
// Derive class
public:
string &str2)
{
string temp;
return temp;
};
// Driver code
int main()
derive obj;
// Print string
Output
#include <iostream>
#include <string.h>
// Base class
class Base {
public:
};
// Driver code
int main()
Base b;
myfun(b);
return 0;
Output
Given two binary strings, return their sum (also a binary string).
Example:
Input: a = "11", b = "1"
Output: "100"
We strongly recommend you to minimize your browser and try this yourself
first
The idea is to start from the last characters of two strings and compute the digit sum
one by one. If the sum becomes more than 1, then store carry for the next digits.
C++
// binary strings
#include <bits/stdc++.h>
string padding;
padding.push_back('0');
A = padding + A;
string res;
if (carry == '1')
else
// possible cases
if (carry == '1')
else
}
// This if condition solves 100 101 010
if (carry == '1')
else
if (carry == '1')
res.push_back(carry);
reverse(res.begin(), res.end());
// To remove leading zeroes
int index = 0;
res[index] == '0')
index++;
return (res.substr(index));
// Driver code
int main()
return 0;
Output:
10001
Remove Leading Zeros From String in C++
Last Updated : 14 Sep, 2022
Input : 000012356090
Output : 12356090
In this article, we will use two string functions i.e, string erase and stoi() to remove leading
zeros from the string.
1. Using String Erase Function
Count trailing zeros.
Use the string erase function to remove characters equal to the above count. Below is C++
implementation.
CPP
#include <iostream>
int i = 0;
i++;
str.erase(0, i);
return str;
// Driver code
int main()
string str;
str = "00000123569";
str = removeZero(str);
cout << str << endl;
return 0;
Output
123569
C++
#include <iostream>
int main()
{
string str;
str = "00000123569";
str = to_string(num);
return 0;
Output
lexicographical_compare in C++
Last Updated : 11 Mar, 2024
C++ STL offer many utilities to solve basic common life problems. Comparing values
are always necessary, but sometimes we need to compare the strings also. Therefore,
this article aims at explaining about “lexicographical_compare()” that allows
to compare strings. This function is defined in “algorithm” header. It has two
implementations. Syntax 1 : lexicographical_compare(iter1 beg1, iter1 end1, iter2
beg2, iter2 end2)
Template:
template
bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2,
iter2 end2)
Parameters :
beg1 : Input iterator to initial position of first sequence.
end1 : Input iterator to final position of first sequence.
Return value :
Returns a boolean true, if range1 is strictly lexicographically
smaller than range2 else returns a false.
CPP
// lexicographical_compare()
#include<iostream>
int main()
else
Return value :
Returns a boolean true, if range1 is strictly lexicographically
smaller
than range2 else returns a false.
CPP
// lexicographical_compare()
#include<iostream>
return tolower(s1)<tolower(s2);
int main()
else
else
{
cout << "geeksforgeeks is not lexicographically less ";
// lexicographical_compare()
#include<bits/stdc++.h>
char list[][100]={
{'a','b','a','c','u','s'},
{'a','p','p','l','e'},
{'c','a','r'},
{'a','b','b','a'}
};
// the smallest
strcpy(min,list[i]);
// prints "abacus"
cout<<min[i];
The reversing of a string is nothing but simply substituting the last element of a string
to the 1st position of the string.
// 'for' loop
#include <bits/stdc++.h>
int n = str.length();
// corners
// Driver program
int main()
reverseStr(str);
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
Using a first to last Approach with while loop
C++
#include <bits/stdc++.h>
int n = len-1;
int i = 0;
while(i<=n){
swap(str[i],str[n]);
n = n-1;
i = i+1;
// Driver program
int main()
reverseStr(str);
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
Using a Last to First Approach ‘for‘ Loop
C++
#include <bits/stdc++.h>
// Driver code
int main(void)
{
string s = "GeeksforGeeks";
reverse(s);
return (0);
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
Using a Last to First Approach ‘while’ Loop
C++
#include <bits/stdc++.h>
{
int len = str.length();
int n = len;
while(n--)
// Driver code
int main(void)
string s = "GeeksforGeeks";
reverse(s);
return (0);
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
1. Using recursion Function with two pointer approach
Recursion functions are used for iterating to different indexes of the string.
C++
// using recursion
#include <bits/stdc++.h>
if(n<=i){return;}
swap(str[i],str[n]);
reverseStr(str,n-1,i+1);
}
// Driver program
int main()
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
2. Using one pointer approach in recursion
Below is the implementation of the code:
C++
#include <iostream>
return;
i++;
getreverse(str, i);
int main()
getreverse(name, 0);
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
3. Using the inbuilt “reverse” Function
There is a direct function in the “algorithm” header file for doing reverse that saves
our time when programming.
// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin,
BidirectionalIterator end);
CPP
// reverse() function
#include <bits/stdc++.h>
int main()
// Reverse str[begin..end]
reverse(str.begin(), str.end());
cout << str;
return 0;
Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
4. Reverse a String Using the Constructor
Passing reverse iterators to the constructor returns us a reversed string.
CPP
#include <bits/stdc++.h>
int main()
return 0;
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
5. Using a Temporary String
CPP
// reversing of string
#include <bits/stdc++.h>
int main()
{
string str = "GeeksforGeeks";
int n = str.length();
string rev;
rev.push_back(str[i]);
return 0;
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
How could we get the reverse of a const string?
To get the reverse of a const string we have to first declare a ‘const string’ in a user-
defined function following which we have declared then use the following algorithm
for the calling of the desired objects.
“const reverseConstString = function(string) { return
string.split("").reverse().join("")”
Example:
C++
#include <bits/stdc++.h>
int n = strlen(str);
// corners
swap(rev[i], rev[j]);
return rev;
// Driver code
int main(void)
printf("%s", reverseConstString(s));
return (0);
Output
skeeGrofskeeG
Time Complexity: O(N)
Auxiliary Space: O(N)
Using Stack Data Structure
C++
#include <bits/stdc++.h>
int main()
string s = "GeeksforGeeks";
stack<char> st;
for (char x : s)
st.push(x);
while (!st.empty()) {
st.pop();
return 0;
Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
Using Vector Data Structure
C++
#include <bits/stdc++.h>
int main()
string s = "GeeksforGeeks";
int n=s.length();
vector<char> vec;
vec.push_back(s[i]);
for(auto i:vec){
cout<<i;
return 0;
}
Output
skeeGrofskeeG
Copy the string S to another string, say P, and then reverse the string S.
Now check if the string S is equal to the string P and then print “Yes“.
Otherwise, print “No“.
C++
#include <bits/stdc++.h>
string isPalindrome(string S)
// string S
string P = S;
// If S is equal to P
if (S == P) {
// Return "Yes"
return "Yes";
// Otherwise
else {
// return "No"
return "No";
// Driver Code
int main()
string S = "ABCDCBA";
cout << isPalindrome(S);
return 0;
Output
Yes
Complexity Analysis
Algorithm
Iterate over the range [0, N/2], using the variable i, and in each iteration check if
the character at index i and N-i-1 are not equal, then print “No” and break.
If none of the above cases satisfy, then print “Yes“.
C++
// is palindrome
string isPalindrome(string S)
// the S[N-i-1]
// Return No
return "No";
// Return "Yes"
return "Yes";
// Driver Code
int main()
string S = "ABCDCBA";
return 0;
Output
Yes
String str is given which contains lowercase English letters and spaces. It may contain
multiple spaces. Get the first letter of every word and return the result as a string. The
result should not contain any space.
Examples:
Input: str = "geeks for geeks"
Output: gfg
The idea is to traverse each character of string str and maintain a boolean variable,
which was initially set as true. Whenever we encounter space we set the boolean
variable is true. And if we encounter any character other than space, we will check the
boolean variable, if it was set as true as copy that charter to the output string and set
the boolean variable as false. If the boolean variable is set false, do nothing.
Algorithm:
1. Traverse string str. And initialize a variable v as true.
2. If str[i] == ' '. Set v as true.
3. If str[i] != ' '. Check if v is true or not.
a) If true, copy str[i] to output string and set v as false.
b) If false, do nothing.
C++
#include<bits/stdc++.h>
bool v = true;
v = true;
result.push_back(str[i]);
v = false;
return result;
// Driver code
int main()
return 0;
Output
gfg
Time Complexity: O(n)
Space Complexity: O(1), if space of storing resultant string is taken in account it will
be O(n).
Another Approach:
In this approach, we will first split the input string based on the spaces. The spaces in
the strings can be matched using a regular expression. The split strings are stored in an
array of strings. Then we can simply add the first character of each split string in the
result.
C++
// approach
#include <bits/stdc++.h>
char *p;
vector<string> s;
p = strtok(input, " ");
while (p != NULL)
s.push_back(p);
string charBuffer;
charBuffer += values[0];
return charBuffer;
}
// Driver code
int main()
return 0;
Output
gfg
Time Complexity: O(N + M), where n is the length of the input string and m is the
number of words.
Space Complexity: O(M + N)
Method: Using Recursion
C++
#include<bits/stdc++.h>
if (index == str.length())
return result;
result.push_back(str[index+1]);
}
// Driver code
int main()
return 0;
Output
gfg
std::string::insert() in C++
Last Updated : 10 Sep, 2018
#include <iostream>
#include <string>
str1.insert(6, str2);
// Driver code
int main()
insertDemo(str1, str2);
return 0;
Output:
Original String : Hello World!
Using insert : Hello GeeksforGeeks World!
Syntax 2: Inserts at most, str_num characters of str, starting with index str_idx.
string& string::insert (size_type idx, const string& str, size_type
str_idx,
size_type
str_num)
idx : is the index number where insertion is to be made.
str : is the string from which characters are to be picked to insert.
str_idx : is the index number in str.
str_num : is the number of characters to be inserted from str.
Returns *this.
Errors:
Throws out_of_range if idx > size().
Throws out_of_range if str_idx > str.size().
Throws length_error if the resulting size exceeds the maximum number
of characters.
#include <iostream>
#include <string>
// Driver code
int main()
insertDemo(str1, str2);
return 0;
Output:
Original String : Hello World!
Using insert : Hello Geeks World!
Syntax 3: Inserts the characters of the C-string cstr so that the new characters start
with index idx.
string& string::insert (size_ type idx, const char* cstr)
idx : is the index number where insertion is to be made.
*cstr : is the pointer to the C-string which is to be inserted.
Returns *this.
Errors:
Throws out_of_range if idx > size().
Throws length_error if the resulting size exceeds the maximum number
of characters.
Note: cstr may not be a null pointer (NULL).
#include <iostream>
#include <string>
// Driver code
int main()
insertDemo(str);
return 0;
Output:
Original String : GeeksforGeeks
Using insert : Geeks are forGeeks
Syntax 4: Inserts chars_len characters of the character array chars so that the new
characters start with index idx.
string& string::insert (size_type idx, const char* chars, size_type
chars_len)
idx : index number where insertion is to be made.
*chars : is the pointer to the array.
chars_len : is the number of characters to be inserted from character
array.
Returns : *this
Errors:
Throws out_of_range if idx > size().
Throws length_error if the resulting size exceeds the maximum number
of characters.
Note : chars must have at least chars_len characters.
// size_type chars_len)
#include <iostream>
#include <string>
// Driver code
int main()
insertDemo(str);
return 0;
Output:
Original String : GeeksforGeeks
Using insert : Geeks are here forGeeks
Syntax 5: Inserts num occurrences of character c at the position specified by idx.
string& string ::insert (size_type idx, size_type num, char c)
idx : is the index number where insertion is to be made.
c : is the character to be inserted.
num : is the number of repetition of character c
Returns : *this
Errors:
Throw out_of_range if idx > size().
Throw length_error if the resulting size exceeds the maximum number of
characters.
#include <iostream>
#include <string>
// 5 occurrences of '$'
str.insert(5, 5, '$');
// Driver code
int main()
string str("**********");
insertDemo(str);
return 0;
Output:
Original String : **********
Using insert : *****$$$$$*****
Syntax 6: Inserts num occurrences of character c at the position specified by iterator
pos.
void string ::insert (iterator pos, size_type num, char c)
pos : is the position of iterator.
c : is the character which is to be inserted.
Returns : *this
Errors:
Throws out_of_range if pos > size().
Throws length_error if the resulting size exceeds the maximum number
of characters.
#include <iostream>
#include <string>
// at position str.begin() + 5
str.insert(str.begin() + 5, 5, '$');
}
// Driver code
int main()
string str("**********");
insertDemo(str);
return 0;
Output:
Original String : **********
Using insert : *****$$$$$*****
Syntax 7: Inserts a copy of character c before the character to which iterator pos
refers.
iterator string ::insert (iterator pos, char c )
pos : is the position of iterator.
c : is the character which is to be inserted.
Returns : iterator pointing to the first character inserted.
Error:
Throws length_error if the resulting size exceeds the maximum number
of characters.
#include <string>
std::string::iterator pos;
// str.begin() + 5
pos = str.insert(str.begin()+5,'$');
}
// Driver code
int main()
string str("**********");
insertDemo(str);
return 0;
Output:
Original String : **********
Using insert : *****$*****
Value at Iterator returned : $
Syntax 8: Inserts all characters of the range [ beg,end ) before the character to which
iterator pos refers.
void string ::insert (iterator pos, InputIterator beg, InputIterator
end )
pos : is the iterator position.
beg, end : Input iterators to the initial and final positions in a
sequence.
Error:
Throws length_error if the resulting size exceeds the maximum number
of characters.
// CPP code for insertinsert (iterator pos, InputIterator beg,
// InputIterator end )
#include <iostream>
#include <string>
// at position str1.begin() + 6
}
// Driver code
int main()
insertDemo(str1, str2);
return 0;
Output:
Original String : Hello World!
Using insert : Hello forWorld!
Splitting a string by some delimiter is a very common task. For example, we have a
comma-separated list of items from a file and we want individual items in an array.
Almost all programming languages, provide a function split a string by some
delimiter.
In C++
Note: The main disadvantage of strtok() is that it only works for C
style strings.
Therefore we need to explicitly convert C++ string into a char
array.
Many programmers are unaware that C++ has two additional APIs
which are more elegant
and works with C++ string.
Method 1: Using stringstream API of C++
Prerequisite: stringstream API
Stringstream object can be initialized using a string object, it automatically tokenizes
strings on space char. Just like “cin” stream stringstream allows you to read a string
as a stream of words.
Some of the Most Common used functions of StringStream.
clear() — flushes the stream
str() — converts a stream of words into a C++ string object.
operator << — pushes a string object into the stream.
operator >> — extracts a word from the stream.
The code below demonstrates it.
C++
#include <bits/stdc++.h>
void simple_tokenizer(string s)
{
stringstream ss(s);
string word;
simple_tokenizer(a);
return 0;
Output : How
do
you
do!
Method 2: Using C++ find() and substr() APIs.
Prerequisite: find function and substr().
This method is more robust and can parse a string with any delimiter, not just
spaces(though the default behavior is to separate on spaces.) The logic is pretty simple
to understand from the code below.
C++
#include <bits/stdc++.h>
int start = 0;
{
// Takes C++ string with any separator
string a = "Hi$%do$%you$%do$%!";
tokenize(a, "$%");
return 0;
Output: Hi
do
you
do
!
Method 3: Using temporary string
If you are given that the length of the delimiter is 1, then you can simply use a temp
string to split the string. This will save the function overhead time in the case of
method 2.
C++
#include <iostream>
// If cur char is not del, then append it to the cur "word", otherwise
// you have completed the word, print it, and start a new word.
if(str[i] != del){
temp += str[i];
else{
temp = "";
}
int main() {
split(str, del);
return 0;
Output
geeks for geeks
Given a string, reverse it using stack. For example “GeeksQuiz” should be converted
to “ziuQskeeG”.
Following is simple algorithm to reverse a string using stack.
1) Create an empty stack.
2) One by one push all characters of string to stack.
3) One by one pop all characters from stack and put
them back to string.
Recommended Practice
// using stack
#include <bits/stdc++.h>
// A structure to represent
// a stack
class Stack
public:
int top;
unsigned capacity;
char* array;
};
stack->capacity = capacity;
stack->top = -1;
sizeof(char))];
return stack;
if (isFull(stack))
return;
stack->array[++stack->top] = item;
if (isEmpty(stack))
return -1;
return stack->array[stack->top--];
// a string
int n = strlen(str);
// to stack
int i;
for (i = 0; i < n; i++)
push(stack, str[i]);
str[i] = pop(stack);
// Driver code
int main()
reverse(str);
str;
return 0;
Output:
Reversed string is ziuQskeeG
C++ program to check whether a String is a
Pangram or not
Last Updated : 17 Mar, 2023
Given string str, the task is to check whether a string is pangram or not using in C++.
A string is a Pangram if the string contains all the English alphabet letters.
Examples:
Input: str = “We promptly judged antique ivory buckles for the next prize”
Output: Yes
Explanations: In the above string, str has all the English alphabet letters.
Input: str = “We promptly judged antique ivory buckles for the prize”
Output: No
C++
#include <bits/stdc++.h>
int index;
// If uppercase character,
// If lowercase character,
else
continue;
mark[index] = true;
// Return false
if (mark[i] == false)
return (false);
// Driver Code
int main()
if (checkPangram(str) == true)
printf("Yes");
else
printf("No");
return (0);
Output
Yes
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)
Method-2: Using STL
The transform() method of STL can be used to check whether the given string is
Pangram or not.
Syntax:
transform(s.begin(), s.end(), s.begin(), ::toupper);
Approach:
In order to check if the string contains all the alphabets of the English alphabet:
Step 1: Convert all the letters in the string to either uppercase or lowercase using the
transform() method of the STL library. This is done to avoid treating lowercase and
uppercase letters as different entities while checking for the presence of all 26 letters
of the English alphabet.
Step 2: Sort the string using the sort() method of the STL library. This step is required
to identify the distinct letters present in the string.
Step 3: Use the unique() method of the STL library to identify the unique letters
present in the sorted string. The unique() method rearranges the string such that all
the unique letters come first and returns an iterator to the position of the first non-
unique letter.
Step 4: Count the number of unique letters present in the string using the distance()
method of the STL library, which calculates the distance between two iterators.
Step 5: Check if the count of unique letters is equal to 26 (since there are 26 letters in
the English alphabet) or not. If the count is 26, then the given string is a pangram,
and the algorithm returns true. Otherwise, the given string is not a pangram, and the
algorithm returns false.
Note that space is also considered as a distinct entity, which is why the count is
checked against 27 instead of 26.
The time complexity of this algorithm is O(n log n), where n is the length of the input
string, since we are sorting the string using the sort() method. The space complexity is
O(n), since we are creating a new string to store the converted and sorted version of
the input string.
Below is the implementation of the above approach:
CPP
C++
#include <bits/stdc++.h>
string pangrams(string s)
// Initialization of count
int count = 0;
s.end(),
s.begin(),
::toupper);
sort(s.begin(), s.end());
count++;
// including space as a
// distinct character
if (count == 27)
return "Yes";
else
return "No";
// Driver code
int main()
"judged antique"
// Function Call
Output
Yes
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1)
C++ Conversion Programs
C++ Program For Binary To Decimal
Conversion
Last Updated : 04 Aug, 2023
The binary number system uses only two digits 0 and 1 to represent an integer and the
Decimal number system uses ten digits 0 to 9 to represent a number. In this article, we
will discuss the program for Binary to Decimal conversion in C++.
The below diagram explains how to convert ( 1010 ) to an equivalent decimal value.
Recommended Practice
Try It!
// to decimal
#include <iostream>
// to decimal
int binaryToDecimal(int n)
int num = n;
int dec_value = 0;
// 1, i.e 2^0
int base = 1;
while (temp) {
base = base * 2;
}
return dec_value;
// Driver code
int main()
Output
169
Complexity Analysis
#include <iostream>
#include <string>
// to decimal
int binaryToDecimal(string n)
string num = n;
int dec_value = 0;
int base = 1;
dec_value += base;
base = base * 2;
return dec_value;
// Driver code
int main()
Output
169
Complexity Analysis
C++
#include <bitset>
#include <iostream>
#include <string>
int main()
bitset<4> bits(binary_string);
unsigned long decimal_value = bits.to_ulong();
return 0;
Output
13
The problem is to convert the given binary number (represented as a string) to its
equivalent octal number. The input could be very large and may not fit even into an
unsigned long long int.
Examples:
Input: 110001110
Output: 616
Input: 1111001010010100001.010110110011011
Output: 1712241.26633
Simple Approach
The idea is to consider the binary input as a string of characters and then follow the
steps:
1. Get the length of the substring to the left and right of the decimal point(‘.’)
as left_len and right_len.
2. If left_len is not a multiple of 3 add a min number of 0’s in the beginning to make
the length of the left substring a multiple of 3.
3. If right_len is not a multiple of 3 add a min number of 0’s in the end to make the
length of the right substring a multiple of 3.
4. Now, from the left extract one by one substrings of length 3 and add its
corresponding octal code to the result.
5. If in between a decimal(‘.’) is encountered then add it to the result.
Below is the C++ program to implement the above approach:
C++
#include <bits/stdc++.h>
// octal
(*um)["000"] = '0';
(*um)["001"] = '1';
(*um)["010"] = '2';
(*um)["011"] = '3';
(*um)["100"] = '4';
(*um)["101"] = '5';
(*um)["110"] = '6';
(*um)["111"] = '7';
// of binary
int l = bin.size();
int t = bin.find_first_of('.');
int len_left = t != -1 ? t : l;
if (t != -1) {
createMap(&bin_oct_map);
int i = 0;
while (1) {
i += 3;
if (i == bin.size())
break;
if (bin.at(i) == '.') {
octal += '.';
i++;
}
// required octal number
return octal;
// Driver code
int main()
return 0;
Output
Octal number = 1712241.26633
The complexity of the above method
Time Complexity: O(n), where n is the length of the string.
Auxiliary space: O(1).
Optimized Approach
The steps for this approach are as follows:
1. Convert the given binary number into groups of three digits starting from the
rightmost side.
2. Convert each group of three digits to its corresponding octal digit.
3. Concatenate the octal digits obtained in step 2 to get the octal equivalent of the
given binary number.
Below is the C++ program to implement the above approach:
C++
// to octal
#include <cmath>
#include <iostream>
#include <string>
// octal
if (binary.find_first_not_of("01.") != string::npos) {
// to octal
int decimal = stoi(binary.substr(0, binary.find('.')),
nullptr, 2);
decimal /= 8;
// to octal
if (binary.find('.') != string::npos) {
octal += ".";
fractional *= 8;
octal += to_string((int)floor(fractional));
fractional -= floor(fractional);
}
return octal;
// Dtriver code
int main()
cout << "Octal equivalent of " << binary1 << " is "
cout << "Octal equivalent of " << binary2 << " is "
cout << "Octal equivalent of " << binary3 << " is "
cout << "Octal equivalent of " << binary4 << " is "
return 0;
Output
Octal equivalent of 110001110 is 616
Octal equivalent of 1111001010010100001 is 1712241
Octal equivalent of 11011.10 is 33.06314
Octal equivalent of 1002 is Invalid binary number
C++ Program For Octal To Decimal
Conversion
Last Updated : 03 Jul, 2023
Given an octal number as input, we need to write a program to convert the given octal
number into an equivalent decimal number.
Examples:
Input : 67
Output: 55
Input : 512
Output: 330
Input : 123
Output: 83
1. Simple Approach
The idea is to extract the digits of a given octal number starting from the rightmost
digit and keep a variable dec_value.
At the time of extracting digits from the octal number, multiply the digit with the
proper base (Power of 8) and add it to the variable dec_value.
In the end, the variable dec_value will store the required decimal number.
Example:
If the octal number is 67.
dec_value = 6*(8^1) + 7*(8^0) = 55
The below diagram explains how to convert an octal number (123) to an equivalent
decimal value:
Below is the implementation of the above idea.
C++
// to decimal
#include <iostream>
using namespace std;
// to decimal
int octalToDecimal(int n)
int num = n;
int dec_value = 0;
// i.e 8^0
int base = 1;
while (temp)
// it to dec_value
base = base * 8;
return dec_value;
// Driver code
int main()
Output
55
The complexity of the above method
Time complexity: O(logN) where N is the given number
Auxiliary space: O(1)
2. Using Predefined stoi() Function
Below is the C++ program for Octal to Decimal Conversion:
C++
// to decimal
#include <iostream>
int OctToDec(string n)
// Driver code
int main()
string n = "67";
return 0;
Output
55
The octal numbers are a base 8 number system that uses digits from 0-7 and the
decimal numbers are a base 10 numbers system that uses 10 digits from 0-9 to
represent any numeric value.
In this article, we will learn how to write a C++ program to convert a given decimal
number into an equivalent octal number. i.e. convert the number with base value 10 to
base value 8.
Algorithm to Convert Decimal Numbers to Octal in C++
1. Create an array to store the octal representation.
2. Run a loop till the number is not zero.
3. Extract the remainder by taking the mod of the number by 8 and store the
remainder in the array as an octal digit.
4. Update the number by dividing it by 8 in each iteration.
5. Print the array in reverse order.
The below diagram shows an example of converting the decimal number 33 to an
equivalent octal number.
#include <iostream>
// to octal
void decToOctal(int n)
int octalNum[100];
int i = 0;
while (n != 0) {
octalNum[i] = n % 8;
n = n / 8;
i++;
// reverse order
for (int j = i - 1; j >= 0; j--)
// Driver Code
int main()
int n = 33;
// Function Call
decToOctal(n);
return 0;
Output
41
Explanation
If the given decimal number is 33.
Step 1: Remainder when 33 is divided by 8 is 1. Therefore, arr[0] = 1.
Step 2: Divide 33 by 8. The new number is 33/8 = 4.
Step 3: Remainder, when 4 is divided by 8, is 4. Therefore, arr[1] = 4.
Step 4: Divide 4 by 8. The new number is 4/8 = 0.
Step 5: Since the number becomes = 0.
Stop repeating steps and print the array in reverse order. Therefore, the equivalent
octal number is 41.
C++ Program For Hexadecimal To Decimal
Conversion
Last Updated : 22 Aug, 2023
The hexadecimal numbers are base 16 numbers that use 16 symbols {0, 1, 2, 4, 5, 6, 7,
8, 9, A, B, C, D, E, F} to represent all digits. Here, (A, B, C, D, E, F) represents (10,
11, 12, 13, 14, 15). Decimal numbers are base 10 numbers with 10 symbols to
represent all digits.
In this article, we will learn to write a program in C++ to convert the hexadecimal
number into an equivalent decimal number.
Algorithm
Initialize a variable dec_value with 0 to store the decimal value.
Traverse the hexadecimal string from right to left and check,
If the current character is a number 0-9, convert it to its corresponding
integer by subtracting ‘0’ from its ASCII value.
If the character is a letter from ‘A’ to ‘F’, convert it to its corresponding
integer by subtracting ‘A’ from its ASCII value and adding 10 to it.
Multiply each digit of the hexadecimal number with the proper base (Power of 16)
and add it to the variable dec_value.
Update the base value in each iteration by multiplying it by 16.
After traversing all the digits of the hexadecimal number, the variable dec_value
will store the equivalent decimal number.
The below diagram explains how to convert a hexadecimal number (1AB) to an
equivalent decimal value:
C++ Program to Convert Hexadecimal Number to Decimal
Number
C++
// to decimal
#include <bits/stdc++.h>
// to decimal
// i.e 16^0
int base = 1;
int dec_val = 0;
// it to integral 10 - 15 by subtracting 55
}
return dec_val;
// Driver code
int main()
return 0;
Output
26
The hexadecimal numbers are base 16 numbers that use 16 symbols {0, 1, 2, 4, 5, 6, 7,
8, 9, A, B, C, D, E, F} to represent all digits. Here, (A, B, C, D, E, F) represents (10,
11, 12, 13, 14, 15). Decimal numbers are base 10 numbers with 10 symbols to
represent all digits.
In this article, we will learn to write a program in C++ to convert the hexadecimal
number into an equivalent decimal number.
Algorithm
Initialize a variable dec_value with 0 to store the decimal value.
Traverse the hexadecimal string from right to left and check,
If the current character is a number 0-9, convert it to its corresponding
integer by subtracting ‘0’ from its ASCII value.
If the character is a letter from ‘A’ to ‘F’, convert it to its corresponding
integer by subtracting ‘A’ from its ASCII value and adding 10 to it.
Multiply each digit of the hexadecimal number with the proper base (Power of 16)
and add it to the variable dec_value.
Update the base value in each iteration by multiplying it by 16.
After traversing all the digits of the hexadecimal number, the variable dec_value
will store the equivalent decimal number.
The below diagram explains how to convert a hexadecimal number (1AB) to an
equivalent decimal value:
C++ Program to Convert Hexadecimal Number to Decimal
Number
C++
// to decimal
#include <bits/stdc++.h>
// to decimal
// i.e 16^0
int base = 1;
int dec_val = 0;
// it to integral 10 - 15 by subtracting 55
}
return dec_val;
// Driver code
int main()
return 0;
Output
26
In this article, we will learn to write a C++ program to convert a decimal number into
an equivalent hexadecimal number. i.e. convert the number with base value 10 to base
value 16.
In the decimal system, we use ten digits (0 to 9) to represent a number, while in the
hexadecimal system, we use sixteen symbols (0 to 9 and A to F) to represent a
number.
Algorithm for Decimal to Hexadecimal Conversion
1. Initialize a character array hexaDeciNum to store the hexadecimal
representation.
2. Run a loop till n is non-zero.
3. Inside the loop,
1. Initialize an integer variable temp to store the remainder and a character
variable ch to store the converted hexadecimal character.
2. Find the remainder of the number by taking mod by 16 (base of the
hexadecimal system).
3. Check if temp < 10, convert it to the corresponding ASCII character for the
digit by adding 48 to the character, and store it in hexaDeciNum. (‘0’ to ‘9’ =>
ASCII 48 to 57).
4. Else, convert the current decimal number to the corresponding ASCII
character for the digit by adding 55 to the digit, and storing it in hexaDeciNum.
4. Update the number by dividing it by 16.
5. Print the character array in reverse order.
The below diagram shows an example of converting the decimal number 2545 to an
equivalent hexadecimal number.
C++ Program to Convert Decimal Number To Hexadecimal
C++
#include <iostream>
// to hexadecimal
void decToHexa(int n)
char hexaDeciNum[100];
int i = 0;
while (n != 0) {
int temp = 0;
temp = n % 16;
i++;
}
else {
i++;
n = n / 16;
// Driver code
int main()
{
int n = 2545;
decToHexa(n);
return 0;
Output
9F1
Explanation
If the given decimal number is 2545.
Step 1: Calculate the remainder when 2545 is divided by 16 is 1. Therefore, temp
= 1. As temp is less than 10. So, arr[0] = 48 + 1 = 49 = ‘1’.
Step 2: Divide 2545 by 16. The new number is 2545/16 = 159.
Step 3: Calculate the remainder when 159 is divided by 16 is 15. Therefore, temp
= 15. As temp is greater than 10. So, arr[1] = 55 + 15 = 70 = ‘F’.
Step 4: Divide 159 by 16. The new number is 159/16 = 9.
Step 5: Calculate the remainder when 9 is divided by 16 is 9. Therefore, temp = 9.
As temp is less than 10. So, arr[2] = 48 + 9 = 57 = ‘9’.
Step 6: Divide 9 by 16. The new number is 9/16 = 0.
Step 7: Since the number becomes = 0. Stop repeating steps and print the array in
reverse order. Therefore, the equivalent hexadecimal number is 9F1.
Complexity Analysis
Time complexity: O(log16n)
Auxiliary space: O(1)
Binary Numbers uses only 0 and 1 (base-2), while Decimal Number uses 0 to 9 (base-
10). In this article, we will learn to implement a C++ program to convert Decimal
numbers to Binary Numbers.
The below diagram shows an example of converting the decimal number 17 to an
equivalent binary number.
C++
#include <iostream>
// to binary
void decToBinary(int n)
int binaryNum[32];
int i = 0;
while (n > 0) {
// array
binaryNum[i] = n % 2;
n = n / 2;
i++;
// order
// Driver code
int main()
int n = 10;
decToBinary(n);
return 0;
Output
1010
Explanation
Complexity Analysis
In the below C++ program, a bitset of size 4 is created and initialized with 10. Now
the bitset binaryRepresentation will store the binary representation of 10.
C++
// bitset class
#include <bitset>
#include <iostream>
#include <math.h>
int main()
bitset<sz> binaryRepresentation(decimalNumber);
return 0;
Output
Binary representation: 1010
C++ Program For Boolean to String
Conversion
Last Updated : 04 Aug, 2023
In this article, we will see how to convert a boolean to a string using a C++ program.
In boolean algebra, there are only two values 0 and 1 which
represent False and True. Thus, boolean to string conversion can be stated as:
Boolean -> String
1 -> True
0 -> False
Example:
Input: 1
Output: True
Methods to Convert a Boolean to a String in C++
There are 2 ways to convert boolean to string in C++:
1. Using Customized Boolean To String Conversion Function.
2. Using Alphanumeric Boolean Values.
Let’s discuss each of these methods in detail.
#include <iostream>
using namespace std;
// into string
string btos(bool x)
if (x)
return "True";
return "False";
// Driver code
int main()
// for OR operation
cout << 1 << " || " << 0 << " is " << btos(1 || 0)
<< endl;
cout << 1 << " && " << 0 << " is " << btos(1 && 0)
<< endl;
return 0;
Output
1 || 0 is True
1 && 0 is False
Complexity Analysis
C++
// Driver code
int main()
return 0;
Output
Printing true value before boolalpha: 1
Printing true value after boolalpha: true
Complexity Analysis
There are situations, where we need to convert textual data into numerical values for various
calculations. In this article, we will learn how to convert strings to double in C++.
Methods to Convert String to Double
We can convert String to Double in C++ using the following methods:
1. Using stod() Function
2. Using stold() Function
3. Using atof() Function
Let’s discuss each of these methods in detail.
1. Using stod() Function
In C++, the stod() function performs a string to double conversion. It is a library function
defined inside <string.h> header file.
Syntax
double stod(const string& str, size_t* pos = 0);
Parameters
str: the string to convert.
pos: address of an integer to store the number of characters processed. This parameter can
also be a null pointer, in which case it is not used.
Return Value
Converted double value.
C++
#include <iostream>
// Driver code
int main()
double n1 = stod(s1);
double n2 = stod(s2);
return 0;
Output
49.12
Complexity Analysis
C++
#include <iostream>
// Driver code
int main()
return 0;
Output
49.12
Complexity Analysis
C++
#include <iostream>
using namespace std;
// Driver code
int main()
return 0;
Output
14.25
Complexity Analysis
Here, we will build a C++ program for double to string conversion using various
methods i.e.
1. Using to_string
2. Using stringstream
3. Using sprintf
4. Using lexical_cast
We will keep the same input in all the mentioned approaches and get an output
accordingly.
Input:
n = 456321.7651234
Output:
string: 456321.7651234
1. Using to_string
In C++, use std::to string to convert a double to a string. The required parameter is a
double value, and a string object containing the double value as a sequence of
characters is returned.
C++
#include <iostream>
#include <string.h>
int main()
double n = 456321.7651234;
string str = to_string(n);
return 0;
Output
String is: 456321.765123
2. Using stringstream
A double can also be converted into a string in C++ in different ways depending on
our requirements using ostringstream.
C++
#include <iostream>
#include <sstream>
#include <string>
int main()
{
ostringstream s;
double n = 2332.43;
s << n;
return 0;
Output
String is:2332.43
3. Using sprintf
By specifying the precision in sprintf, we can convert double to string or character
array with custom precision. We can use sprintf to add extra text (as required) to the
string at the same time.
C++
#include <cstring>
#include <iostream>
#include <string>
#define Max_Digits 10
int main()
double N = 1243.3456;
return 0;
Output
string is: 1243.345600
4. Using lexical_cast
The lexical cast is one of the best ways to convert double to string.
C++
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
int main()
double n = 432.12;
return 0;
Output
string is:432.12
In this article, we will learn how to convert strings to long in C++. For this
conversion, there are 3 ways as follows:
1. Using stol()
2. Using stoul()
3. Using atol()
Let’s start by discussing each of these methods in detail.
Example:
Input: s1 = “20”
s2 = “30”
Output: s1 + s2
long: 50
1. Using stol()
In C++, the stol() function performs a string to long conversion.
Syntax:
long int stol (const string& str, size_t* idx = 0, int base = 10)
Parameters:
str: It specifies a string object with the representation of an integral number.
idx: It specifies a Pointer to an object of type size_t, whose value is set by the
function to the position of the next character in str after the numerical value. The
parameter can also be a null pointer, in which case it is not used.
base: It specifies the numerical base to determine the number system in which the
characters are interpreted. If the base is 0, the base to be used is determined by the
format in the sequence. The default value is 10.
Below is the C++ program to string to long using stol():
C++
#include <iostream>
int main()
return 0;
Output
50
The time complexity is O(1).
The auxiliary space is also O(1).
2. Using stoul()
In C++ to convert a string into a long integer, there is a function called stoul().
The stoul() function performs a string to unsigned long conversion.
Syntax:
unsigned long stoul (const string& str, size_t* idx = 0, int base = 10);
Parameters:
str: String object with the representation of an integral number.
idx: Pointer to an object of type size_t, whose value is set by the function to the
position of the next character in str after the numerical value. This parameter can
also be a null pointer, in which case it is not used.
base: Numerical base (radix) that determines the valid characters and their
interpretation. If this is 0, the base used is determined by the format in the
sequence. Notice that by default this argument is 10, not 0.
Below is the C++ program to convert string to long using stoul():
C++
#include <iostream>
// Driver code
int main()
Output
50
The time complexity is O(1)
The auxiliary space is also O(1)
3. Using atol()
In C++, the atol() function translates a string and returns its equivalent integer value.
Syntax:
long int atol (const char * str)
Parameters: The function accepts one mandatory parameter str which is the
representation of an integral number.
Below is the C++ program to convert string to long using atol():
C++
#include <iostream>
// Driver code
int main()
{
cout << n;
return 0;
Output
123456654
Given a Long number N, the task is to convert the N to a string using C++.
Explanation:
Input: N = -10243213 // long input
Output: -10243213 // string output
Explanation: -10243213 is the string in the output.
Input: N = 42131983
Output: 42131983
Approach A
In this approach, we are converting every digit of the long to the char and appending it
to the resultant string.
Follow the steps below to solve the problem:
1. If a long number is negative, store the negative sign to any variable and make the
long number positive.
if (long_num < 0) {
signValue = "-";
long_num = -long_num; //converting number to positive value
}
2. Extract every digit from the long number one by one from the last and convert it to
the character and push it to the stack.
while (long_num > 0) {
#include <bits/stdc++.h>
stack<char> stringStack;
if (long_num < 0) {
signValue = "-";
long_num = -long_num;
stringStack.push(convertedDigit);
long_num /= 10;
while (!stringStack.empty()) {
long_to_string += stringStack.top();
stringStack.pop();
// singValue to it.
return signValue + long_to_string;
int main()
return 0;
Output
-10243213
Time Complexity & Space Complexity: O (Digit_count_of_long_number)
Approach B
C++ contains the stringstream class inside the <stream> library. We can create an
object of the stringstream class and insert the variable of any data type. It returns the
string object.
Create the object of stringstream class i.e. Stringstream stream;
Add long number to stream object i.e. stream << 43543422;
Get the string object from stream object using str() method i.e. long_to_string =
stream.str();
Example:
C++
// C++ program to demonstrate
// using stringstream
#include <iostream>
#include <sstream>
#include <string>
int main()
stringstream stream;
// str() method
long_to_string = stream.str();
return 0;
Output
43543422
Approach C
The c++ <string> library provides the std::to_string() method to convert the any
datatype to the string.
String long_to_string = to_string(76456474);
Example:
C++
#include <iostream>
#include <string>
int main()
string long_to_string;
long_to_string = to_string(long_num);
return 0;
Output
76456474
In this article, we will learn how to convert int to char in C++. For this conversion, there are
5 ways as follows:
1. Using typecasting.
2. Using static_cast.
3. Using sprintf().
4. Using to_string() and c_str().
5. Using stringstream.
Let’s start by discussing each of these methods in detail.
Examples:
Input: N = 65
Output: A
Input: N = 97
Output: a
1. Using Typecasting
Method 1:
1. Declaration and initialization: To begin, we will declare and initialize our integer with
the value to be converted.
2. Typecasting: It is a technique for transforming one data type into another. We are
typecasting integer N and saving its value in the data type char variable c.
3. Print the character: Finally, print the character using cout.
Below is the C++ program to convert int to char using typecasting:
C++
#include <iostream>
// Driver code
int main()
{
int N = 97;
return 0;
Output
a
The time complexity is O(1) and an auxiliary space is O(1).
Method 2:
1. Declaration and initialization: To begin, we will declare and initialize our integer with
the value to be converted.
2. Typecasting: Declare another variable as character c and assign the value of N to the C
3. Print the character: Finally, print the character using cout.
Below is the C++ program to convert int to char using typecasting:
C++
#include <iostream>
// Driver code
int main()
{
int N = 65;
char c = N;
cout << c;
return 0;
Output
2. Using static_cast
The integer can be converted to a character using the static_cast function. Below is the C++
program to convert int to char using static_cast:
C++
#include <iostream>
// Driver code
int main()
int N = 65;
char c = static_cast<char>(N);
cout << c;
return 0;
Output
3. Using sprintf()
Allot space for a single int variable that will be converted into a char buffer. It is worth
noting that the following example defines the maximum length Max_Digits for integer data.
Because the sprintf function sends a char string terminating with 0 bytes to the destination,
we add sizeof(char) to get the char buffer length. As a result, we must ensure that enough
space is set aside for this buffer.
Below is the C++ program to convert int to char using sprintf():
C++
#include <iostream>
#define Max_Digits 10
// Driver code
int main()
int N = 1234;
char n_char[Max_Digits +
sizeof(char)];
std::sprintf(n_char,
"%d", N);
std::printf("n_char: %s \n",
n_char);
return 0;
Output
n_char: 1234
C++
#include <iostream>
// Driver code
int main()
int N = 1234;
string t = to_string(N);
printf("n_char: %s \n",
n_char);
return 0;
Output
n_char: 1234
5. Using stringstream
A stringstream connects a string object to a stream, allowing you to read from it as if it were
a stream (like cin). Stringstream requires the inclusion of the sstream header file. The
stringstream class comes in handy when processing input.
Below is the C++ program to convert int to char using stringstream:
C++
// stringstream
#include <iostream>
#include <sstream>
// Driver code
int main()
int N = 1234;
std::stringstream t;
t << N;
t.str().c_str();
printf("n_char: %s \n",
n_char);;
return 0;
}
Output
n_char: 1234
C++
#include <iostream>
//Driver code
int main()
return 0;
}
Output
A
Time complexity: O(1).
Auxiliary space: O(1).
Steps:
1. Take an integer input from the user.
2. Check if the input value corresponds to a valid character in the ASCII table by checking
the range of the input value.
3. If the input value corresponds to a valid character, then add the corresponding offset value
of ‘0’ or ‘A’ (depending on the input) to the integer value to get the corresponding
character value.
4. Output the corresponding character.
C++
#include <iostream>
int main() {
char ch;
ch = num;
} else if(num >= 97 && num <= 122) {
ch = num;
} else {
return 0;
cout << "The corresponding character is: " << ch << endl;
num = 97;
ch = num;
ch = num;
} else {
return 0;
}
cout << "The corresponding character is: " << ch << endl;
return 0;
Output
Enter an integer: 65
The corresponding character is: A
Enter an integer: 97
The corresponding character is: a
Time Complexity: O(1), as there are no loops involved.
Auxiliary Space: O(1), as we are only using a single character variable to store the result.
Steps:
1. Calculate the number of digits in the input int value.
2. Iterate through the digits from right to left, extracting each digit and adding the ASCII
value of ‘0’ to convert it to a char.
3. Store the resulting char array in the provided output buffer.
C++
#include <iostream>
#include <cstring>
using namespace std;
int len = 0;
len++;
temp /= 10;
num /= 10;
result[len] = '\0';
}
int main() {
char result[100];
int_to_char(num, result);
return 0;
Output
12345
Here we will see how to convert char to int using a C++ program. There are 6 ways to
convert char to int in C++:
1. Using Typecasting.
2. Using static_cast.
3. Using sscanf().
4. Using stoi().
5. Using atoi().
6. Using string stream.
Let’s discuss each of these methods in detail.
1. Using Typecasting
Method 1:
1. Declare and initialize our character to be converted.
2. Typecast the character to convert character to int using int.
3. Print the integer using cout.
Below is the C++ program to convert char to int value using typecasting:
C++
#include <iostream>
// Driver code
int main()
char ch = 'A';
return 0;
Output
65
The time complexity is O(1) and The auxiliary space is also O(1)
If a numeric character needs to be typecasted into the integer value then either we can
subtract 48 or ‘0’ and then typecast the numeric character into int.
Below is the C++ program to convert char to integer value using typecasting:
C++
#include <iostream>
// Driver code
int main()
char ch = '5';
Output
5
5
Method 2:
1. Declare and initialize our character to be converted.
2. Declare another variable as int N and assign the character ch to the N.
3. Print the integer using cout.
Below is the C++ program to convert char to int value using typecasting:
C++
#include <iostream>
// Driver code
int main()
{
char ch = 'a';
int N = int(ch);
cout << N;
return 0;
Output
97
2. Using static_cast
The character can be converted to an integer using the static_cast function. Below is
the C++ program to convert char to int value using static_cast:
C++
#include <iostream>
// Driver code
int main()
{
char ch = 'A';
int N = static_cast<int>(ch);
cout << N;
return 0;
Output
65
3. Using sscanf
Reads data from s and stores it in the places specified by the additional arguments in
the parameter format. Below is the C++ program to convert char to int using sscanf():
C++
#include <iostream>
// Driver code
int main()
{
int x;
return 0;
Output
The integer value of x : 1234
4. Using stoi
The stoi() function in C++ converts a string to an integer value. Below is the C++
program to convert char to int using stoi():
C++
#include <iostream>
#include <string>
int main()
int x = stoi(s1);
return 0;
Output
The integer value of x : 45
5. Using atoi
If the execution is successful, the atoi() method returns the converted integer value. If
the given string cannot be converted to an integer, it will return 0. Below is the C++
program to convert char to int using atoi():
C++
#include <iostream>
int main()
int y = atoi(str);
return 0;
Output
The integer value of y :1234
6. Using stringstream
A stringstream connects a string object to a stream, allowing you to read from it as if
it were a stream (like cin). Stringstream requires the inclusion of the sstream header
file. The stringstream class comes in handy when processing input.
Below is the C++ program to convert char to int using string stream:
C++
#include <string>
#include <sstream>
// Driver code
int main()
stringstream string;
int n;
string >> n;
return 0;
Output
Integer value is: 5
#include <iostream>
//Driver code
int main()
return 0;
Output
97
Searching a number
Arrays
Searching
+2 more
Solve Problem
Example:
C++
// x in arr[]. If x is present
// otherwise return -1
#include <iostream>
int n, int x)
{
int i;
if (arr[i] == x)
return i;
return -1;
// Driver code
int main(void)
int x = 10;
// Function call
(result == -1) ?
cout << "Element is not present in array" :
result;
return 0;
Output
Element is present at index 3
The time complexity of the above algorithm is O(n).
The space complexity of the above algorithm is O(1) as no extra space is used.
Linear search is rarely used practically because other search algorithms such as the
binary search algorithm and hash tables allow significantly faster-searching
comparison to Linear search.
Improve Linear Search Worst-Case Complexity
1. if element Found at last O(n) to O(1)
2. It is the same as previous method because here we are performing 2 ‘if’ operations
in one iteration of the loop and in previous method we performed only 1 ‘if’
operation. This makes both the time complexities same.
Below is the implementation:
C++14
#include<bits/stdc++.h>
int search_Element)
int left = 0;
// left variable
if (arr[left] == search_Element)
{
position = left;
break;
// right variable
if (arr[right] == search_Element)
position = right;
break;
}
left++;
right--;
if (position == -1)
// Driver code
int main()
int search_element = 5;
// Function call
search(arr, search_element);
Output
Element found in Array at 5 Position with 1 Attempt
In this article, we will learn about the Binary Search algorithm and how to implement
it in a C++ program.
Binary Search is a search algorithm that is faster than the linear search algorithm.
Binary Search is used to search the position of the target element in a sorted array by
repeatedly dividing the search space in half. Binary search eliminates half portion of
the array with each comparison. It works in a time complexity of O(log n) where n is
the number of elements in the array.
How does Binary Search works?
The idea is to compare the middle element with the target value, if the middle element
is equal to the target value, the index of the middle element is the position of the target
value.
If the target value is smaller than the middle element, the target value is searched in
the left half of the current space and If the target value is greater than the middle
element, the target value is searched in the right half of the current space. This is done
until the target element is found if the element is present in the array.
Examples
Input: arr[] = {10, 20, 30, 50, 60, 80, 110, 130, 140, 170}, x = 110
Output: 6
Explanation: Element x is present at index 6.
Input: arr[] = {10, 20, 30, 40, 60, 110, 120, 130, 170}, x = 175
Output: -1
Explanation: Element x is not present in arr[].
Illustration of Binary Search Algorithm
// current sub-array
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
}
// If the base case is reached, the element is not
return -1;
// Driver code
int main(void)
// Element to be searched
int x = 10;
(result == -1)
Output
Element is present at index 3
Complexity Analysis
Time Complexity : O(log n)
Auxiliary Space : O(log n)
Binary Search Program in C++ (Iterative)
C++
#include <bits/stdc++.h>
// current sub-array
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
low = mid + 1;
else
high = mid - 1;
return -1;
// Driver code
int main(void)
// Element to be searched
int x = 10;
(result == -1)
return 0;
Output
Element is present at index 3
Complexity Analysis
Time Complexity : O(log n)
Auxiliary Space : O(1)
The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the
beginning. The algorithm maintains two subarrays in a given array.
The subarray which is already sorted.
Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending
order) from the unsorted subarray is picked and moved to the sorted subarray.
Flowchart of the Selection Sort:
Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
First pass:
For the first position in the sorted array, the whole array is traversed from index 0
to 4 sequentially. The first position where 64 is stored presently, after traversing
whole array it is clear that 11 is the lowest value.
64 25 12 22 11
Thus, replace 64 with 11. After one iteration 11, which happens to be the least
value in the array, tends to appear in the first position of the sorted list.
11 25 12 22 64
Second Pass:
For the second position, where 25 is present, again traverse the rest of the array in
a sequential manner.
11 25 12 22 64
After traversing, we found that 12 is the second lowest value in the array and it
should appear at the second place in the array, thus swap these values.
11 12 25 22 64
Third Pass:
Now, for third place, where 25 is present again traverse the rest of the array and
find the third least value present in the array.
11 22 64
12 25
While traversing, 22 came out to be the third least value and it should appear at
the third place in the array, thus swap 22 with element present at third position.
11 25 64
12 22
Fourth pass:
Similarly, for fourth position traverse the rest of the array and find the fourth least
element in the array
As 25 is the 4th lowest value hence, it will place at the fourth position.
11 22 25 64
12
Fifth Pass:
At last the largest value present in the array automatically get placed at the last
position in the array
The resulted array is the sorted array.
11 12 22 25 64
Approach:
Initialize minimum value(min_idx) to location 0
Traverse the array to find the minimum element in the array
While traversing if any element smaller than min_idx is found then swap both the
values.
Then, increment min_idx to point to next element
Repeat until array is sorted
Recommended PracticeSelection SortTry It!
C++
// selection sort
#include <bits/stdc++.h>
//Swap function
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
int i, j, min_idx;
// unsorted subarray
// unsorted array
min_idx = i;
min_idx = j;
swap(&arr[min_idx], &arr[i]);
int i;
int main()
selectionSort(arr, n);
printArray(arr, n);
return 0;
Output
Sorted array:
11 12 22 25 64
In this article, we will learn about the bubble sort algorithm and how to write the
bubble sort program in C. We will also look at the working of bubble sort in C and the
optimized C program that improves the performance of bubble sort.
What is Bubble Sort?
Bubble sort is a simple sorting algorithm that works by comparing the adjacent
elements in the list and swapping them if the elements are not in the specified order. It
is an in-place and stable sorting algorithm that can sort items in data structures such as
arrays and linked lists.
Bubble Sort Algorithm in C
The algorithm to sort data of the list in increasing order using bubble sort in C is:
Run two loops nested in one another.
The outer loop will run from i = 0 to i < n – 1, where n is the number of elements
in the list.
The inner loop will run from j = 0 to j < n – i – 1. It is because, after each iteration
of the outer loop, one element at the end (or at the start if the order is decreasing
order) will be in its right place so we can leave it as it is.
This process will be repeated till the conditions of the loop are satisfied.
For decreasing order,
The inner loop will run from j = i to j < n – 1.
We will compare the elements as arr[ j ] < arr[ j + 1 ].
Everything else will be the same.
Bubble Sort Program in C
C
#include <stdio.h>
// Swap function
arr[i] = arr[j];
arr[j] = temp;
}
int i, j;
// in place
swap(arr, j, j + 1);
{
int i;
printf("\n");
// Driver code
int main()
int arr[] = { 5, 1, 4, 2, 8 };
bubbleSort(arr, N);
printArray(arr, N);
return 0;
Output
Sorted array:
1 2 4 5 8
Complexity Analysis of Bubble Sort
Time Complexity: O(N2), where N is the number of items in the list.
Auxiliary Space: O(1)
Working of Bubble Sort in C
The Bubble sort algorithm works by comparing the adjacent elements and swapping
them if they are in the wrong order.
First Pass
Algorithm compares the first two elements
5 1 4 2 8
C
#include <stdbool.h>
#include <stdio.h>
// Swap function
int temp = a;
a = b;
b = temp;
// done
swapped = true;
if (swapped == false)
break;
int i;
// Driver code
int main()
int arr[] = { 5, 3, 1, 9, 8, 2, 4, 7 };
bubbleSort(arr, N);
printArray(arr, N);
return 0;
Output
Sorted array: 1 2 3 4 5 7 8 9
C++ Program For Merge Sort
Last Updated : 07 Mar, 2024
Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides the input
array into two halves, calls itself for the two halves, and then it merges the two sorted
halves. The merge() function is used for merging two halves. The merge(arr, l, m, r)
is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the
two sorted sub-arrays into one.
Pseudocode :
• Declare left variable to 0 and right variable to n-1
• Find mid by medium formula. mid = (left+right)/2
• Call merge sort on (left,mid)
• Call merge sort on (mid+1,right)
• Continue till left is less than right
• Then call merge function to perform merge sort.
Algorithm:
Step 1: Start
Step 2: Declare an array and left, right, mid variable
Step 3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
Step 4: Stop
See the following C implementation for details.
MergeSort(arr[], l, r)
If r > l
Find the middle point to divide the array into two halves:
middle m = l + (r – l)/2
Call mergeSort for first half:
Call mergeSort(arr, l, m)
Call mergeSort for second half:
Call mergeSort(arr, m + 1, r)
Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
How Merge sort Works?
To know the functioning of merge sort, lets consider an array arr[] = {38, 27, 43, 3, 9,
82, 10}
At first, check if the left index of array is less than the right index, if yes then
calculate its mid point
Now, as we already know that merge sort first divides the whole array iteratively
into equal halves, unless the atomic values are achieved.
Here, we see that an array of 7 items is divided into two arrays of size 4 and 3
respectively.
Now, again find that is left index is less than the right index for both arrays, if
found yes, then again calculate mid points for both the arrays.
Now, further divide these two arrays into further halves, until the atomic units of
the array is reached and further division is not possible.
After dividing the array into smallest units, start merging the elements again based
on comparison of size of elements
Firstly, compare the element for each list and then combine them into another list
in a sorted manner.
C++
#include <iostream>
// and rightArray[]
auto indexOfSubArrayOne = 0,
indexOfSubArrayTwo = 0;
// array[left..right]
if (leftArray[indexOfSubArrayOne] <=
rightArray[indexOfSubArrayTwo])
{
array[indexOfMergedArray] =
leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
else
array[indexOfMergedArray] =
rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
{
array[indexOfMergedArray] =
leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
indexOfMergedArray++;
array[indexOfMergedArray] =
rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
// of arr to be sorted */
// Returns recursively
return;
// UTILITY FUNCTIONS
cout<<endl;
// Driver code
int main()
printArray(arr, arr_size);
printArray(arr, arr_size);
return 0;
Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Time Complexity: O(n logn), Sorting arrays on different machines. Merge Sort is a
recursive algorithm and time complexity can be expressed as following recurrence
relation.
T(n) = 2T(n/2) + θ(n)
The above recurrence can be solved either using the Recurrence Tree method or the
Master method. It falls in case II of Master Method and the solution of the recurrence
is θ(nLogn). Time complexity of Merge Sort is θ(nLogn) in all 3 cases (worst,
average and best) as merge sort always divides the array into two halves and takes
linear time to merge two halves.
Auxiliary Space: O(n)
Space Complexity :
• In merge sort all elements are copied into an auxiliary array
• so N auxiliary space is required for merge sort.
Given a string of lowercase characters from ‘a’ – ‘z’. We need to write a program to print the
characters of this string in sorted order.
Examples:
Input: bbccdefbbaa
Output: aabbbbccdef
Input: geeksforgeeks
Output: eeeefggkkorss
Recommended Practice
Try It!
A simple approach will be to use sorting algorithms like quick sort or merge sort and sort
the input string and print it.
C++
// string of characters
#include<bits/stdc++.h>
// in sorted order
sort(str.begin(), str.end());
// Driver code
int main()
string s = "geeksforgeeks";
sortString(s);
return 0;
Output:
eeeefggkkorss
Time Complexity: O(n log n), where n is the length of string.
Space Complexity: O(1) as no extra space has been used.
An efficient approach will be to observe first that there can be a total of 26 unique
characters only. So, we can store the count of occurrences of all the characters from ‘a’ to ‘z’
in a hashed array. The first index of the hashed array will represent character ‘a’, second will
represent ‘b’ and so on. Finally, we will simply traverse the hashed array and print the
characters from ‘a’ to ‘z’ the number of times they occurred in input string.
Below is the implementation of above idea:
C++
// string of characters
#include<bits/stdc++.h>
// in sorted order
// initialized to zero.
// count of characters
charCount[str[i]-'a']++;
// characters
// Driver code
int main()
string s = "geeksforgeeks";
sortString(s);
return 0;
Output:
eeeefggkkorss
Given a 2D array, sort each row of this array and print the result.
Examples:
Input :
77 11 22 3
11 89 1 12
32 11 56 7
11 22 44 33
Output :
3 11 22 77
1 11 12 89
7 11 32 56
11 22 33 44
Input :
8 6 4 5
3 5 2 1
9 7 4 2
7 8 9 5
Output :
4 5 6 8
1 2 3 5
2 4 7 9
5 7 8 9
Method 1 (Using Bubble Sort): Start iterating through each row of the given 2D
array, and sort elements of each row using an efficient sorting algorithm
Implementation:
C++
Java
Python3
C#
Javascript
// C++ code to
#include<bits/stdc++.h>
using namespace std;
int r, int c)
// swapping of elements
// Driver code
int main()
{9, 5, 3, 2},
{6, 3, 1, 2}};
sortRowWise(m, r, c);
return 0;
Output
1 7 8 9
0 2 3 7
2 3 5 9
1 2 3 6
Time Complexity: O(r*c*max(r,c))
Auxiliary Space: O(1), since no extra space has been taken.
Method 2 (Using Library Function): The idea is to use Arrays.sort() for every row
of the matrix.
Implementation:
C++
Java
Python3
C#
Javascript
// matrix row-wise
#include <bits/stdc++.h>
#define M 4
#define N 4
// individual rows.
{
for (int j = 0; j < N; j++)
// Driver code
int main()
{7, 3, 0, 2},
{9, 5, 3, 2},
{6, 3, 1, 2}};
sortRowWise(m);
Output
1 7 8 9
0 2 3 7
2 3 5 9
1 2 3 6
Time Complexity: O(r*c*log(c))
Auxiliary Space: O(1)
C++ Program to Sort the Elements of an Array
in Ascending Order
Last Updated : 10 Jul, 2022
Here, we will see how to sort the elements of an array in ascending order using a C++
program. Below are the examples:
Input: 3 4 5 8 1 10
Output: 1 3 4 5 8 10
Input: 11 34 6 20 40 3
Output: 3 6 11 20 34 40
There are 2 ways to sort an array in ascending order in C++:
1. Brute-force Approach Using Bubble Sort.
2. Optimized Approach Using Quicksort.
Let’s start discussing these solutions.
#include <bits/stdc++.h>
// Driver code
int main()
// Initializing arrya
sizeof(nums[0]));
sort(nums, size_nums);
return 0;
// Sort function
bool isSwapped;
/**
previous one.
**/
isSwapped = false;
swapNums(num, j, (j - 1));
isSwapped = true;
}
if (!isSwapped)
break;
nums[first] = nums[second];
nums[second] = curr;
Output
Before sorting the array is:
1 12 6 8 10
#include <bits/stdc++.h>
// Driver code
int main()
{
int nums[] = {1, 6, 3, 10, 50};
sizeof(nums[0]));
return 0;
}
/**
numerical order.
*/
// Base Condition
return;
// These are just for swapping
// the elements.
start++;
end--;
// elements.
int x = nums[start];
nums[start] = nums[end];
nums[end] = x;
start++;
end--;
Output
Before sorting array is:
1 6 3 10 50
A structure is a user-defined data type in C/C++. A structure creates a data type that
can be used to group items of possibly different types into a single type.
How to pass structure as an argument to the functions?
Passing of structure to the function can be done in two ways:
By passing all the elements to the function individually.
By passing the entire structure to the function.
In this article, entire structure is passed to the function. This can be done using call
by reference as well as call by value method.
Examples 1: Using Call By Value Method
#include <bits/stdc++.h>
struct Distance {
int kilometer;
int meter;
};
Distance d;
// assigning value to new instance of structure
d.kilometer = d1.kilometer
+ d2.kilometer
+ (d1.meter + d2.meter)
/ 1000;
<< endl;
void initializeFunction()
Distance1.kilometer = 10;
Distance1.meter = 455;
Distance2.kilometer = 9;
Distance2.meter = 745;
// distance as parameters
TotalDistance(Distance1, Distance2);
}
// Driver code0
int main()
initializeFunction();
return 0;
Output:
Total distance:kilometer: 20
meter: 200
Examples 2: Using Call By Reference Method
#include <bits/stdc++.h>
int n;
};
n2.n++;
void initializeFunction()
number n1;
// assigning value to n
n1.n = 10;
cout << " number before calling "
increment(n1);
// Driver code
int main()
initializeFunction();
return 0;
Output:
number before calling increment function:10
number after calling increment function:11
How to return a structure from the functions?
To return a structure from a function the return type should be a structure only.
Examples:
#include <iostream>
#include <stdlib.h>
// required structure
struct Employee {
int Id;
string Name;
};
Employee data(Employee E)
E.Id = 45;
E.Name = "aman";
// returning structure
return (E);
// Driver code
int main()
{
// creating object of Employee
Employee Emp;
Emp = data(Emp);
return 0;
Output:
Employee Id: 45
Employee Name: aman
Arrays are used to store sets of data of similar data types at contiguous memory
locations. Unlike Arrays, Structures are user-defined data types that are used to store
groups of items of non-similar data types. Here, we are going to compile a C++
program that will store the information of the students in a Structure.
Information in Structure
1. For a Student
Below is the implementation of the topic:
C++
#include <bits/stdc++.h>
struct student {
// Student Name
string name;
string rollno;
// Subjects Enrolled(Array)
vector<string> subjects;
vector<int> marks;
// Student's CGPA
float cgpa;
};
// Function to print a vector(for more
// vector" at GFG)
void printStudent(student* s)
{
printv(s->subjects);
printv(s->marks);
// Driver Code
int main()
// New Student
student s;
// Declaring all the information of a student
s.name = "GeeksforGeeks";
s.rollno = "S20200010234";
s.cgpa = 8.918;
printStudent(&s);
return 0;
Output
Student Details:
Name: GeeksforGeeks
Roll Number: S20200010234
Subjects: [ DSA OOPS DBMS CCN ]
Marks: [ 89 78 86 90 ]
CGPA 8.918
C++
#include <bits/stdc++.h>
// Structure Of students
struct student {
string name;
string rollno;
// Subjects Enrolled(Array)
vector<string> subjects;
vector<int> marks;
// Student's CGPA
float cgpa;
};
void printStudent(student* s)
printv(s->subjects);
printv(s->marks);
// Driver Code
int main()
// Array of Students
student arrayofstudents[10];
// Student 1
arrayofstudents[0].name = "GeeksforGeeks";
arrayofstudents[0].rollno = "S20200010234";
arrayofstudents[0].subjects
arrayofstudnets[0].cgpa = 8.918;
// Student 2
arrayofstudnets[1].name = "GFG";
arrayofstudnets[1].rollno = "S20200010164";
arrayofstudnets[1].subjects
arrayofstudnets[1].cgpa = 8.45;
// Student 3
arrayofstudnets[2].name = "gfg";
arrayofstudnets[2].rollno = "S20200010169";
arrayofstudnets[2].subjects
arrayofstudnets[2].cgpa = 9.47;
// Function call
printStudent(&arrayofstudnets[i]);
}
return 0;
Output
Student Details:
Name: GeeksforGeeks
Roll Number: S20200010234
Subjects: [ DSA OOPS DBMS CCN ]
Marks: [ 89 78 86 90 ]
CGPA 8.918
Student Details:
Name: GFG
Roll Number: S20200010164
Subjects: [ DSA OOPS DBMS CCN ]
Marks: [ 89 80 89 80 ]
CGPA 8.45
Student Details:
Name: gfg
Roll Number: S20200010169
Subjects: [ DSA OOPS DBMS CCN ]
Marks: [ 99 0 99 90 ]
CGPA 9.47
Structure Sorting (By Multiple Rules) in C++
Last Updated : 05 Apr, 2023
Prerequisite : Structures in C
Name and marks in different subjects (physics, chemistry and maths) are given for all
students. The task is to compute total marks and ranks of all students. And finally
display all students sorted by rank.
Rank of student is computed using below rules.
1. If total marks are different, then students with higher marks gets better rank.
2. If total marks are same, then students with higher marks in Maths gets better rank.
3. If total marks are same and marks in Maths are also same, then students with
better marks in Physics gets better rank.
4. If total marks are same and marks in both Maths and Physics are also same, then
students with better marks in Chemistry gets better rank.
5. If all marks (total, Maths, Physics and Chemistry) are same, then any student can
be assigned better rank.
Recommended Problem
Arrays
Searching
+2 more
Solve Problem
#include <bits/stdc++.h>
struct Student
};
// to given rules
if (a.total != b.total)
if (a.math != b.math)
return a.math > b.math;
if (a.phy != b.phy)
// function compareTwoStudents()
sort(a, a + n, compareTwoStudents);
// Assigning ranks after sorting
a[i].rank = i + 1;
// Driver code
int main()
int n = 5;
Student a[n];
// Details of Student 1
a[0].name = "Bryan";
a[0].math = 80;
a[0].phy = 95;
a[0].che = 85;
// Details of Student 2
a[1].name = "Kevin";
a[1].math = 95;
a[1].phy = 85;
a[1].che = 99;
// Details of Student 3
a[2].name = "Nicky";
a[2].math = 95;
a[2].phy = 85;
a[2].che = 80;
// Details of Student 4
a[3].name = "Steve";
a[3].math = 80;
a[3].phy = 70;
a[3].che = 90;
// Details of Student 5
a[4].name = "Rohan";
a[4].math = 80;
a[4].phy = 80;
a[4].che = 80;
computeRanks(a, n);
<< "Name"
<< "Physics"
<< " "
<< "Chemistry";
<< "Total\n";
cout << a[i].math << " " << a[i].phy << " "
return 0;
Output
Rank Name Maths Physics Chemistry Total
1 Kevin 95 85 99 279
2 Nicky 95 85 80 260
3 Bryan 80 95 85 260
4 Rohan 80 80 80 240
5 Steve 80 70 90 240
Time complexity : O(nlogn)
Auxiliary Space :O(n)
C++ Class and Object Programs
C++ Classes and Objects
Last Updated : 17 Apr, 2023
class Geeks {
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
};
int main()
Geeks obj1;
obj1.geekname = "Abhi";
obj1.printname();
return 0;
}
Output
Geekname is:Abhi
#include <bits/stdc++.h>
class Geeks
public:
string geekname;
int id;
// printname is not defined inside class definition
void printname();
void printid()
};
void Geeks::printname()
int main() {
Geeks obj1;
obj1.geekname = "xyz";
obj1.id=15;
// call printname()
obj1.printname();
// call printid()
obj1.printid();
return 0;
Output
Geekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition are by
default inline, but you can also make any non-class function inline by using the
keyword inline with them. Inline functions are actual functions, which are copied
everywhere during compilation, like pre-processor macro, so the overhead of function
calls is reduced.
Note: Declaring a friend function is a way to give private access to a non-member
function.
Constructors
Constructors are special class members which are called by the compiler every time
an object of that class is instantiated. Constructors have the same name as the class
and may be defined inside or outside the class definition. There are 3 types of
constructors:
Default Constructors
Parameterized Constructors
Copy Constructors
C++
#include <bits/stdc++.h>
class Geeks
public:
int id;
//Default Constructor
Geeks()
id=-1;
}
//Parameterized Constructor
Geeks(int x)
id=x;
};
int main() {
Geeks obj1;
Geeks obj2(21);
return 0;
}
Output
Default Constructor called
Geek id is: -1
Parameterized Constructor called
Geek id is: 21
A Copy Constructor creates a new object, which is an exact copy of the existing
object. The compiler provides a default Copy Constructor to all the classes.
Syntax:
class-name (class-name &){}
Destructors
Destructor is another special member function that is called by the compiler when the
scope of the object ends.
C++
#include <bits/stdc++.h>
class Geeks
public:
int id;
//Definition for Destructor
~Geeks()
};
int main()
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
Geeks obj2;
obj2.id=i;
i++;
Output
Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7
Many people might say that it’s a basic syntax and we should give a semicolon at the
end of the class as its rule defines in cpp. But the main reason why semi-colons are
there at the end of the class is compiler checks if the user is trying to create an
instance of the class at the end of it.
Yes just like structure and union, we can also create the instance of a class at the end
just before the semicolon. As a result, once execution reaches at that line, it creates a
class and allocates memory to your instance.
C++
#include <iostream>
int a, b;
public:
cout << "parameterized constructor -values" << a << " "<< b << endl;
}instance;
int main() {
return 0;
Output
Default Constructor
We can see that we have created a class instance of Demo with the name “instance”,
as a result, the output we can see is Default Constructor is called.
Similarly, we can also call the parameterized constructor just by passing values here
C++
#include <iostream>
class Demo{
public:
int a, b;
Demo()
cout << "parameterized Constructor values-" << a << " "<< b << endl;
}instance(100,200);
int main() {
return 0;
Output
parameterized Constructor values-100 200
Encapsulation in C++
Last Updated : 04 Sep, 2023
Encapsulation in C++ is defined as the wrapping up of data and information in a
single unit. In Object Oriented Programming, Encapsulation is defined as binding
together the data and the functions that manipulate them.
Consider a real-life example of encapsulation, in a company, there are different
sections like the accounts section, finance section, sales section, etc. Now,
The finance section handles all the financial transactions and keeps records of all
the data related to finance.
Similarly, the sales section handles all the sales-related activities and keeps records
of all the sales.
Now there may arise a situation when for some reason an official from the finance
section needs all the data about sales in a particular month.
In this case, he is not allowed to directly access the data of the sales section. He will
first have to contact some other officer in the sales section and then request him to
give the particular data.
This is what Encapsulation is. Here the data of the sales section and the employees
that can manipulate them are wrapped under a single name “sales section”.
Two Important property of Encapsulation
1. Data Protection: Encapsulation protects the internal state of an object by keeping
its data members private. Access to and modification of these data members is
restricted to the class’s public methods, ensuring controlled and secure data
manipulation.
2. Information Hiding: Encapsulation hides the internal implementation details of a
class from external code. Only the public interface of the class is accessible,
providing abstraction and simplifying the usage of the class while allowing the
internal implementation to be modified without impacting external code.
For example if we give input , and output should be half of input
C++
#include <iostream>
class temp{
int a;
int b;
public:
a=input;
b=a/2;
return b;
};
int main() {
int n;
cin>>n;
temp half;
int ans=half.solve(n);
cout<<ans<<endl;
Features of Encapsulation
Below are the features of encapsulation:
1. We can not access any function from the class directly. We need an object to
access that function that is using the member variables of that class.
2. The function which we are making inside the class must use only member
variables, only then it is called encapsulation.
3. If we don’t make a function inside the class which is using the member variable of
the class then we don’t call it encapsulation.
4. Encapsulation improves readability, maintainability, and security by grouping data
and methods together.
5. It helps to control the modification of our data members.
Encapsulation also leads to data abstraction. Using encapsulation also hides the data,
as in the above example, the data of the sections like sales, finance, or accounts are
hidden from any other section.
Simple Example of C++:
C++
#include <iostream>
#include <string>
class Person {
private:
string name;
int age;
public:
this->name = name;
this->age = age;
this->name = name;
}
string getName() {
return name;
this->age = age;
int getAge() {
return age;
};
int main() {
person.setAge(32);
return 0;
Output
Name: John Doe
Age: 30
Name: Jane Doe
Age: 32
In C++, encapsulation can be implemented using classes and access modifiers.
Example:
C++
// Encapsulation
#include <iostream>
private:
int x;
public:
// variable x
void set(int a) { x = a; }
// variable x
};
// Driver code
int main()
{
Encapsulation obj;
obj.set(5);
return 0;
Output
5
Explanation: In the above program, the variable x is made private. This variable can
be accessed and manipulated only using the functions get() and set() which are present
inside the class. Thus we can say that here, the variable x and the functions get() and
set() are bound together which is nothing but encapsulation.
C++
#include <iostream>
// declaring class
class Circle {
// access modifier
private:
// Data Member
float area;
float radius;
public:
void getRadius()
void findArea()
};
int main()
{
// creating instance(object) of class
Circle cir;
Output
Enter radius
Area of circle=0
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-
Oriented Programming.
Inheritance is a feature or a process in which, new classes are created from the
existing classes. The new class created is called “derived class” or “child class” and
the existing class is known as the “base class” or “parent class”. The derived class
now is said to be inherited from the base class.
When we say derived class inherits the base class, it means, the derived class inherits
all the properties of the base class, without changing the properties of base class and
may add new features to its own. These new features in the derived class will not
affect the base class. The derived class is the specialized class for the base class.
Sub Class: The class that inherits properties from another class is called Subclass
or Derived Class.
Super Class: The class whose properties are inherited by a subclass is called Base
Class or Superclass.
The article is divided into the following subtopics:
Why and when to use inheritance?
Modes of Inheritance
Types of Inheritance
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be the same for all three
classes. If we create these classes avoiding inheritance then we have to write all of
these functions in each of the three classes as shown below figure:
You can clearly see that the above process results in duplication of the same code 3
times. This increases the chances of error and data redundancy. To avoid this type of
situation, inheritance is used. If we create a class Vehicle and write these three
functions in it and inherit the rest of the classes from the vehicle class, then we can
simply avoid the duplication of data and increase re-usability. Look at the below
diagram in which the three classes are inherited from vehicle class:
Using inheritance, we have to write the functions only one time instead of three times
as we have inherited the rest of the three classes from the base class (Vehicle).
Implementing inheritance in C++: For creating a sub-class that is inherited from the
base class we have to follow the below syntax.
Derived Classes: A Derived class is defined as the class derived from the base class.
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base class
access-specifier — either of private, public or protected. If neither is specified,
PRIVATE is taken as default
base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data members. However, it
does inherit a full parent object, which contains any private members which that class
declares.
Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }
Note:
o When a base class is privately inherited by the derived class, public members of the
base class becomes the private members of the derived class and therefore, the public
members of the base class can only be accessed by the member functions of the
derived class. They are inaccessible to the objects of the derived class.
o On the other hand, when the base class is publicly inherited by the derived class,
public members of the base class also become the public members of the derived
class. Therefore, the public members of the base class are accessible by the objects of
the derived class as well as by the member functions of the derived class.
C++
// the class
#include <iostream>
class Person {
int id;
char name[100];
public:
void set_p()
void display_p()
cout << endl <<"Id: "<< id << "\nName: " << name <<endl;
};
class Student : private Person {
char course[50];
int fee;
public:
void set_s()
set_p();
void display_s()
display_p();
cout <<"Course: "<< course << "\nFee: " << fee << endl;
}
};
int main()
Student s;
s.set_s();
s.display_s();
return 0;
Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee:70000
Id: 101
Name: Dev
Course: GCS
Fee: 70000
C++
class Person
int id;
char name[100];
public:
void set_p();
void display_p();
};
void Person::set_p()
cin>>id;
void Person::display_p()
char course[50];
int fee;
public:
void set_s();
void display_s();
};
void Student::set_s()
set_p();
cin>>course;
cin>>fee;
void Student::display_s()
display_p();
int main()
Student s;
s.set_s();
s.display_s();
return 0;
Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee: 70000
Id: 101
Name: Dev
Course: GCS
Fee: 70000
C++
#include<iostream>
#include<string.h>
class Person
{
int id;
char name[100];
public:
void set_p(int,char[]);
void display_p();
};
this->id=id;
strcpy(this->name,n);
void Person::display_p()
cout<<endl<<id<<"\t"<<name;
}
char course[50];
int fee;
public:
void set_s(int,char[],char[],int);
void display_s();
};
set_p(id,n);
strcpy(course,c);
fee=f;
}
void Student::display_s()
display_p();
cout<<"t"<<course<<"\t"<<fee;
main()
Student s;
s.set_s(1001,"Ram","B.Tech",2000);
s.display_s();
return 0;
CPP
// of Inheritance
#include <bits/stdc++.h>
// Base class
class Parent {
public:
int id_p;
};
public:
int id_c;
};
// main function
int main()
{
Child obj1;
obj1.id_c = 7;
obj1.id_p = 91;
return 0;
Output
Child id is: 7
Parent id is: 91
Output:
Child id is: 7
Parent id is: 91
In the above program, the ‘Child’ class is publicly inherited from the ‘Parent’ class so
the public data members of the class ‘Parent’ will also be inherited by the class
‘Child’.
Modes of Inheritance: There are 3 modes of inheritance.
1. Public Mode: If we derive a subclass from a public base class. Then the public
member of the base class will become public in the derived class and protected
members of the base class will become protected in the derived class.
2. Protected Mode: If we derive a subclass from a Protected base class. Then both
public members and protected members of the base class will become protected in
the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then both public
members and protected members of the base class will become Private in the
derived class.
Note: The private members in the base class cannot be directly accessed in the
derived class, while protected members can be directly accessed. For example,
Classes B, C, and D all contain the variables x, y, and z in the below example. It is
just a question of access.
CPP
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x is public
// y is protected
};
class C : protected A {
// x is protected
// y is protected
};
// x is private
// y is private
};
The below table summarizes the above three modes and shows the access specifier of
the members of the base class in the subclass when derived in public, protected and
private modes:
Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
Types of Inheritance in C++
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only
one class. i.e. one subclass is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
CPP
// Single inheritance
#include<iostream>
// base class
class Vehicle {
public:
Vehicle()
};
};
// main function
int main()
Car obj;
return 0;
Output
This is a Vehicle
C++
// Example:
#include<iostream>
class A
protected:
int a;
public:
void set_A()
{
cin>>a;
void disp_A()
cout<<endl<<"Value of A="<<a;
};
class B: public A
int b,p;
public:
void set_B()
{
set_A();
cin>>b;
void disp_B()
disp_A();
cout<<endl<<"Value of B="<<b;
void cal_product()
p=a*b;
}
};
main()
B _b;
_b.set_B();
_b.cal_product();
return 0;
C++
// Example:
#include<iostream>
using namespace std;
class A
protected:
int a;
public:
void set_A(int x)
a=x;
void disp_A()
cout<<endl<<"Value of A="<<a;
};
class B: public A
int b,p;
public:
set_A(x);
b=y;
void disp_B()
disp_A();
cout<<endl<<"Value of B="<<b;
}
void cal_product()
p=a*b;
};
main()
B _b;
_b.set_B(4,5);
_b.cal_product();
return 0;
Output
Product of 4 * 5 = 20
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can
inherit from more than one class. i.e one subclass is inherited from more than
one base class.
Syntax:
class subclass_name : access_mode base_class1, access_mode
base_class2, ....
{
// body of subclass
};
class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};
Here, the number of base classes will be separated by a comma (‘, ‘) and the access
mode for every base class must be specified.
CPP
// multiple inheritance
#include <iostream>
using namespace std;
class Vehicle {
public:
};
class FourWheeler {
public:
FourWheeler()
};
};
// main function
int main()
Car obj;
return 0;
Output
This is a Vehicle
This is a 4 wheeler Vehicle
C++
// Example:
#include<iostream>
using namespace std;
class A
protected:
int a;
public:
void set_A()
cin>>a;
void disp_A()
cout<<endl<<"Value of A="<<a;
}
};
class B: public A
protected:
int b;
public:
void set_B()
cin>>b;
void disp_B()
{
cout<<endl<<"Value of B="<<b;
};
class C: public B
int c,p;
public:
void set_C()
cin>>c;
void disp_C()
cout<<endl<<"Value of C="<<c;
}
void cal_product()
p=a*b*c;
};
main()
C _c;
_c.set_A();
_c.set_B();
_c.set_C();
_c.disp_A();
_c.disp_B();
_c.disp_C();
_c.cal_product();
return 0;
To know more about it, please refer to the article Multiple Inheritances.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from
another derived class.
Syntax:-
class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
CPP
// Multilevel Inheritance
#include <iostream>
// base class
class Vehicle {
public:
};
public:
fourWheeler()
};
public:
};
// main function
int main()
Car obj;
return 0;
}
Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is
inherited from a single base class. i.e. more than one derived class is created from a
single base class.
Syntax:-
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
CPP
// Hierarchical Inheritance
#include <iostream>
// base class
class Vehicle {
public:
};
};
// second sub class
};
// main function
int main()
Car obj1;
Bus obj2;
return 0;
Output
This is a Vehicle
This is a Vehicle
#include <iostream>
// base class
class Vehicle {
public:
// base class
class Fare {
public:
};
};
};
// main function
int main()
{
Bus obj2;
return 0;
Output
This is a Vehicle
Fare of Vehicle
C++
// Example:
#include <iostream>
class A
protected:
int a;
public:
void get_a()
cin>>a;
};
class B : public A
protected:
int b;
public:
void get_b()
cin>>b;
}
};
class C
protected:
int c;
public:
void get_c()
cin>>c;
};
protected:
int d;
public:
void mul()
get_a();
get_b();
get_c();
};
int main()
D d;
d.mul();
return 0;
// Inheritance
#include <iostream>
class ClassA {
public:
int a;
};
public:
int b;
};
class ClassC : public ClassA {
public:
int c;
};
public:
int d;
};
int main()
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
Output
a from ClassB : 10
a from ClassC : 100
b : 20
c : 30
d : 40
Output:
a from ClassB : 10
a from ClassC : 100
b : 20
c : 30
d : 40
In the above example, both ClassB and ClassC inherit ClassA, they both have a single
copy of ClassA. However Class-D inherits both ClassB and ClassC, therefore Class-D
has two copies of ClassA, one from ClassB and another from ClassC.
If we need to access the data member of ClassA through the object of Class-D, we
must specify the path from which a will be accessed, whether it is from ClassB or
ClassC, bcoz compiler can’t differentiate between two copies of ClassA in Class-D.
There are 2 Ways to Avoid this Ambiguity:
1) Avoiding ambiguity using the scope resolution operator: Using the scope
resolution operator we can manually specify the path from which data member a will
be accessed, as shown in statements 3 and 4, in the above example.
CPP
#include<iostream>
class ClassA
public:
int a;
};
public:
int b;
};
public:
int c;
};
public:
int d;
};
int main()
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
Output:
a : 100
b : 20
c : 30
d : 40
Abstraction in C++
Last Updated : 06 Sep, 2023
Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and
hiding the details. Data abstraction refers to providing only essential information
about the data to the outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerator will increase the speed of the car or applying brakes will stop
the car but he does not know how on pressing the accelerator the speed is actually
increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car. This is what abstraction is.
Types of Abstraction:
1. Data abstraction – This type only shows the required information about the data
and hides the unnecessary data.
2. Control Abstraction – This type only shows the required information about the
implementation and hides unnecessary information.
Abstraction using Classes
We can implement Abstraction in C++ using classes. The class helps us to group data
members and member functions using available access specifiers. A Class can decide
which data member will be visible to the outside world and which is not.
// working of Abstraction
#include <iostream>
class implementAbstraction {
private:
int a, b;
public:
// private members
a = x;
b = y;
}
void display()
};
int main()
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
Output
a = 10
b = 20
You can see in the above program we are not allowed to access the variables a and b
directly, however, one can call the function set() to set the values in a and b and the
function display() to display the values of a and b.
Example
C++
#include<iostream>
class Vehicle
private:
void piston()
cout<<"4 piston\n";
void manWhoMade()
cout<<"Markus Librette\n";
}
public:
void company()
cout<<"GFG\n";
void model()
cout<<"SIMPLE\n";
void color()
cout<<"Red/GREEN/Silver\n";
void cost()
void oil()
{
cout<<"PETRO\n";
};
int main()
Vehicle obj;
obj.company();
obj.model();
obj.color();
obj.cost();
obj.oil();
Output
GFG
SIMPLE
Red/GREEN/Silver
Rs. 60000 to 900000
PETRO
// access modifier
#include<iostream>
// class definition
class Circle
public:
double radius;
double compute_area()
return 3.14*radius*radius;
}
};
// main function
int main()
Circle obj;
obj.radius = 5.5;
return 0;
Output:
Radius is: 5.5
Area is: 94.985
In the above program, the data member radius is declared as public so it could be
accessed outside the class and thus was allowed access from inside main().
2. Private: The class members declared as private can be accessed only by the
member functions inside the class. They are not allowed to be accessed directly by
any object or function outside the class. Only the member functions or the friend
functions are allowed to access the private data members of the class.
Example:
CPP
// access modifier
#include<iostream>
class Circle
private:
double radius;
public:
double compute_area()
{ // member function can access private
return 3.14*radius*radius;
};
// main function
int main()
Circle obj;
obj.radius = 1.5;
Output:
In function 'int main()':
11:16: error: 'double Circle::radius' is private
double radius;
^
31:9: error: within this context
obj.radius = 1.5;
^
The output of the above program is a compile time error because we are not allowed
to access the private data members of a class directly from outside the class. Yet an
access to obj.radius is attempted, but radius being a private data member, we obtained
the above compilation error.
However, we can access the private data members of a class indirectly using the
public member functions of the class.
Example:
CPP
// access modifier
#include<iostream>
private:
double radius;
public:
void compute_area(double r)
radius = r;
};
// main function
int main()
Circle obj;
obj.compute_area(1.5);
return 0;
Output:
Radius is: 1.5
Area is: 7.065
3. Protected: The protected access modifier is similar to the private access modifier in
the sense that it can’t be accessed outside of its class unless with the help of a friend
class. The difference is that the class members declared as Protected can be accessed
by any subclass (derived class) of that class as well.
Note: This access through inheritance can alter the access modifier of the elements of
base class in derived class depending on the mode of Inheritance.
Example:
CPP
#include <bits/stdc++.h>
// base class
class Parent
protected:
int id_protected;
};
// sub class or derived class from public base class
public:
id_protected = id;
void displayId()
};
// main function
int main() {
Child obj1;
obj1.setId(81);
obj1.displayId();
return 0;
Output:
id_protected is: 81
C++ Polymorphism
Last Updated : 16 Nov, 2023
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A
real-life example of polymorphism is a person who at the same time can have
different characteristics. A man at the same time is a father, a husband, and an
employee. So the same person exhibits different behavior in different situations. This
is called polymorphism. Polymorphism is considered one of the important features of
Object-Oriented Programming.
Types of Polymorphism
Compile-time Polymorphism
Runtime Polymorphism
Types of Polymorphism
1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator
overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of
arguments or/and changing the type of arguments. In simple terms, it is a feature of
object-oriented programming providing many functions that have the same name but
distinct parameters when numerous tasks are listed under one function name. There
are certain Rules of Function Overloading that should be followed while overloading
a function.
Below is the C++ program to show function overloading or compile-time
polymorphism:
C++
// function overloading or
// Compile-time Polymorphism
#include <bits/stdc++.h>
class Geeks {
public:
void func(int x)
}
// Function with same name but
// 1 double parameter
void func(double x)
// 2 int parameters
cout << "value of x and y is " << x << ", " << y
<< endl;
};
// Driver code
int main()
{
Geeks obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85, 64);
return 0;
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64
Explanation: In the above example, a single function named function func() acts
differently in three different situations, which is a property of polymorphism. To
know more about this, you can refer to the article – Function Overloading in C++.
B. Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type,
this ability is known as operator overloading. For example, we can make use of the
addition operator (+) for string class to concatenate two strings. We know that the task
of this operator is to add two operands. So a single operator ‘+’, when placed between
integer operands, adds them and when placed between string operands, concatenates
them.
Below is the C++ program to demonstrate operator overloading:
CPP
// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream>
class Complex {
private:
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
Complex res;
return res;
void print() { cout << real << " + i" << imag << endl; }
};
// Driver code
int main()
Complex c3 = c1 + c2;
c3.print();
Output
12 + i9
Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this
operator is used to add two numbers (integers or floating point numbers), but here the
operator is made to perform the addition of two imaginary or complex numbers. To
know more about this one, refer to the article – Operator Overloading.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The function call
is resolved at runtime in runtime polymorphism. In contrast, with compile time
polymorphism, the compiler determines which function call to bind to the object after
deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
Function overriding Explanation
#include <bits/stdc++.h>
class Animal {
public:
};
public:
};
// Driver code
int main(void)
{
Output
Black
We can see that the parent class reference will always refer to the data member of the
parent class.
B. Virtual Function
A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
Virtual functions are Dynamic in nature.
They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:
C++
#include <iostream>
class GFG_Base {
public:
// virtual function
<< "\n\n";
void print()
<< "\n\n";
};
// Declaring a Child Class
public:
void display()
<< "\n\n";
void print()
<< "\n\n";
};
// Driver code
int main()
GFG_Base* base;
GFG_Child child;
base = &child;
base->GFG_Base::display();
base->print();
Output
Called virtual Base Class function
Called GFG_Base print function
Example 2:
C++
#include <bits/stdc++.h>
class base {
public:
};
public:
// print () is already virtual function in
};
// Driver code
int main()
base* bptr;
derived d;
bptr = &d;
bptr->print();
// Non-virtual function, binded
// at compile time
bptr->show();
return 0;
Output
print derived class
show base class
The parameters should follow any one or more than one of the following conditions
for Function overloading:
Parameters should have a different type
add(int a, int b)
add(double a, double b)
Below is the implementation of the above discussion:
C++
#include <iostream>
// Driver code
int main()
add(10, 2);
add(5.3, 6.2);
return 0;
Output
sum = 12
sum = 11.5
Parameters should have a different number
add(int a, int b)
add(int a, int b, int c)
Below is the implementation of the above discussion:
C++
#include <iostream>
// Driver code
int main()
add(10, 2);
add(5, 6, 4);
return 0;
}
Output
sum = 12
sum = 15
Parameters should have a different sequence of parameters.
add(int a, double b)
add(double a, int b)
Below is the implementation of the above discussion:
C++
#include<iostream>
cout<<"sum = "<<(a+b);
{
cout<<endl<<"sum = "<<(a+b);
// Driver code
int main()
add(10,2.5);
add(5.5,6);
return 0;
Output
sum = 12.5
sum = 11.5
Following is a simple C++ example to demonstrate function overloading.
CPP
#include <iostream>
void print(double f) {
int main() {
print(10);
print(10.10);
print("ten");
return 0;
Output
Here is int 10
Here is float 10.1
Here is char* ten
C++
#include<iostream>
cout<<"sum ="<<(a+b);
cout<<endl<<"sum ="<<(a+b+c);
main()
{
add(10,2);
add(5,6,4);
return 0;
C++
#include<iostream>
cout<<"sum ="<<(a+b);
cout<<endl<<"sum ="<<(a+b);
}
main()
add(10,2.5);
add(5.5,6);
return 0;
ELSE ERROR
override identifier in C++
Last Updated : 13 Jun, 2022
Function overriding is a redefinition of the base class function in its derived class with
the same signature i.e. return type and parameters.
But there may be situations when a programmer makes a mistake while overriding
that function. So, to keep track of such an error, C++11 has come up with
the override identifier. If the compiler comes across this identifier, it understands that
this is an overridden version of the same class. It will make the compiler check the
base class to see if there is a virtual function with this exact signature. And if there is
not, the compiler will show an error.
The programmer’s intentions can be made clear to the compiler by override. If the
override identifier is used with a member function, the compiler makes sure that the
member function exists in the base class, and also the compiler restricts the program
to compile otherwise.
Let’s understand through the following example:
CPP
Output
Compiled successfully
Explanation: Here, the user intended to override the function func() in the derived
class but did a silly mistake and redefined the function with a different signature.
Which was not detected by the compiler. However, the program is not actually what
the user wanted. So, to get rid of such silly mistakes to be on the safe side, the
override identifier can be used.
Below is a C++ example to show the use of override identifier in C++.
CPP
#include <iostream>
class Base {
public:
};
public:
};
int main()
Base b;
derived d;
cout << "Compiled successfully" << endl;
return 0;
Output(Error)
prog.cpp:17:7: error: 'void derived::func(int)'
marked 'override', but does not override
void func(int a) override
^
Here, we will see how to use this keyword in a class using a C++ program. this
keyword in C++ is an implicit pointer that points to the object of the class of which
the member function is called. Every object has its own this pointer. Every object can
reference itself by this pointer.
There are 4 ways this keyword can be used in a class in C++:
1. Resolve Shadowing Issue Using this Keyword.
2. Access Currently Executing Object Using this Keyword.
3. Access Data Members Using this Keyword.
4. Calling Member Functions Using this Keyword.
Let’s start discussing these different ways in detail.
C++
// C++ program to use this keyword
#include <iostream>
class GFG
string name;
public:
GFG(string name)
this->name = name;
void display()
{
};
// Driver code
int main()
GFG gfg("GeeksforGeeks");
gfg.display();
return 0;
Output
GeeksforGeeks
#include <iostream>
class GFG
string name;
public:
GFG(string name)
// constructor.
this->name = name;
}
void display()
void del()
// the object
delete this;
};
// Driver code
int main()
gfg->del();
return 0;
Output
GeeksforGeeks
Example 2: Below is the C++ program to use this keyword to access currently
executing object to chain function calls:
C++
#include <iostream>
class GFG
string name;
int data;
public:
this->name = name;
return *this;
this->data = data;
return *this;
void display()
};
// Driver code
int main()
// Creating object
GFG gfg;
gfg = gfg.setName("GeeksforGeeks").setData(20);
gfg.display();
return 0;
Output
GeeksforGeeks
20
C++
// object
#include <iostream>
class GFG
string name;
public:
GFG(string name)
this->name = name;
void display()
};
// Driver code
int main()
GFG gfg("GeeksforGeeks");
gfg.display();
return 0;
Output
GeeksforGeeks
C++
// executing objects
#include <iostream>
class GFG
string name;
public:
GFG(string name)
this->name = name;
void displayX(int);
void display();
};
// executing object
this->display();
}
void GFG :: display()
// Driver code
int main()
GFG gfg("GeeksforGeeks");
gfg.displayX(4);
return 0;
Output
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
// variables in a Function
#include <iostream>
#include <string>
void demo()
{
// static variable
// function calls
count++;
int main()
demo();
return 0;
Output
0 1 2 3 4
You can see in the above program that the variable count is declared static. So, its
value is carried through the function calls. The variable count is not getting initialized
every time the function is called. As a side note, Java doesn’t allow static local
variables in functions.
Static variables in a class: As the variables declared as static are initialized only once
as they are allocated space in separate static storage so, the static variables in a class
are shared by the objects. There can not be multiple copies of the same static
variables for different objects. Also because of this reason static variables can not be
initialized using constructors.
C++
#include <iostream>
class GfG {
public:
static int i;
GfG(){
// Do nothing
};
};
int main()
GfG obj1;
GfG obj2;
obj1.i = 2;
obj2.i = 3;
// prints value of i
Output
undefined reference to `GfG::i'
collect2: error: ld returned 1 exit status
You can see in the above program that we have tried to create multiple copies of the
static variable i for multiple objects. But this didn’t happen. So, a static variable inside
a class should be initialized explicitly by the user using the class name and scope
resolution operator outside the class as shown below:
C++
#include <iostream>
class GfG {
public:
static int i;
GfG(){
// Do nothing
};
};
int GfG::i = 1;
int main()
{
GfG obj;
// prints value of i
Output
1
#include <iostream>
class GfG {
int i;
public:
GfG()
i = 0;
};
int main()
int x = 0;
if (x == 0) {
GfG obj;
Output
Inside Constructor
Inside Destructor
End of main
In the above program, the object is declared inside the if block as non-static. So, the
scope of a variable is inside the if block only. So when the object is created the
constructor is invoked and soon as the control of if block gets over the destructor is
invoked as the scope of the object is inside the if block only where it is declared. Let
us now see the change in output if we declare the object as static.
C++
#include <iostream>
class GfG {
int i = 0;
public:
GfG()
i = 0;
}
~GfG() { cout << "Inside Destructor\n"; }
};
int main()
int x = 0;
if (x == 0) {
Output
Inside Constructor
End of main
Inside Destructor
You can clearly see the change in output. Now the destructor is invoked after the end
of the main. This happened because the scope of static objects is throughout the
lifetime of the program.
Static functions in a class: Just like the static data members or static variables inside
the class, static member functions also do not depend on the object of the class. We
are allowed to invoke a static member function using the object and the ‘.’ operator
but it is recommended to invoke the static members using the class name and the
scope resolution operator. Static member functions are allowed to access only the
static data members or other static member functions, they can not access the non-
static data members or member functions of the class.
C++
#include <iostream>
class GfG {
public:
};
// main function
int main()
GfG::printMsg();
}
Output
Welcome to GfG!
A friend class can access private and protected members of other classes in which it
is declared as a friend. It is sometimes useful to allow a particular class to access
private and protected members of other classes. For example, a LinkedList class may
be allowed to access private members of Node.
We can declare a friend class in C++ by using the friend keyword.
Syntax:
friend class class_name; // declared in the base class
Friend class
Example:
C++
// C++ Program to demonstrate the
#include <iostream>
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
private_variable = 10;
protected_variable = 99;
}
// friend class declaration
friend class F;
};
// class GFG.
class F {
public:
void display(GFG& t)
<< t.protected_variable;
}
};
// Driver code
int main()
GFG g;
F fri;
fri.display(g);
return 0;
Output
The value of Private Variable = 10
The value of Protected Variable = 99
Note: We can declare friend class or function anywhere in the base class body
whether its private, protected or public block. It works all the same.
Friend Function
Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++. They are the non-member functions that can
access and manipulate the private and protected members of the class for they are
declared as friends.
A friend function can be:
1. A global function
2. A member function of another class
Friend Function in C++
Syntax:
friend return_type function_name (arguments); // for a global
function
or
friend return_type class_name::function_name (arguments); // for a
member function of another class
Friend Function Syntax
We can declare any global function as a friend function. The following example
demonstrates how to declare a global function as a friend function in C++:
Example:
C++
#include <iostream>
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
private_variable = 10;
protected_variable = 99;
};
<< endl;
}
// driver code
int main()
base object1;
friendFunction(object1);
return 0;
Output
Private Variable: 10
Protected Variable: 99
In the above example, we have used a global function as a friend function. In the next
example, we will use a member function of another class as a friend function.
We can also declare a member function of another class as a friend function in C++.
The following example demonstrates how to use a member function of another class
as a friend function in C++:
Example:
C++
#include <iostream>
class anotherClass {
public:
};
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
private_variable = 10;
protected_variable = 99;
};
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
// driver code
int main()
base object1;
anotherClass object2;
object2.memberFunction(object1);
return 0;
Output
Private Variable: 10
Protected Variable: 99
Note: The order in which we define the friend function of another class is important
and should be taken care of. We always have to define both the classes before the
function definition. Thats why we have used out of class member function definition.
Features of Friend Functions
A friend function is a special function in C++ that in spite of not being a member
function of a class has the privilege to access the private and protected data of a
class.
A friend function is a non-member function or ordinary function of a class, which
is declared as a friend using the keyword “friend” inside the class. By declaring a
function as a friend, all the access permissions are given to the function.
The keyword “friend” is placed only in the function declaration of the friend
function and not in the function definition or call.
A friend function is called like an ordinary function. It cannot be called using the
object name and dot operator. However, it may accept the object as an argument
whose value it wants to access.
A friend function can be declared in any section of the class i.e. public or private
or protected.
Below are some more examples of friend functions in different scenarios:
A Function Friendly to Multiple Classes
C++
#include <iostream>
// Forward declaration
class ABC;
class XYZ {
int x;
public:
void set_data(int a)
x = a;
};
class ABC {
int y;
public:
void set_data(int a)
{
y = a;
};
else
// Driver code
int main()
ABC _abc;
XYZ _xyz;
_xyz.set_data(20);
_abc.set_data(35);
max(_xyz, _abc);
return 0;
Output
35
The friend function provides us with a way to access private data but it also has its
demerits. Following is the list of advantages and disadvantages of friend functions in
C++:
Deleting a derived class object using a pointer of base class type that has a non-virtual
destructor results in undefined behavior. To correct this situation, the base class
should be defined with a virtual destructor.
For example, the following program results in undefined behavior.
CPP
#include <iostream>
class base {
public:
base()
~base()
};
public:
derived()
~derived()
};
int main()
base *b = d;
delete b;
getchar();
return 0;
Output
Constructing base
Constructing derived
Destructing base
Making base class destructor virtual guarantees that the object of derived class is
destructed properly, i.e., both base class and derived class destructors are called. For
example,
CPP
#include <iostream>
class base {
public:
base()
{ cout << "Constructing base\n"; }
virtual ~base()
};
public:
derived()
~derived()
};
int main()
base *b = d;
delete b;
getchar();
return 0;
Output
Constructing base
Constructing derived
Destructing derived
Destructing base
class Test {
public:
/* Other members */
};
Complete Example
A pure virtual function is implemented by classes that are derived from an Abstract
class.
C++
// functions
#include <iostream>
int x;
public:
};
int y;
public:
};
int main(void)
Derived d;
d.fun();
return 0;
Output
fun() called
C++
// virtual functions
#include <iostream>
class Test {
int x;
public:
};
int main(void)
Test t;
return 0;
Output
Compiler Error: cannot declare variable 't' to be of abstract
type 'Test' because the following virtual functions are pure
within 'Test': note: virtual void Test::show()
2. We can have pointers and references of abstract class type.
For example, the following program works fine.
C++
class Base {
public:
};
public:
};
int main(void)
// of type Derived
// pointer
bp->show();
return 0;
Output
In Derived
3. If we do not override the pure virtual function in the derived class, then the
derived class also becomes an abstract class.
The following example demonstrates the same.
C++
class Base {
public:
};
};
int main(void)
Derived d;
return 0;
Output
Compiler Error: cannot declare variable 'd' to be of abstract type
'Derived' because the following virtual functions are pure within
'Derived': virtual void Base::show()
4. An abstract class can have constructors.
For example, the following program compiles and runs fine.
C++
#include <iostream>
class Base {
protected:
int x;
public:
Base(int i)
x = i;
};
int y;
public:
// calling the constructor of Base class
Derived(int i, int j)
: Base(i)
y = j;
void fun()
cout << "x = " << x << ", y = " << y << '\n';
};
int main(void)
d.fun();
// pointer
ptr->fun();
return 0;
Output
Constructor of base called
x = 4, y = 5
Constructor of base called
x = 6, y = 7
5. An abstract class in C++ can also be defined using struct keyword.
Example
struct shapeClass
{
virtual void Draw()=0;
}
C++
// in C++
#include <bits/stdc++.h>
class Singleton{
private:
// member variables
static Singleton*
instancePtr;
// Default constructor
Singleton()
public:
= delete;
/*
*/
if (instancePtr == NULL)
return instancePtr;
else
return instancePtr;
string loves)
this->name = name;
this->loves = loves;
void print()
};
// Driver code
int main()
Singleton* GeeksForGeeks
= Singleton ::getInstance();
GeeksForGeeks->setValues("Manish",
"GeeksForGeeks");
GeeksForGeeks ->print();
gfg->setValues("Vartika",
"GeeksForGeeks");
gfg->print();
return 0;
Output
Manish Loves GeeksForGeeks.
Address of GeeksForGeeks: 0x1793010
C++
#include <bits/stdc++.h>
class Singleton{
private:
// member variables
// an object.)
// Default constructor
Singleton()
public:
// is pointing to an instance of
// Singleton class
static Singleton *getInstance()
return instancePtr;
string loves)
this->name = name;
this->loves = loves;
void print()
};
// initializing instancePtr with an instance
= new Singleton();
// Driver code
int main()
Singleton *gfg
= Singleton::getInstance();
gfg->setValues("Learner",
"GeeksForGeeks");
gfg->print();
Singleton *geeksForGeeks
= Singleton::getInstance();
geeksForGeeks->setValues("Everyone",
"GeeksForGeeks");
geeksForGeeks->print();
return 0;
Output
Learner Loves GeeksForGeeks.
Address of gfg : 0xd63010
C++
#include<bits/stdc++.h>
class Singleton{
private:
// member variables
// Default constructor
Singleton()
//same as above
Singleton(string name,
string loves)
this->name = name;
this->loves = loves;
public:
// deleting copy constructor.
if(instancePtr == NULL)
return instancePtr;
}
else
return instancePtr;
string loves)
this->name = name;
this->loves = loves;
}
// prints values of member variables.
void print()
};
// Driver code
int main()
// Gives error
Singleton *geeksForGeeks
= new Singleton();
// Cannot create object of Singleton class
return 0;
Output
Explanation: As shown in the above output we are not able to instantiate an instance
of the Singleton class by using the constructor. We can have only one instance of the
Singleton class which we will get by using the getInstance() method.
C++ Program to Create an Interface
Last Updated : 05 Jul, 2022
Interfaces are nothing but a way to describe the behavior of a class without
committing to the implementation of the class. In C++ programming there is no built-
in concept of interfaces. In order to create an interface, we need to create an abstract
class which is having only pure virtual methods. In C++, Interfaces are also called
pure abstract classes.
Pure Virtual Functions
A Pure Virtual Function is a function where we only declare the function but not the
function definition. The implementation for pure virtual methods is done at the
derived class by method/function overriding. A function is said to be a pure virtual
function if it is defined in the class as follows:
virtual datatype functionName(parameter1, parameter2,…) = 0
Abstract Class
Importance of Interfaces
Any class derived from the pure abstract class (Interface) must implement all of
the methods of the base class i.e. Interface.
Interface pointers can be passed to functions and classes thereby we can call the
functions of the derived class from there itself.
#include <iostream>
#include <string>
// Interface(Abstract class
class GFG
public:
};
public:
string returnString()
{
return "GeeksforGeeks";
};
// Driver code
int main()
child childObj;
GFG* ptr;
ptr = &childObj;
return 0;
Output
GeeksforGeeks
Example 2: In the below code, an abstract class websiteName is created with a pure
virtual function in it. So it acts as an interface. The functionality of the method
getName() is implemented in the two child classes of the base class.
C++
// C++ program to implement
// the Interface
#include <iostream>
#include <string>
// Interface(Abstract class
class websiteName
public:
};
public:
string getName()
{
return "GFG";
};
public:
string getName()
return "GeeksforGeeks";
};
// Driver code
int main()
shortForm obj1;
fullForm obj2;
websiteName* ptr;
ptr = &obj1;
ptr->getName();
ptr = &obj2;
ptr->getName();
return 0;
Output
Short form - GFG
Full form - GeeksforGeeks
by a simpler code:
i5 = (i1 + i2) / (i3 - i4)
The operator symbol for both prefix(++i) and postfix(i++) are the same. Hence, we
need two different function definitions to distinguish between them. This is achieved
by passing a dummy int parameter in the postfix version.
Here is the code to demonstrate the same.
Example: Pre-increment overloading
CPP
#include <bits/stdc++.h>
class Integer {
private:
int i;
public:
// Parameterised constructor
Integer(int i = 0)
this->i = i;
Integer& operator++()
++i;
return *this;
};
// Driver function
int main()
Integer i1(3);
i1.display();
Integer i2 = ++i1;
i1.display();
i2.display();
Output
Before increment: i = 3
After post decrement:
i1: i = 4
i2: i = 4
Example: Post-Increment Overloading
CPP
// overloading
#include <bits/stdc++.h>
class Integer {
private:
int i;
public:
// Parameterised constructor
Integer(int i = 0)
this->i = i;
Integer operator++(int)
++i;
return temp;
}
// Function to display the value of i
void display()
};
// Driver function
int main()
Integer i1(3);
i1.display();
Integer i2 = i1++;
cout << "After post increment: " << endl;
i1.display();
i2.display();
Output
Before increment: i = 3
After post increment:
i1: i = 4
i2: i = 3
// overloading
#include <bits/stdc++.h>
class Integer {
private:
int i;
public:
// Parameterised constructor
Integer(int i = 0)
this->i = i;
Integer& operator--()
{
--i;
return *this;
void display()
};
// Driver function
int main()
Integer i1(3);
Integer i2 = --i1;
i1.display();
i2.display();
Output
Before decrement: i = 3
After pre decrement:
i1: i = 2
i2: i = 2
Example: Post-Decrement Overloading
CPP
// overloading
#include <bits/stdc++.h>
class Integer {
private:
int i;
public:
// Parameterised constructor
Integer(int i = 0)
this->i = i;
Integer operator--(int)
{
--i;
return temp;
void display()
};
// Driver function
int main()
Integer i1(3);
cout << "Before decrement: ";
i1.display();
Integer i2 = i1--;
i1.display();
i2.display();
Output
Before decrement: i = 3
After post decrement:
i1: i = 2
i2: i = 3
Given two complex numbers of the form and the task is to add these two complex
numbers.
a1 + ib1 and a2 + ib2
Here the values of real and imaginary numbers are passed while calling the
parameterized constructor and, with the help of a default(empty) constructor, the
function addComp is called to get the addition of complex numbers.
Examples:
Input: a1 = 4, b1 = 8
a2 = 5, b2 = 7
Output: Sum = 9 + i15
#include<bits/stdc++.h>
class Complex
{
// Declaring variables
// Constructor to accept
Complex(int tempReal = 0,
int tempImaginary = 0)
real = tempReal;
imaginary = tempImaginary;
// complex numbers
// complex numbers
return temp;
};
// Driver code
int main()
{
// First Complex number
Complex C3;
// Calling addComp() method
C3 = C3.addComp(C1, C2);
C3.imaginary;
Output
Complex number 1 : 3 + i2
Complex number 2 : 9 + i5
Sum of complex number : 12 + i7
Explanation of the above method
1. A class Complex is created for complex numbers with two data members real
and imaginary, a parameterized constructor, and a function to add complex
numbers.
2. Parameterized constructor is used to initialize the data members real and
imaginary.
3. A function addComp() with Class return type is created to add two complex
numbers.
The complexity of the above method
Time Complexity: O(1)
Auxiliary Space: O(1)
C++ File Handling Programs
C++ program to create a file
Last Updated : 28 Sep, 2018
Problem Statement: Write a C++ program to create a file using file handling and
check whether the file is created successfully or not. If a file is created successfully
then it should print “File Created Successfully” otherwise should print some error
message.
Approach: Declare a stream class file and open that text file in writing mode. If the
file is not present then it creates a new text file. Now check if the file does not exist or
not created then return false otherwise return true.
Below is the program to create a file:
#include <bits/stdc++.h>
// Driver code
int main()
fstream file;
// opening file "Gfg.txt"
// in out(write) mode
file.open("Gfg.txt",ios::out);
if(!file)
return 0;
file.close();
return 0;
Output:
C++ Program to Create a Temporary File
Last Updated : 31 Jul, 2022
Here, we will see how to create a temporary file using a C++ program. Temporary file
in C++ can be created using the tmpfile() method defined in the <cstdio> header file.
The temporary file created has a unique auto-generated filename. The file created is
opened in binary mode and has access mode “wb+”. These temporary files are
automatically deleted when the program is terminated or when they are closed in the
program using fclose().
Syntax:
std::FILE* tmpfile();
Return value: The associated file stream or a null pointer if an error has occurred.
Below is the C++ program to create a temporary file, writing in and reading from the
temporary file:
C++
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main()
FILE* fp = tmpfile();
if (fp == NULL)
exit(1);
}
// Writing in temporary file the content
fputs(write, fp);
rewind(fp);
// and displaying it
char read[100];
fclose(fp);
return 0;
Output:
Welcome to Geeks For Geeks
Read/Write Class Objects from/to File in C++
Last Updated : 24 Jan, 2023
Given a file “Input.txt” in which every line has values same as instance variables of a
class.
Read the values into the class’s object and do necessary operations.
Theory :
The data transfer is usually done using '>>'
and <<' operators. But if you have
a class with 4 data members and want
to write all 4 data members from its
object directly to a file or vice-versa,
we can do that using following syntax :
Output :
Terry
C++
// C++ program to demonstrate read/write of class
// objects in C++.
#include <iostream>
#include <fstream>
class Contestant {
public:
// Instance variables
string Name;
int input();
};
int Contestant::input()
ofstream file_obj;
file_obj.open("Input.txt", ios::app);
Contestant obj;
obj.Name = str;
obj.Age = age;
obj.Ratings = ratings;
file_obj.write((char*)&obj, sizeof(obj));
str = "Terry";
age = 21;
ratings = 3200;
obj.Name = str;
obj.Age = age;
obj.Ratings = ratings;
// Writing the object's data in file
file_obj.write((char*)&obj, sizeof(obj));
//It's always a good practice to close the file after opening them
file_obj.close();
return 0;
int Contestant::output_highest_rated()
ifstream file_obj;
// Opening file in input mode
file_obj.open("Input.txt", ios::in);
Contestant obj;
file_obj.read((char*)&obj, sizeof(obj));
int max = 0;
string Highest_rated;
while (!file_obj.eof()) {
max = obj.Ratings;
Highest_rated = obj.Name;
// Checking further
file_obj.read((char*)&obj, sizeof(obj));
//It's always a good practice to close the file after opening them
file_obj.close();
return 0;
}
// Driver code
int main()
Contestant object;
object.input();
object.output_highest_rated();
return 0;
Output:
Terry
rename function in C
Last Updated : 21 Sep, 2023
The rename() function is used to rename a file in C. It changes the name of the file
from old_name to new_name without modifying the content present in the file. It is
defined inside <stdio.h> header file.
In this article, we will learn how to rename a file using the rename() function in C
programming language.
Syntax of rename()
int rename (const char *old_name, const char *new_name);
If new_name is the name of an existing file in the same folder then the function may
either fail or override the existing file, depending on the specific system and library
implementation.
Parameters
Return Value
C
#include <stdio.h>
int main()
// Any string
int value;
else {
perror("Error");
return 0;
Output
If file name changed
File name changed successfully
OR
If file is not present
Error: No such file or directory
Here, we will build C++ Program to Make a File Read-Only using 2 approaches i.e.
1. Using ifstream
2. Using fstream
C++ programming language offers a library called fstream consisting of different
kinds of classes to handle the files while working on them. The classes present in
fstream are ofstream, ifstream, fstream.
1. Using “ifstream”
The output of the below code consists of data present in the specified “Geeks for
Geeks.txt” file.
ifstream class is used to read the file and doesn’t support writing data into the file. i.e.
making files available to read-only. The created input stream “ifstream in” specifies
the file to be opened in reading mode.
C++
#include <fstream>
#include <iostream>
int main()
ifstream in;
if (!in)
else {
char c;
while (1) {
in >> c;
if (in.eof())
break;
cout << c;
in.close();
return 0;
Output:
Geeks_for_Geeks
2. Using “fstream”
The fstream class is used to read the file and also enables writing data into the opened
file.
Here in the below code, we opened a file in read mode by specifying “ios::in“ in the
open method and displayed the data present in the file on the successful opening of a
file.
C++
#include <fstream>
#include <iostream>
int main()
fstream readFile;
if (!readFile)
else {
char c;
while (1) {
readFile >> c;
if (readFile.eof())
break;
cout << c;
readFile.close();
return 0;
Output:
Geeks_for_Geeks
As we are given two paths of two files, we have to compare these two paths and check
whether they are equal or greater or smaller using a C++ program.
Input:
path1 = "/a/b/c" , path2 = "/a/b/"
Output:
path1 is greater than path2
Approaches:
Using built-in compare function :
#include <iostream>
if (res > 0)
else if (res == 0)
// Driver code
int main()
string p1 = "/a/b/c";
string p2 = "/a/b/";
string p3 = "/a/b";
string p4 = "/a/b";
string p5 = "/a/b";
string p6 = "/a/b.";
return 0;
}
Output
/a/b/c is greater than /a/b/
/a/b is equal to /a/b
/a/b is less than /a/b.
OR
C++
C++
if (p1[i] != p2[i]) {
cout << p1 << " is not equal to " << p2 << endl;
return;
}
// Driver code
int main()
string p1 = "/a/b/c";
string p2 = "/a/b/";
string p3 = "/a/b";
string p4 = "/a/b";
string p5 = "/a/b";
string p6 = "/a/b.";
return 0;
Output
/a/b/c is not equal to /a/b/
/a/b is equal to /a/b
/a/b is not equal to /a/b.
Using Comparison operators:
syntax:
#include <iostream>
{
// Comparing using if-else
cout << p1 << " is greater than " << p2 << endl;
cout << p1 << " is less than " << p2 << endl;
else
// Driver code
int main()
string p1 = "/a/b/c";
string p2 = "/a/b/";
string p3 = "/a/b";
string p4 = "/a/b";
string p5 = "/a/b";
string p6 = "/a/b.";
return 0;
Output
/a/b/c is greater than /a/b/
/a/b is equal to /a/b
/a/b is less than /a/b.
Time Complexity: O(1)
Auxiliary Space: O(1)
C++ Program to Copy One File into Another
File
Last Updated : 20 Jun, 2022
To copy the text/contents of one file to another file, we should know the basics of
reading and writing a text file in C++. To copy the file using C++, we read the
contents of the source file and write it into the destination file.
Steps to copy one file to another in C++:
1. Create objects of ifstream and ofstream classes.
2. Check if they are connected to their respective files. If so, go ahead otherwise
check the filenames twice.
3. Read the contents of the source file using the getline() method and write the same
to the destination using the << operator ( i.e. copy each line from ifstream object to
ofstream object).
4. Close files after the copy using the close() method.
5. End the program.
Note: ifstream and ofstream classes are present in the <fstream> library.
Example:
C++
#include <fstream>
#include <iostream>
int main()
string line;
ifstream ini_file{
"original.txt"
}; // This is the original file
else {
// Closing file
ini_file.close();
out_file.close();
return 0;
Output:
Original File – original.txt:
File: original.txt
In this example, we have assumed that both the original file and the copy file are in
the same directory where the code file of this program is. The above program runs
unless the whole contents of the original file get copied to another file.
Given source and destination text files. Append the content from the source file to the
destination file and then display the content of the destination file.
Example :
Input : file.txt : "geeks", file2.txt : "geeks for"
Output: file2.txt : "geeks for geeks"
Method 1:
Approach:
1. Open file.txt in inputstream and file2.txt in outputstream with the append option,
so that the previous content of the file are not deleted.
2. Check if there’s an error in opening or locating a file. If yes, then throw an error
message.
3. If both files are found, then write content from the source file to the destination
file.
4. Display the content of the destination file.
Below is the implementation of the above approach:
CPP
// destination file
#include <bits/stdc++.h>
// driver code
int main()
fstream file;
// Input stream class to
// operate on files.
// operate on files.
if (!ifile.is_open()) {
else {
string word;
// opening file
file.open("file2.txt");
// displaying content of
// destination file
return 0;
Output
file not found
Method 2: We can do the same using different functions mentioned below:
fopen(): Returns a pointer to the object that controls the opened file stream
fprintf(): Writes the string pointed by format to the stream
fclose(): Closes the file associated with the stream and disassociates it.
fgetc(): Returns the character currently pointed by the internal file position
indicator of the specified stream
Approach:
1. Open source file in read mode and destination file in append mode using fopen()
2. check if they exist
3. Iterate every character of the source file using fgetc() and print it to the destination
file using fprintf() with while loop
4. Close both files using fclose()
5. Open destination file in read mode
6. print it
7. close it
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
int main()
if (file2 == NULL) {
return 1;
return 1;
char ch = fgetc(file);
ch = fgetc(file);
}
fclose(file);
fclose(file2);
printf("%c", ch2);
ch2 = fgetc(file3);
fclose(file3);
}
// This code is contributed by Shivesh Kumar Dwivedi
Output
file not found
Getting the list of files in a directory is one of the most common operations performed
by the Filesystem of an OS. The file explorer application in most operating systems
performs the same operation in the background. In this article, you will learn how to
get the list of files in a directory using C++.
Two methods can be used to Get the List of Files in a Directory:
Using the system function – ( functions in C++ )
Using the directory_iterator – ( Invoking directory traversing commands from the
operating system’s command interpreter )
1. Getting the list of files using the system function
The list of files in a directory could be obtained by calling the system function and
sending an argument to dir /a-d for Windows OS (or ls -p | grep -v / in Linux OS).
The help page of the command is as follows:
Directory displayed using cmd
A Windows machine would be used for demonstration, and the list of files in the
following directory would be obtained.
Code:
C++
#include <bits/stdc++.h>
#include <cstdlib>
#include <iostream>
int main()
// backslash
string path(
"\"C:\\Users\\Sauleyayan\\Desktop\\New folder\"");
command.append(path);
// function requires
// system function
system(final_command);
return 0;
Output:
Output of Program
Explanation: Firstly, the cstdlib header file is imported to allow the use of the system
function. Then the directory’s path on which the files are to be searched is assigned to
the variable path. Then another variable named command is assigned the command to
be run. After which, both variables are concatenated to produce the final command.
Then another variable of type const char * is defined and assigned the value of the
aforementioned concatenated string. Since the system function requires a const char *
as an argument, this conversion was necessary. Then the char array (containing the
command) is passed to the system function, which delivers the desired result.
2. Getting the list of files using the directory_iterator function
Getting the list of files within a directory could be done by using an iterator on the
directory. Which will go through each element of the directory one by one. Then
distinguishes whether the path belongs to a file or directory and, in the end, displays
the valid ones.
The following code uses C++17 standard code.
Code:
C++
#include <filesystem>
#include <iostream>
#include <string>
#include <sys/stat.h>
namespace fs = std::filesystem;
int main()
std::string path
= "C:\\Users\\Sauleyayan\\Desktop\\New folder";
// directory
// exhausted
// subsequent lines
Output:
Output of Program
Explanation: Firstly the header files filesystem and sys/stat.h were imported. Then a
path to the directory is assigned to a variable. A structure template is initialized, which
will be used to differentiate between a file and a directory. Then in a for loop, all the
directory elements are iterated through. The first three statements in the for loop are
just converting the path to the directory element from std::filesystem::path to const
char * datatype. This is required as the stat function takes in an argument a character
array, hence the requirement for this conversion. Then in an if the condition it is
checked whether the path belongs to a directory or not. If it does not, then the path is
displayed. Otherwise, it is ignored.
C++ Program to Append a String in an Existing
File
Last Updated : 28 Jul, 2022
Here, we will build a C++ program to append a string in an existing file using 2
approaches i.e.
1. Using ofstream
2. Using fstream
C++ programming language offers a library called fstream consisting of different
kinds of classes to handle the files while working on them. The classes present in
fstream are ofstream, ifstream and fstream.
The file we are considering the below examples consists of the text “Geeks for
Geeks“.
1. Using “ofstream“
In the below code we appended a string to the “Geeks for Geeks.txt” file and printed
the data in the file after appending the text. The created ofstream “ofstream
of” specifies the file to be opened in write mode and “ios::app“ in the open method
specifies the append mode.
C++
#include <fstream>
#include <iostream>
#include <string>
int main()
ofstream of;
fstream f;
if (!of)
else {
of << " String";
of.close();
string word;
f.close();
return 0;
Output:
Data appended successfully
Geeks for Geeks String
2. Using “fstream“
In the below code we appended a string to the “Geeks for Geeks.txt” file and printed
the data in the file after appending the text. The created fstream “fstream f” specifies
the file to be opened in reading & writing mode and “ios::app“ in the open method
specifies the append mode.
C++
#include <fstream>
#include <string>
int main()
fstream f;
if (!f)
else {
f.close();
string word;
f.close();
return 0;
Output:
Data appended successfully
Geeks for Geeks String_fstream
Here, we will see how to read contents from one file and write it to another file using
a C++ program. Let us consider two files file1.txt and file2.txt. We are going to read
the content of file.txt and write it in file2.txt
Contents of file1.txt:
Welcome to GeeksForGeeks
Approach:
1. Create an input file stream object and open file.txt in it.
2. Create an output file stream object and open file2.txt in it.
3. Read each line from the file and write it in file2.
Below is the C++ program to read contents from one file and write it to another file:
C++
// C++ program to read contents from
#include<bits/stdc++.h>
// Driver code
int main()
ifstream in("file1.txt");
// write to file2.txt
ofstream f("file2.txt");
// file.txt
string text;
getline(in, text);
// file2.txt
return 0;
Output:
file1.txt
GeeksforGeeks is a Computer Science portal for geeks.
file2.txt
GeeksforGeeks is a Computer Science portal for geeks.
A runtime error occurs while the program is running. Because this is not a
compilation error, the compilation will be completed successfully. Here, we will learn
how to handle runtime exceptions in C++.
There are 5 types of runtime exceptions discussed here:
1. Division by zero.
2. Segmentation faults.
3. Large memory allocation/Large Static Memory Allocation.
4. Type Specifier Error.
5. Invalid memory access during runtime.
Let’s start discussing each of these runtime errors in detail.
1. Division By Zero
When we divide an integer value by zero then we get this type of error called division
by zero error. It is also called floating-point exceptions (SIGFPE). Below is the C++
program to demonstrate division by zero exception:
C++
#include <iostream>
// Driver code
int main()
int a = 10;
int res = a / 0;
return 0;
Output:
2. Segmentation Faults
In the below code, the line *(str + 1) = ‘n’ tries to write to read-only memory. Below
is the C++ program to demonstrate segmentation fault:
C++
// segmentation fault
#include <iostream>
// Driver code
int main()
char *str;
// of data segment
str = "GeeksforGeeks";
// memory
*(str + 1) = 'n';
return 0;
Output:
3. Large memory Allocation/Large Static Memory
Allocation
In general, any compiler or any language will accept up to 10^8. However, to be on
the safe side we generally used up to 10^7. In the below code, the size of the array is
more than 10^8 so here we got an error due to large memory allocation. It is also
called an abort signal (SIGABRT).
Below is the C++ program to demonstrate large memory allocation runtime exception:
C++
// runtime exception
#include <iostream>
// Driver code
int main()
{
int a = 100000000000;
return 0;
Output:
C++
#include <iostream>
int main()
scanf("%d", &a);
return 0;
Output:
prog.cpp: In function ‘int main()’:
prog.cpp:10:19: warning: format ‘%d’ expects argument of type ‘int*’, but argument
2 has type ‘long long int*’ [-Wformat=]
scanf(“%d”, &a);
^
C++
// runtime
#include <iostream>
int arr[5];
// Driver code
int main()
int a = arr[-10];
cout << a;
return 0;
Output
281923776
// a syntax error
#include <iostream>
int main() {
return 0;
Output:
Syntax Error
2. Runtime Errors
This type of error occurs while the program is running. Because this is not a
compilation error, the compilation will be completed successfully.
These errors occur due to segmentation fault when a number is divided by division
operator or modulo division operator.
Example: Let us consider an array of length 5 i.e. array[5], but during runtime, if we
try to access 10 elements i.e array[10] then we get segmentation fault errors called
runtime errors. Giving only an array length of 5
C++
// a runtime error
#include <iostream>
int main()
{
int array[5];
return 0;
But in output trying to access more than 5 i.e if we try to access array[10] during
runtime then we get an error.
Output:
Segmentation fault
3. Logical Errors
Even if the syntax and other factors are correct, we may not get the desired results due
to logical issues. These are referred to as logical errors. We sometimes put a
semicolon after a loop, which is syntactically correct but results in one blank loop. In
that case, it will display the desired output.
Example: In the below example, the for loop iterates 5 times but the output will be
displayed only one time due to the semicolon at the end of for loop. These kinds of
errors are called logical errors.
C++
// a logical error
#include <iostream>
int main() {
int j;
for(j=0;j<=5;j++);
return 0;
Output
Geeks for geeks
4. Linker Errors
When the program is successfully compiled and attempting to link the different object
files with the main object file, errors will occur. When this error occurs, the
executable is not generated. This could be due to incorrect function prototyping, an
incorrect header file, or other factors. If main() is written as Main(), a linked error will
be generated.
Example:
C++
// a linker error
#include <iostream>
using namespace std;
int Main() {
return 0;
Output:
Linker Error
5. Semantic Errors
When a sentence is syntactically correct but has no meaning, semantic errors occur.
This is similar to grammatical errors. If an expression is entered on the left side of the
assignment operator, a semantic error may occur.
Example:
C++
#include <iostream>
int main()
a + b = c;
cout << c;
return 0;
Output:
Semantic Error
C++ Program to Handle the Exception
Methods
Last Updated : 30 Jun, 2022
Exception handling is a manner to handle the runtime error, we carry out exception
handling, so, the normal flow of the program may be maintained even after runtime
errors. Exceptions are runtime anomalies or abnormal conditions that a program
encounters during its execution.
The Exception Handling mechanism offers a way to transfer control from one part of
a program to another, This makes it clean to separate the mistake handling code from
the code written to address the real functionality of the program.
C++ provides the following specialized keywords for exception handling:
1. try: A block of code that may throw an exception is typically placed inside the try
block, It’s followed by one or extra seize blocks. If an exception happens, it is
thrown from the try block.
2. catch: This block catches the exception thrown from the try block, code to address
the exception is written inside this catch block.
3. throw: throw keyword is used to throw an exception. Also used to list the
exceptions that a function throws but doesn’t handle itself.
Syntax:
try
{
// Block of code to try
#include <iostream>
// Driver code
int main()
int numerator = 5;
int denominator = 0;
Output:
Floating-point exception (SIGFPE)
The above program will show an abnormal behavior and the output will not be
displayed. An exception is being thrown in the code but it is not being caught so either
it will show a floating-point exception or not display any output.
Below is the C++ program to handle divide by zero exception:
C++
#include <iostream>
// Driver code
int main()
int numerator = 5;
int denominator = 0;
int result;
try
if(denominator == 0)
throw denominator;
catch(int ex)
ex << endl;
return 0;
}
Output
Exception: Divide by zero not allowed :0
Division Result is: 4197440
Example 2: Below is the C++ program to input an age integer if the age is less than
18 then return NO, but if the age is greater than or equal to 18 then return Yes:
C++
#include <iostream>
// Driver code
int main()
try
{
int age = 10;
else
throw (age);
endl;
return 0;
Output
No, You must be at least 18 years old
Age is: 10
C++ defines a set of standard exceptions defined in <exception> which can be used in
the programs. These exceptions are arranged in the parent-child class hierarchy.
Below is the table listing the standard exceptions with description:
S.No
. Exception Description
C++
#include <iostream>
#include <exception>
return "GeeksforGeeks";
};
// Driver code
int main()
try
{
throw Exceptions();
catch(Exceptions& it)
endl;
catch(std::exception& it)
{}
Output
Customised Exception caught
GeeksforGeeks
An Exception is a run-time error, which occurs during the execution of a program,
that disrupts the normal flow of the program’s instructions. For example, Lack of
Memory, Lack of Disk Space, Dividing by zero, etc.
Types of Exceptions
There are two types of Exceptions, Built-in Exceptions, and User-Defined Exceptions.
Built-in Exceptions can be divided into 2 main categories:
1. Checked Exception: These are the compile-time exceptions because these
exceptions are checked by the compiler at the compile-time. The compile ensures
whether the programmer handles the exception or not.
2. Unchecked Exception: The compiler will not check the unchecked exceptions at
compile time. It occurs when the sure inputs bad input during interaction with the
program.
What are Checked Exceptions?
The exception is checked by the compiler for smooth execution of the program at
runtime.
Checked exceptions commonly occur exception. So, the compiler takes very much
care about these exceptions.
It is possible that a method declares that it can throw an exception, but actually it
does not. Still, the caller has to deal with it.
The checked exception declaration has a domino effect. Any methods that will use
the previous method will also have to handle the checked exception.
The Exception class is the base class from which exceptions inherit. For example, the
InvalidCastException class hierarchy is as follows: Object. Exception.
SystemException.
Why exceptions aren’t checked by the compiler in C++?
C++ provides a syntax for checked exceptions.
Example:
void G() throw(Exception);
void f() throw();
Exceptions are not checked by the compiler in C++ for 3 reasons:
1. C++ exception specifications inhibit optimization: With the exception possibly
of throw(), compilers insert extra code to check that when you throw an exception, it
matches the exception specification of functions during a stack unwind. Way to make
your program slower.
2. C++ exception specifications are not compiler-enforced: As far as your compiler
is concerned, the following is syntactically correct:
void AStupidFunction() throw()
{
throw 42;
}
If the exception specification is violated then the program terminates the execution.
3. C++ exception specifications are part of a function’s signature: If you have a
base class with a virtual function and try to override it, the exception specifications
must match exactly. So, you’d better plan ahead, and it’s still a pain.
struct A
{
virtual int value() const throw()
{
return 10;
}
}
struct B : public A
{
// ERROR!
virtual int value() const
{
return functionThatCanThrow();
}
}
Exception specifications give you these problems, and the gain for using them is
minimal. In contrast, if you avoid exception specifications altogether, coding is easier
and you avoid this stuff.
Exception Handling
Exception Handling is a process to handle runtime errors. We perform exception
handling. So, the normal flow of the program can be maintained even after runtime
errors. It is designed to handle synchronous exceptions only in the program. C++
exception handling is built upon three keywords: try, catch, and throw.
1. try Block: A block of code containing other code that could potentially have an
exception.
Syntax:
try{
statement1;
statement2;
}
2. catch: This handles the exception with some sort of solution.
Syntax:
try{
statement1;
statement2;
}
catch (argument)
{
// Action
statement3;
}
3. throw: This statement can be added anywhere after some kind of exception
condition.
throw(excep);
throw excep;
throw; // re-throw
C++
// exceptions
#include <iostream>
// is 0 or not.
if (b == 0)
}
// Driver code
int main()
int x = 50;
int y = 0;
int answer = 0;
/*
*/
try
}
// Printing the thrown exception from
// the function
return 0;
Output:
Division by zero!
Exceptions are run-time errors or abnormal conditions that a program may encounter
during execution.
Examples:
Division by zero
Access to an array out of its bounds
Running out of memory
Running out of disk space
Types of Exceptions:
Synchronous Exceptions: The exceptions which occur during the program
execution due to some fault in the input data. For example, Errors such as
overflow, and division by zero.
Asynchronous Exceptions: The exceptions caused by events or faults unrelated
(extended) to the program and beyond the control of the program. For example
Keyboard failures, and hardware disk failures.
The exception handling in C++ is designed to handle only synchronous exceptions in
a program. The goal of exception handling is to create a routine that checks and sends
an exceptional condition in order to execute suitable code. The procedure needs to
carry out the following responsibilities:
Detect the problem(Hit the exception)
Tells about error detection(throw the exception)
Receive error information(Catch the exception)
Take corrective action(Handle the exception)
The keywords try, throw, and catch. The keyword try is used to preface a block of
code which may result in exceptions.
Syntax of try statement:
try{
statement1;
statement2;
}
When an exception is found, it is thrown using a throw statement in the try block.
Syntax of the throw statement
throw(excep);
throw excep;
throw;// re-throwing of an exception
A catch block is defined by the keyword ‘catch‘ the exception and handles it
accordingly. The catch block that catches an exception must immediately follow the
try block of the exception.
Syntax of catch statement:
try{
statement1;
statement2;
}
catch (argument)
{
statement3;// action to be taken
}
When an exception is found, the execution of the catch block starts. The catch
statement may or may not contains an argument of exception type, it is optional.
When an argument is declared in the catch, the argument can be used in the catch
block. After the execution of the catch block, the lines inside the blocks are executed.
In case no exception is found, the catch block is ignored and if a mismatch is found,
the program is finished.
#include <iostream>
int main()
try {
if (Gfg2 != 0)
else
return 0;
Output:
Division by zero: 0
C++ Program to illustrate Array Index Out of Bounds Exception
C++
// exception
#include <iostream>
// initialize an array of
// 5
int a[5] = { 1, 2, 3, 4, 5 }, i;
try {
i = 0; // initialize i with 0
// size 5
while (1) {
if (i != 5) {
i++;
}
// if i go beyond 5 then throw exception
else
throw i;
catch (int i) {
<< endl;
return 0;
Output:
1
2
3
4
5
Array Index out of Bounds Exception: 5
C++ Program to Throw Multiple Exceptions and Define Multiple Catch
Statements
C++
// C++ program to throw multiple
#include <iostream>
void num(int k)
try {
if (k == 0)
else if (k > 0)
else if (k < 0)
throw 1.0; // throwing double value
catch (char g) {
catch (int j) {
catch (double f) {
int main()
return 0;
Output:
Demo of Multiple catches
caught an null value
*** end of try catch ***
We use Exception Handling to overcome exceptions occurred in execution of a
program in a systematic manner.
Dividing a number by Zero is a mathematical error (not defined) and we can use
exception handling to gracefully overcome such operations. If you write a code
without using exception handling then the output of division by zero will be shown as
infinity which cannot be further processed.
Consider the code given below, the Division function returns the result of numerator
divided by denominator which is stored in the variable result in the main and then
displayed. This Division function does not have any rumination for denominator being
zero.
// Exception Handling
#include <iostream>
} // end Division
int main()
// and 0 in denominator
float denominator = 0;
float result;
} // end main
Output:
The quotient of 12.5/0 is inf
We can handle this exception in a number of different ways, some of which are listed
below
1) Using the runtime_error class
The runtime_error class is a derived class of Standard Library class exception,
defined in exception header file for representing runtime errors.
Now we consider the exact same code but included with handling the division by
zero possibility. Here, we have the try block inside main that calls the Division
function. The Division function checks if the denominator passed is equal to zero
if no it returns the quotient, if yes it throws a runtime_error exception. This
Exception is caught by the catch block which prints the message “Exception
occurred” and then calls the what function with runtime_error object e. The what()
function {used in the code given below} is a virtual function of the class Standard
exception defined in stdexcept header file, it is used to identify the exception. This
prints the message “Math error: Attempted to divide by Zero”, after which the
program resumes the ordinary sequence of instructions.
#include <iostream>
{
// If denominator is Zero
// throw runtime_error
if (den == 0) {
} // end Division
int main()
numerator = 12.5;
denominator = 0;
catch (runtime_error& e) {
<< e.what();
}
} // end main
Output:
Exception occurred
Math error: Attempted to divide by Zero
2) Using User defined exception handling
Here we define a class Exception that publicly inherits from runtime_error class.
Inside the class Exception, we define only a constructor that will display the
message “Math error: Attempted to divide by Zero” when called using the class
object. We define the Division function that calls the constructor of class
Exception when denominator is zero otherwise returns the quotient. Inside of main
we give some values to numerator and denominator, 12.5 and 0 respectively. Then
we come to the try block that calls the Division function which will either return
the quotient or throw an exception. The catch block catches the exception of type
Exception, displays the message “Exception occurred” and then calls the what
function. After the exception is handled the program resumes.
#include <iostream>
#include <stdexcept>
public:
Exception()
};
{
// If denominator is Zero
if (den == 0)
throw Exception();
} // end Division
int main()
numerator = 12.5;
denominator = 0;
// of type Exception
catch (Exception& e) {
<< e.what();
}
} // end main
Output:
Exception occurred
Math error: Attempted to divide by Zero
3) Using Stack Unwinding
In stack unwinding we have the main inside which the try block calls the Division
function which in turn calls the CheckDenominator function. The
CheckDenominator function checks if denominator is zero, if true throws an
exception otherwise returns the value of denominator. The Division function
calculates the value of quotient {if non-zero value of denominator was passed} and
returns the same to the main. The catch block catches any exception thrown and
displays the message “Exception occurred” and calls the what function which
prints “Math error: Attempted to divide by zero”. After this the program resumes.
#include <iostream>
#include <stdexcept>
// if denominator is zero
// throw exception
if (den == 0) {
else
return den;
} // end CheckDenominator
} // end Division
int main()
numerator = 12.5;
denominator = 0;
try {
catch (runtime_error& e) {
// prints that exception has occurred
// runtime_error class
<< e.what();
} // end main
Output:
Exception occurred
Math error: Attempted to divide by zero
4) Using try and catch(…)
In this code the try block calls the CheckDenominator function. In
CheckDenominator function we check if denominator is zero, if true throw an
exception by passing a string “Error”. This string is caught by the catch block and
therefore prints the message “Exception occurred”. The catch block here is capable
of catching exception of any type.
#include <iostream>
#include <stdexcept>
using namespace std;
// defining CheckDenominator
if (den == 0)
throw "Error";
else
return den;
} // end CheckDenominator
int main()
numerator = 12.5;
denominator = 0;
// try block
try {
if (CheckDenominator(denominator)) {
// catch block
catch (...) {
} // end main
Output:
Exception occurred
#include <iostream>
int main()
return 0;
int c()
int a = 3;
int b = 6;
Output
3
C++ allows Multithreading by using the ‘thread’ header file. The program acts as one
thread but to increase program execution time/performance we can use threads to run
parts of the program concurrently. But it may lead to issues of memory consistency
errors and may not give us the proper output. Threads are used to improve the
performance of applications by running processes parallel to each other.
The thread may share the same resource or reference pointer. Two or more threads
may refer to the same object or share some common resource and they try to update or
make changes independently on shared resource data which can leave data
inconsistent.
Example: In the below C++ program, two threads are used to use the same functions.
First, it should run for thread 1 and then for thread 2. But to show memory
consistency for sharing the same resource/function output is not consistent.
C++14
// memory consistency
#include <bits/stdc++.h>
#include <thread>
class thread_obj {
public:
void operator()(int x)
{
for (int i = 0; i < 50; i++)
};
// Driver code
int main()
// thread 1
// thread 2
th1.join();
// wait for thread2 to join
th2.join();
return 0;
}
Output – You can see inconsistency in output (It is machine Dependent)
Example 2: In the below C++ program, an attempt will be made to access the same
value from different threads as one can see memory consistency errors as both threads
will run concurrently.
C++
// consistency error
#include <iostream>
#include <thread>
int x = 100;
void thread_function()
x--;
x << "\n";
}
// Driver code
int main()
std::thread t(&thread_function);
x++;
x << "\n";
return 0;
}
Output – You can see inconsistency in output (It is machine Dependent)
We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a
vector or array (items with random access)
It generally takes two parameters, the first one being the point of the array/vector from
where the sorting needs to begin and the second parameter being the length up to
which we want the array/vector to get sorted. The third parameter is optional and can
be used in cases such as if we want to sort the elements lexicographically.
By default, the sort() function sorts the elements in ascending order.
Below is a simple program to show the working of sort().
CPP
// sort() in STL.
#include <bits/stdc++.h>
int main()
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
be sorted*/
return 0;
Output
Array after sorting using default sort is :
0 1 2 3 4 5 6 7 8 9
Time Complexity: O(N log N)
Auxiliary Space: O(1)
How to sort in descending order?
sort() takes a third parameter that is used to specify the order in which elements are to
be sorted. We can pass the “greater()” function to sort in descending order. This
function does a comparison in a way that puts greater elements before.
CPP
// greater<>().
#include <bits/stdc++.h>
int main()
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
return 0;
}
Output
Array after sorting :
9 8 7 6 5 4 3 2 1 0
Time Complexity: O(N log N)
Auxiliary Space: O(1)
Sort the array only in the given range: To deal with such types of problems we just
have to mention the range inside the sort function.
Below is the implementation of above case:
C++
#include <bits/stdc++.h>
int main()
int arr[] = { 0, 1, 5, 8, 9, 6, 7, 3, 4, 2 };
// (n-1)
return 0;
Output
Array after sorting :
0 1 2 3 4 5 6 7 8 9
Time Complexity: O(N log N)
Auxiliary Space: O(1)
How to sort in a particular order?
We can also write our own comparator function and pass it as a third parameter. This
“comparator” function returns a value; convertible to bool, which basically tells us
whether the passed “first” argument should be placed before the passed “second”
argument or not.
For eg: In the code below, suppose intervals {6,8} and {1,9} are passed as arguments
in the “compareInterval” function(comparator function). Now as i1.first (=6) < i2.first
(=1), so our function returns “false”, which tells us that “first” argument should not be
placed before “second” argument and so sorting will be done in order like {1,9} first
and then {6,8} as next.
CPP
#include <bits/stdc++.h>
struct Interval {
};
int main()
Interval arr[]
= { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
// start time
return 0;
}
Output
Intervals sorted by start time :
[1,9] [2,4] [4,7] [6,8]
The time complexity of std::sort() is:
1. Best Case – O(N log N)
2. Average Case – O(N log N)
3. Worst-Case – O(N log N)
Space Complexity: It may use O( log N) auxiliary space.
C++
#include <algorithm>
#include <iostream>
public:
};
int main()
int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int asize = sizeof(a) / sizeof(int);
show(a, asize);
cout << endl << "The array after sorting is(asc) :";
sort(a, a + asize);
show(a, asize);
cout << endl << "The array after sorting is(desc) :";
show(a, asize);
show(a, asize);
show(a, asize);
return 0;
Output
The array before sorting is : 1 5 8 9 6 7 3 4 2 0
The array after sorting is(asc) :0 1 2 3 4 5 6 7 8 9
The array after sorting is(desc) :9 8 7 6 5 4 3 2 1 0
The array after sorting is(asc but our comparator class) :0 1 2 3 4 5
6 7 8 9
The array after sorting is(asc but our comparator function) :0 1 2 3 4
5 6 7 8 9
Time Complexity: O(N log N)
Auxiliary Space: O(1)
nitialize a vector in C++ (7 different ways)
Last Updated : 13 Mar, 2024
The following are different ways to construct or initialize a vector in C++ STL
1. Initializing by pushing values one by one:
C++
// by one.
#include <iostream>
#include <vector>
int main()
vector<int> vect;
vect.push_back(10);
vect.push_back(20);
vect.push_back(30);
return 0;
}
Output
10 20 30
2. Specifying size and initializing all values:
C++
// by one.
#include <iostream>
#include <vector>
int main()
int n = 3;
return 0;
Output
10 10 10
3. Initializing like arrays:
C++
#include <iostream>
#include <vector>
int main()
{
vector<int> vect{ 10, 20, 30 };
return 0;
Output
10 20 30
4. Initializing from an array:
C++
#include <iostream>
#include <vector>
int main()
{
return 0;
Output
10 20 30
5. Initializing from another vector:
C++
// another vector.
#include <iostream>
#include <vector>
int main()
return 0;
Output
10 20 30
6. Initializing all elements with a particular value:
C++
#include <vector>
int main()
vector<int> vect1(10);
int value = 5;
// printing vector
Output
5 5 5 5 5 5 5 5 5 5
7. Initialize an array with consecutive numbers using std::iota:
C++
// numbers
#include <iostream>
#include <numeric>
#include <vector>
int main()
vector<int> vec(5);
// initializing using iota()
return 0;
Output
1 2 3 4 5
In the case of arrays, there is not much choice to copy an array into another, other than
the iterative method i.e running a loop to copy each element at its respective index.
But Vector classes have more than one method for copying entire vectors into others
in easier ways.
There are basically two types of copying:-
Method 1: Iterative method. This method is a general method to copy, in this
method a loop is used to push_back() the old vector elements into the new vector.
They are deeply copied
CPP
// by iterative method.
#include<iostream>
#include<vector>
int main()
vector<int> vect2;
vect2.push_back(vect1[i]);
cout<< endl;
// copy is created.
vect1[0] = 2;
cout << "The first element of old vector is :";
return 0;
Output
Old vector elements are : 1 2 3 4
New vector elements are : 1 2 3 4
The first element of old vector is :2
The first element of new vector is :1
In the above code, changing the value at one vector did not alter the value at another
vector, hence they are not allocated at the same address, hence deep copy.
Method 2: By assignment “=” operator. Simply assigning the new vector to the old
one copies the vector. This way of assignment is not possible in the case of arrays.
CPP
// by iterative method.
#include<iostream>
#include<vector>
using namespace std;
int main()
vector<int> vect2;
// vector to other
vect2 = vect1;
cout<< endl;
// copy is created.
vect1[0] = 2;
return 0;
Output
Old vector elements are : 1 2 3 4
New vector elements are : 1 2 3 4
The first element of old vector is :2
The first element of new vector is :1
Method 3: By passing vector as constructor. At the time of declaration of vector,
passing an old initialized vector copies the elements of the passed vector into the
newly declared vector. They are deeply copied.
CPP
// by constructor method.
#include<bits/stdc++.h>
int main()
vector<int> vect2(vect1);
cout << "Old vector elements are : ";
cout<< endl;
// copy is created.
vect1[0] = 2;
return 0;
Output
Old vector elements are : 1 2 3 4
New vector elements are : 1 2 3 4
The first element of old vector is :2
The first element of new vector is :1
Method 4: copy(first_iterator_o, last_iterator_o, back_inserter()) :- This is
another way to copy old vector into new one. This function takes 3 arguments, first,
the first iterator of the old vector, second, the last iterator of the old vector and third is
back_inserter function to insert values from the back. This also generated a deep
copy.
CPP
#include<iostream>
int main()
vector<int> vect2;
cout<< endl;
// copy is created.
vect1[0] = 2;
return 0;
Output
Old vector elements are : 1 2 3 4
New vector elements are : 1 2 3 4
The first element of old vector is :2
The first element of new vector is :1
Method 5: assign(first_iterator_o, last_iterator_o):
This method assigns the same values to the new vector as the old one. This takes 2
arguments, the first iterator to the old vector and the last iterator to the old vector. This
generates a deep copy.
CPP
// by assign()
#include<iostream>
int main()
vector<int> vect2;
// Copying vector by assign function
vect2.assign(vect1.begin(), vect1.end());
cout<< endl;
// copy is created.
vect1[0] = 2;
cout << "The first element of old vector is :";
return 0;
Output
Old vector elements are : 1 2 3 4
New vector elements are : 1 2 3 4
The first element of old vector is :2
The first element of new vector is :1
Method 6: By using insert function. The vector class has a standard
function, insert(), that can insert elements from a specified range.
C++
// by instert() function
#include<iostream>
int main()
vector<int> vect2;
cout<< endl;
// copy is created.
vect1[0] = 2;
return 0;
Output
Old vector elements are : 1 2 3 4
New vector elements are : 1 2 3 4
The first element of old vector is :2
The first element of new vector is :1
Some of the merge operation classes are provided in C++ STL under the header file
“algorithm”, which facilitates several merge operations in a easy manner.
Some of them are mentioned below.
1. merge(beg1, end1, beg2, end2, beg3) :- This function merges two sorted
containers and stores in new container in sorted order (merge sort). It takes 5
arguments, first and last iterator of 1st container, first and last iterator of 2nd
container and 1st iterator of resultant container.
2. includes(beg1, end1, beg2, end2) :- This function is used to check whether one
sorted container elements are including other sorted container elements or not.
Returns true if 1st container includes 2nd container else returns false.
CPP
#include<iostream>
int main()
// for merging
vector<int> v3(12);
v2.end(), v3.begin());
// Displaying resultant container
return 0;
Output
The new container after merging is :
1 1 3 4 5 5 6 7 20 25 30 30
v4 includes v1
Time complexity:
The time complexity of the merge() and include() functions is O(n1 + n2) where n1
and n2 are the sizes of the two containers being merged or checked, respectively.
Space complexity:
The space complexity of the merge() and include() functions is O(n1 + n2) where n1
and n2 are the sizes of the two containers being merged or checked, respectively. This
is due to the fact that both functions require an additional container of a size equal to
the sum of the sizes of the two containers being merged or checked.
inplace_merge(beg1, beg2, end) :- This function is used to sort two consecutively
placed sorted ranges in a single container. It takes 3 arguments, iterator to beginning
of 1st sorted range, iterator to beginning of 2nd sorted range, and iterator to last
position.
CPP
// inplace_merge()
#include<iostream>
int main()
// for inplace_merge()
vector<int> v3(12);
// one container
inplace_merge(v3.begin(),it,v3.end());
return 0;
Output:
The new container after inplace_merging is :
1 1 3 4 5 5 6 7 20 25 30 30
set_union(beg1, end1, beg2, end2, beg3) :- This function computes the set union of
two containers and stores in new container .It returns the iterator to the last element of
resultant container. It takes 5 arguments, first and last iterator of 1st container, first
and last iterator of 2nd container and 1st iterator of resultant container . The
containers should be sorted and it is necessary that new container is resized to suitable
size.
set_intersection(beg1, end1, beg2, end2, beg3) :- This function computes the set
intersection of two containers and stores in new container .It returns the iterator to the
last element of resultant container. It takes 5 arguments, first and last iterator of 1st
container, first and last iterator of 2nd container and 1st iterator of resultant container .
The containers should be sorted and it is necessary that new container is resized to
suitable size.
One way to implement set-union and set-intersection in sorted ranges can be
found here
CPP
// C++ code to demonstrate the working of
#include<iostream>
int main()
// for union
vector<int> v3(10);
// Declaring resultant vector
// for intersection
vector<int> v4(10);
v2.end(), v3.begin());
v3.resize(it - v3.begin());
return 0;
Output:
Union of two containers is : 1 3 4 5 6 7 20 25 30
Intersection of two containers is : 1 5 30
set_difference(beg1, end1, beg2, end2, beg3) :- This function computes the set
difference of two containers and stores in new container .It returns the iterator to the
last element of resultant container. It takes 5 arguments, first and last iterator of 1st
container, first and last iterator of 2nd container and 1st iterator of resultant container .
The containers should be sorted and it is necessary that new container is resized to
suitable size.
set_symmetric_difference(beg1, end1, beg2, end2, beg3) :- This function computes
the set symmetric difference of two containers and stores in new container .It returns
the iterator to the last element of resultant container. It takes 5 arguments, first and
last iterator of 1st container, first and last iterator of 2nd container and 1st iterator of
resultant container . The containers should be sorted and it is necessary that new
container is resized to suitable size.
CPP
#include<iostream>
int main()
// for difference
vector<int> v3(10);
// for symmetric_difference
vector<int> v4(10);
v3.resize(it - v3.begin());
v4.resize(it1 - v4.begin());
return 0;
Output:
Difference of two containers is : 3 4 20
Symmetric difference of two containers is : 3 4 6 7 20 25
The time complexity of set_difference() and set_symmetric_difference() is O(m+n)
where m and n are the size of the two input containers.
The space complexity of both the functions is O(m+n) as the resulting vector would
take the same size as the combined size of the two input vectors.
std::transform() in C++ STL (Perform an
operation on all elements)
Last Updated : 03 Jan, 2023
Consider the problem of adding contents of two arrays into a third array. It is given
that all arrays are of same size.
Following is simple C++ program without transform().
CPP
int main()
int n = sizeof(arr1)/sizeof(arr1[0]);
int res[n];
}
Output
5 7 9
Time Complexity: O(N) , where N is size of array.
Auxiliary Space: (N)
Using transform function of STL, we can add arrays in single line.
C++
#include <bits/stdc++.h>
int main()
int n = sizeof(arr1)/sizeof(arr1[0]);
int res[n];
Output
5 7 9
transform() in C++ is used in two forms:
1. Unary Operation : Applies a unary operator on input to convert into output
transform(Iterator inputBegin, Iterator inputEnd,
Iterator OutputBegin, unary_operation)
Following is C++ example.
C++
#include <bits/stdc++.h>
int n = sizeof(arr)/sizeof(arr[0]);
// back in arr[]
return 0;
Output
2 3 4 5 6
2. Binary Operation: Applies a binary operator on input to convert into output
transform(Iterator inputBegin1, Iterator inputEnd1,
Iterator inputBegin2, Iterator OutputBegin,
binary_operation)
The example mentioned above for adding two arrays is an example of transform with
binary operation.
More examples:
We can use transform to convert a string to upper case (See this)
We can modify above examples for vectors also.
Double-ended queues are sequence containers with the feature of expansion and
contraction on both ends. They are similar to vectors, but are more efficient in case of
insertion and deletion of elements. Unlike vectors, contiguous storage allocation may
not be guaranteed.
Double Ended Queues are basically an implementation of the data structure double-
ended queue. A queue data structure allows insertion only at the end and deletion
from the front. This is like a queue in real life, wherein people are removed from the
front and added at the back. Double-ended queues are a special case of queues where
insertion and deletion operations are possible at both the ends.
The functions for deque are same as vector, with an addition of push and pop
operations for both front and back.
The time complexities for doing various operations on deques are-
Accessing Elements- O(1)
Insertion or removal of elements- O(N)
Insertion or removal of elements at start or end- O(1)
CPP
#include <iostream>
void showdq(deque<int> g)
deque<int>::iterator it;
int main()
deque<int> gquiz;
gquiz.push_back(10);
gquiz.push_front(20);
gquiz.push_back(30);
gquiz.push_front(15);
showdq(gquiz);
gquiz.pop_front();
showdq(gquiz);
gquiz.pop_back();
showdq(gquiz);
return 0;
Output
The deque gquiz is : 15 20 10 30
gquiz.size() : 4
gquiz.max_size() : 4611686018427387903
gquiz.at(2) : 10
gquiz.front() : 15
gquiz.back() : 30
gquiz.pop_front() : 20 10 30
gquiz.pop_back() : 20 10
Time complexity: O(1).
Space complexity: O(1).
Methods of Deque
Method Definition
A C++ priority queue is a type of container adapter, specifically designed such that
the first element of the queue is either the greatest or the smallest of all elements in
the queue, and elements are in non-increasing or non-decreasing order (hence we can
see that each element of the queue has a priority {fixed order}).
In C++ STL, the top element is always the greatest by default. We can also change it
to the smallest element at the top. Priority queues are built on the top of the max heap
and use an array or vector as an internal structure. In simple terms, STL Priority
Queue is the implementation of Heap Data Structure.
Syntax:
std::priority_queue<int> pq;
Example:
C++
#include <iostream>
#include <queue>
using namespace std;
// driver code
int main()
priority_queue<int> pq;
// printing array
while (!pq.empty()) {
pq.pop();
return 0;
Output
Array: 10 2 4 8 6 9
Priority Queue: 10 9 8 6 4 2
Max Heap Priority Queue (default scheme)
#include <iostream>
#include <queue>
void showpq(
while (!g.empty()) {
g.pop();
}
cout << '\n';
// Driver Code
int main()
showArray(arr, 6);
showpq(gquiz);
return 0;
Output
Array: 10 2 4 8 6 9
Priority Queue : 2 4 6 8 9 10
Min Heap Priority Queue
Note: The above syntax may be difficult to remember, so in case of numeric values,
we can multiply the values with -1 and use max heap to get the effect of min heap. Not
only that we can use custom sorting method by replacing greater with custom
comparator function.
Methods of Priority Queue
The following list of all the methods of std::priority_queue class:
Method Definition
The push() method is used to insert an element into the priority queue. To remove an
element from the priority queue the pop() method is used because this removes the
element with the highest priority.
Below is the C++ program for various functions in the priority queue:
C++
// C++ Program to demonstrate various
#include <iostream>
#include <queue>
priority_queue<int> g = gq;
while (!g.empty()) {
g.pop();
// Driver Code
int main()
priority_queue<int> gquiz;
gquiz.push(10);
gquiz.push(30);
gquiz.push(20);
gquiz.push(5);
gquiz.push(1);
showpq(gquiz);
// in priority queue
gquiz.top();
gquiz.pop();
showpq(gquiz);
return 0;
Output
The priority queue gquiz is : 30 20 10 5 1
gquiz.size() : 5
gquiz.top() : 30
gquiz.pop() : 20 10 5 1
Refer end for complexity analysis.
Note: Above shown is one of the methods of priority queue initialization. To know
more about efficient initialization of priority queue, click here.
The top element of the Priority Queue could be accessed using the top() method.
C++
#include <iostream>
#include <queue>
// Driver code
int main()
priority_queue<int> numbers;
numbers.push(1);
numbers.push(20);
numbers.push(7);
numbers.top();
return 0;
Output
Top element: 20
Refer end for complexity analysis.
Note: We can only access the top element in the priority queue.
We use the empty() method to check if the priority_queue is empty. This method
returns:
True – It is returned when the priority queue is empty and is represented by 1
False – It is produced when the priority queue is not empty or False and is
characterized by 0
Example:
C++
#include <iostream>
#include <queue>
// Driver code
int main()
priority_queue<int> pqueueGFG;
pqueueGFG.push(1);
if (pqueueGFG.empty())
else
{
return 0;
Output
Contains element or False
Refer end for complexity analysis.
It determines the size of a priority queue. In simple terms, the size() method is used to
get the number of elements present in the Priority Queue.
Below is the C++ program to check the size of the priority queue:
C++
#include <iostream>
#include <queue>
int main()
priority_queue<string> pqueue;
pqueue.push("Geeks");
pqueue.push("for");
pqueue.push("Geeks");
pqueue.push("C++");
return 0;
Output
Size of the queue: 4
Refer end for complexity analysis.
Swap() function is used to swap the contents of one priority queue with another
priority queue of same type and same or different size.
Below is the C++ program to swap contents of a priority queue with another of similar
type:
C++
#include <bits/stdc++.h>
while (!pq.empty()) {
pq.pop();
}
int main()
priority_queue<int> pq1;
priority_queue<int> pq2;
pq1.push(1);
pq1.push(2);
pq1.push(3);
pq1.push(4);
pq2.push(3);
pq2.push(5);
pq2.push(7);
pq2.push(9);
print(pq1);
print(pq2);
// queues
pq1.swap(pq2);
print(pq1);
return 0;
Output
Before swapping:-
Priority Queue 1 = 4 3 2 1
Priority Queue 2 = 9 7 5 3
After swapping:-
Priority Queue 1 = 9 7 5 3
Priority Queue 2 = 4 3 2 1
Refer end for complexity analysis.
Emplace() function is used to insert a new element into the priority queue container,
the new element is added to the priority queue according to its priority. It is similar to
push operation. The difference is that emplace() operation saves unnecessary copy of
the object.
Below is the C++ program to emplace a new element into the priority queue
container:
C++
#include <bits/stdc++.h>
int main()
priority_queue<int> pq;
pq.emplace(1);
pq.emplace(2);
pq.emplace(3);
pq.emplace(4);
pq.emplace(5);
pq.emplace(6);
while (!pq.empty()) {
pq.pop();
return 0;
Output
Priority Queue = 6 5 4 3 2 1
Refer end for complexity analysis.
C++
// C++ program to illustrate the
#include <bits/stdc++.h>
// Driver code
int main()
priority_queue<int>::value_type AnInt;
priority_queue<string>::value_type AString;
// Declares priority_queues
priority_queue<int> q1;
priority_queue<string> q2;
// Here AnInt acts as a variable of int data type
AnInt = 20;
cout << "The value_type is AnInt = " << AnInt << endl;
q1.push(AnInt);
AnInt = 30;
q1.push(AnInt);
AString = "geek";
<< endl;
q2.push(AString);
AString = "for";
q2.push(AString);
AString = "geeks";
q2.push(AString);
return 0;
Output
The value_type is AnInt = 20
Top element of the integer priority_queue is: 30
priority_queue
value_type O(1) O(1)
Maps are associative containers that store elements in a mapped fashion. Each
element has a key value and a mapped value. No two mapped values can have the
same key values.
std::map is the class template for map containers and it is defined inside the <map>
header file.
Basic std::map Member Functions
Some basic functions associated with std::map are:
begin() – Returns an iterator to the first element in the map.
end() – Returns an iterator to the theoretical element that follows the last element
in the map.
size() – Returns the number of elements in the map.
max_size() – Returns the maximum number of elements that the map can hold.
empty() – Returns whether the map is empty.
pair insert(keyvalue, mapvalue) – Adds a new element to the map.
erase(iterator position) – Removes the element at the position pointed by the
iterator.
erase(const g)– Removes the key-value ‘g’ from the map.
clear() – Removes all the elements from the map.
Examples of std::map
The following examples shows how to perform basic operations on map containers.
Example 1: begin() and end() Function
C++
#include <iostream>
#include <map>
#include <string>
int main()
mp["one"] = 1;
mp["two"] = 2;
mp["three"] = 3;
// map
++it;
}
return 0;
Output
Key: one, Value: 1
Key: three, Value: 3
Key: two, Value: 2
#include <iostream>
#include <map>
#include <string>
int main()
map["one"] = 1;
map["two"] = 2;
map["three"] = 3;
return 0;
Output
Size of map: 3
#include <iostream>
#include <iterator>
#include <map>
int main()
gquiz1[7] = 10;
<< '\n';
<< '\n';
gquiz2.erase(gquiz2.begin(), gquiz2.find(3));
<< '\n';
int num;
num = gquiz2.erase(4);
<< '\n';
<< endl;
<< endl;
return 0;
Output
The map gquiz1 is :
KEY ELEMENT
1 40
2 30
3 60
4 20
5 50
6 50
7 10
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
map["one"] = 1;
map["two"] = 2;
map["three"] = 3;
cout << "Key: one, Value: " << map["one"] << endl;
cout << "Key: two, Value: " << map["two"] << endl;
cout << "Key: three, Value: " << map["three"] << endl;
else {
return 0;
Output
Key: one, Value: 1
Key: two, Value: 2
Key: three, Value: 3
Key 'four' is not in the map
map::insert() Insert elements with a particular key in the map container –> O(log n)
map:: count() Returns the number of matches to element with key-value ‘g’ in the
map. –> O(log n)
Function Definition
map erase() Used to erase elements from the container –> O(log n)
map rbegin()
Returns a reverse iterator which points to the last element of the map.
map find() Returns an iterator to the element with key-value ‘g’ in the map if
found, else returns the iterator to end.
map cbegin() and cbegin() returns a constant iterator referring to the first element in the
cend() map container. cend() returns a constant iterator pointing to the
theoretical element that follows the last element in the multimap.
map emplace() Inserts the key and its element in the map container.
map max_size() Returns the maximum number of elements a map container can hold
–> O(1)
map
emplace_hint() Inserts the key and its element in the map container with a given hint.
map
Returns the object that determines how the elements in the map are
value_comp() ordered (‘<‘ by default).
map key_comp() Returns the object that determines how the elements in the map are
ordered (‘<‘ by default).
map::begin() and begin() returns an iterator to the first element in the map. end()
end() returns an iterator to the theoretical element that follows the last
element in the map
map::operator[] This operator is used to reference the element present at the position
given inside the operator.
map::at() and at() function is used to return the reference to the element associated
map::swap() with the key k. swap() function is used to exchange the contents of
Function Definition
two maps but the maps must be of the same type, although sizes may
differ.
Pair is used to combine together two values that may be of different data types. Pair
provides a way to store two heterogeneous objects as a single unit. It is basically used
if we want to store tuples. The pair container is a simple container defined
in <utility> header consisting of two data elements or objects.
The first element is referenced as ‘first’ and the second element as ‘second’ and
the order is fixed (first, second).
Pair can be assigned, copied, and compared. The array of objects allocated in
a map or hash_map is of type ‘pair’ by default in which all the ‘first’ elements are
unique keys associated with their ‘second’ value objects.
To access the elements, we use variable name followed by dot operator followed
by the keyword first or second.
Syntax:
pair <data_type1, data_type2> Pair_name
CPP
#include <iostream>
#include <utility>
int main()
// defining a pair
PAIR1.first = 100;
PAIR1.second = 'G';
return 0;
Output
100 G
Initializing a Pair: We can also initialize a pair.
Syntax:
pair <data_type1, data_type2> Pair_name (value1, value2) ;
Different ways to initialize pair:
pair g1; //default
pair g2(1, 'a'); //initialized, different data type
pair g3(1, 10); //initialized, same data type
pair g4(g3); //copy of g3
Another way to initialize a pair is by using the make_pair() function.
g2 = make_pair(1, 'a');
Another valid syntax to declare pair is:
g2 = {1, 'a'};
CPP
#include <iostream>
#include <utility>
// Driver Code
int main()
// defining a pair
return 0;
Output
GeeksForGeeks 1.23
Note: If not initialized, the first value of the pair gets automatically initialized.
C++
#include <iostream>
#include <utility>
int main()
{
// it is initialised to 0
// it is initialised to 0
Output:
00
Member Functions
1) make_pair(): This template function allows to create a value pair without writing
the types explicitly.
Syntax:
Pair_name = make_pair (value1,value2);
CPP
// function in pair
#include <iostream>
#include <utility>
// Driver Code
int main()
PAIR1.first = 100;
PAIR1.second = 'G';
return 0;
}
Output
100 G
GeeksForGeeks 1.23
GeeksForGeeks is Best 4.56
2) swap: This function swaps the contents of one pair object with the contents of
another pair object. The pairs must be of the same type.
Syntax:
pair1.swap(pair2) ;
For two given pairs say pair1 and pair2 of the same type, the swap function will swap
the pair1.first with pair2.first and pair1.second with pair2.second.
CPP
// function in pair
#include <iostream>
#include <utility>
// Driver Code
int main()
{
cout << "Contents of pair1 = " << pair1.first << " "
<< pair1.second;
cout << "Contents of pair2 = " << pair2.first << " "
<< pair2.second;
pair1.swap(pair2);
cout << "Contents of pair1 = " << pair1.first << " "
<< pair1.second;
cout << "Contents of pair2 = " << pair2.first << " "
<< pair2.second;
return 0;
}
Output
Before swapping:
Contents of pair1 = A 1Contents of pair2 = B 2
After swapping:
Contents of pair1 = B 2Contents of pair2 = A 1
3) tie(): This function works the same as in tuples. It creates a tuple of lvalue
references to its arguments i.e., to unpack the tuple (or here pair) values into separate
variables. Just like in tuples, here are also two variants of the tie, with and without
“ignore”. “ignore” keyword ignores a particular tuple element from getting unpacked.
However, tuples can have multiple arguments but pairs only have two arguments. So,
in the case of pair of pairs, unpacking needs to be explicitly handled.
Syntax:
tie(int &, int &) = pair1;
CPP
#include <bits/stdc++.h>
// Driver Code
int main()
{
pair<int, int> pair1 = { 1, 2 };
int a, b;
tie(a, b) = pair1;
int x, y;
char z;
tie(x,ignore) = pair3;
tie(y, z) = pair3.second;
cout << x << " " << y << " " << z << "\n";
// contributed by sarthak_eddy.
Output
1 2
3 2
3 4 a
Code to illustrate Functions in Pair:
CPP
#include <iostream>
#include <string>
#include <utility>
g1 = make_pair(string("Geeks"), 1);
g2.first = ".com";
g2.second = 2;
cout << "This is pair g" << g1.second << " with "
<< endl;
cout << "This is pair g" << g3.second << " with value "
<< g3.first
<< endl;
cout << "This is pair g" << g2.second << " with value "
<< endl;
<< endl;
<< "g1 has " << g1.first << " and g2 has "
swap(g1, g2);
<< "g1 has " << g1.first << " and g2 has "
<< g2.first;
return 0;
Output
This is pair g1 with value Geeks.
Multisets are a type of associative containers similar to the set, with the exception that
multiple elements can have the same values. Some Basic Functions associated with
multiset:
begin() – Returns an iterator to the first element in the multiset –> O(1)
end() – Returns an iterator to the theoretical element that follows the last element
in the multiset –> O(1)
size() – Returns the number of elements in the multiset –> O(1)
max_size() – Returns the maximum number of elements that the multiset can hold
–> O(1)
empty() – Returns whether the multiset is empty –> O(1)
insert (x) – Inserts the element x in the multiset –> O(log n)
clear () – Removes all the elements from the multiset –> O(n)
erase(x) – Removes all the occurrences of x –> O(log n)
Implementation:
CPP
// implementation of multiset
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main()
gquiz1.insert(40);
gquiz1.insert(30);
gquiz1.insert(60);
gquiz1.insert(20);
gquiz1.insert(50);
gquiz1.insert(50);
gquiz1.insert(10);
gquiz2.erase(gquiz2.begin(), gquiz2.find(30));
int num;
num = gquiz2.erase(50);
return 0;
}
Output
The multiset gquiz1 is :
60 50 50 40 30 20 10
gquiz1.lower_bound(40) :
40
gquiz1.upper_bound(40) :
30
gquiz2.lower_bound(40) :
40
gquiz2.upper_bound(40) :
60
Removing Element From Multiset Which Have Same Value:
a.erase() – Remove all instances of element from multiset having the same value
a.erase(a.find()) – Remove only one instance of element from multiset having
same value
The time complexities for doing various operations on Multisets are –
Insertion of Elements- O(log N)
Accessing Elements – O(log N)
Deleting Elements- O(log N)
C++
// same value
#include <bits/stdc++.h>
int main()
multiset<int> a;
a.insert(10);
a.insert(10);
a.insert(10);
// 10 from multiset
a.erase(a.find(10));
a.erase(10);
// multiset
Output
3
2
0
Time Complexity: O(max(?(log(i)),(K+log(n))), where i is the size of multiset at the
time of insertion, K is the total count of integers of the value passed, n is the size of
multiset.
Auxiliary Space: O(1).
Function Definition
iterator insert (iterator Adds a new element ‘g’ at the position pointed by the
position,const g) iterator.
the container.
#include <bits/stdc++.h>
int main()
reverse(a.begin(), a.end());
return 0;
Output
Vector: 1 45 54 71 76 12
Reversed Vector: 12 76 71 54 45 1
Given an array arr[], reverse this array using STL in C++. Example:
Input: arr[] = {1, 45, 54, 71, 76, 12}
Output: {12, 76, 71, 54, 45, 1}
CPP
#include <algorithm>
#include <iostream>
return 0;
Output:
Array: 1 45 54 71 76 12
Reversed Array: 12 76 71 54 45 1
Time Complexity: O(N) where N is the size of the array.
Auxiliary Space: O(1)
Stack of Pair in C++ STL with Examples
Last Updated : 25 Mar, 2020
Stack in STL Stacks are a type of container adaptors with LIFO(Last In First Out)
type of working, where a new element is added at one end and (top) an element is
removed from that end only.
Pair in STL The pair container is a simple container defined in header consisting of
two data elements or objects. The first element is referenced as ‘first’ and the second
element as ‘second’ and the order is fixed (first, second).
Stack of pair in STL: Stack of pair can be very efficient in designing complex data
structures.
Syntax:
stack<pair<datatype, datatype>> stack_of_pair;
Below is an example to show the Stack of Pairs:
// CPP program to demonstrate
#include <bits/stdc++.h>
{
while (!s.empty()) {
printPair(s.top());
s.pop();
// Driver code
int main()
s.push({ 1, 5 });
s.push({ 5, 10 });
s.push({ 7, 9 });
cout << "Stack of Pairs: ";
Showstack(s);
<< s.size();
printPair(s.top());
s.pop();
Showstack(s);
return 0;
Output:
Stack of Pairs: (7, 9) (5, 10) (1, 5) (15, 5) (10, 20)
Size of Stack of Pairs: 5
Top of Stack of Pairs: (7, 9)
C++
#include <bits/stdc++.h>
if (str.size() == 0)
return;
// add it to out
// Driver code
int main()
permute(str, "");
return 0;
Output
ABC
ACB
BCA
BAC
CAB
CBA
Time Complexity: O(n*n!)
Auxiliary Space: O(n)
Method 2 (using next_permutation)
We can use next_permutation that modifies a string so that it stores lexicographically
next permutation. If current string is lexicographically largest, i.e., “CBA”, then
next_permutation returns false.
We first sort the string, so that it is converted to lexicographically smallest
permutation. Then we one by one call next_permutation until it returns false.
C++
#include <bits/stdc++.h>
// using next_permutation
// ascending order
sort(str.begin(), str.end());
// is next permutation
do {
// Driver code
int main()
{
string str = "CBA";
permute(str);
return 0;
Output
ABC
ACB
BAC
BCA
CAB
CBA
Time Complexity: O(n*n!)
Auxiliary Space: O(1)
Note that the second method always prints permutations in lexicographically sorted
order irrespective of input string.
Given an array, the task is to print or display all the permutations of this array using
STL in C++.
Examples:
Input: a[] = {1, 2, 3}
Output:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
CPP
#include <bits/stdc++.h>
{
// Sort the given array
sort(a, a + n);
do {
display(a, n);
// Driver code
int main()
return 0;
Output:
Possible permutations are:
10 20 30 40
10 20 40 30
10 30 20 40
10 30 40 20
10 40 20 30
10 40 30 20
20 10 30 40
20 10 40 30
20 30 10 40
20 30 40 10
20 40 10 30
20 40 30 10
30 10 20 40
30 10 40 20
30 20 10 40
30 20 40 10
30 40 10 20
30 40 20 10
40 10 20 30
40 10 30 20
40 20 10 30
40 20 30 10
40 30 10 20
40 30 20 10
Given a Set, the task is to find the maximum and minimum element of this set in C++
STL. Examples:
Input: set={1, 6, 15, 10, 5}
Output: max = 15, min = 1
#include <bits/stdc++.h>
int max_element;
if (!my_set.empty())
max_element = *(my_set.rbegin());
// return the maximum element
return max_element;
int min_element;
if (!my_set.empty())
min_element = *my_set.begin();
return min_element;
}
int main()
set<int> my_set;
my_set.insert(1);
my_set.insert(6);
my_set.insert(15);
my_set.insert(10);
my_set.insert(5);
printSet(my_set);
<< endl;
<< findMax(my_set)
<< endl;
Output:
Set: 1 5 6 10 15
Minimum element: 1
Maximum element: 15
Time Complexity: O(n)
Auxiliary Space: O(n)
Using set.rbegin() and set.rend() methods Approach: Elements in a set are
stored in sorted order. So the minimum element of the set will reside in the first
element and the maximum element in the last element. Therefore, this first and last
element can be fetched with the help of set.rend() and set.rbegin() methods
respectively. Program:
CPP
#include <bits/stdc++.h>
if (!my_set.empty())
max_element = *my_set.rbegin();
return max_element;
int min_element;
if (!my_set.empty())
min_element = *(--my_set.rend());
int main()
set<int> my_set;
my_set.insert(1);
my_set.insert(6);
my_set.insert(15);
my_set.insert(10);
my_set.insert(5);
printSet(my_set);
// Get the minimum element
<< findMin(my_set)
<< endl;
<< findMax(my_set)
<< endl;
Output:
Set: 1 5 6 10 15
Minimum element: 1
Maximum element: 15
Prerequisite: Set
A Set is a container implemented in C++ language in STL and has a concept similar
to how the set is defined in mathematics. The fact that separates the set from the other
containers is that it contains only the distinct elements and elements can be traversed
in sorted order. Having the stronghold on sets is useful in competitive programming
and solving algorithmic problems. The insertion and deletion in STL sets are
discussed in this article.
Insertion in STL Set
We can insert elements in an STL set container using two member functions of
std::set:
1. Using insert() function
2. Using emplace() function
The insert() function is used to insert the elements in the set. After insertion, the
reordering of elements takes place and the set is sorted. This function can be
implemented in 3 ways.
Syntax 1:
set_name.insert(element);
This function inserts the element in the set. The insertion only takes place when the
element passed is not already in the set. It returns a pointer pair. The first element
points to the elements already present or newly inserted. The second element returns
the boolean status “true” or “false”.
Syntax 2:
set_name.insert(hint_position, element);
In this implementation, the hint pointer is sent with the element to be inserted. The use
of a hint pointer is to help insert() know where the actual insertion has to take place.
Hence, trying to reduce the time to allocate the element. The hint pointer does not
force the insertion at a specific position. This function returns the pointer to the
position where the element is inserted.
Syntax 3:
set_name.insert(begin_iterator, end_iterator);
This type of insertion is required to insert the elements of other containers into the
set. The repeated elements are not inserted if they are present in the source container.
Example:
C++
// C++ code to demonstrate the working of insert()
#include <iostream>
int main()
// declaring set
set<int> st;
// declaring iterators
set<int>::iterator it = st.begin();
// inserting 20
ptr = st.insert(20);
// inserted
if (ptr.second)
else
cout << "\nThe set elements after 1st insertion are : ";
st.insert(it, 24);
// printing set elements after insertion
cout << "\nThe set elements after 2nd insertion are : ";
cout << "\nThe set elements after 3rd insertion are : ";
Output
The element was newly inserted
The set elements after 1st insertion are : 20
The set elements after 2nd insertion are : 20 24
The set elements after 3rd insertion are : 20 24 25 26
2. Insertion Using emplace() Function
The emplace() is also used to insert the element into the Set. This function is similar
to “insert()” discussed above, the only difference being that the “in-place”
construction of the element takes place at the position of element insertion contrary
to insert() which copies or movies existing objects.
Syntax of emplace():
set_name.emplace(element);
It increases the size of the set by 1 and returns a pointer pair whose first element of
which is an iterator pointing to the position of the inserted element and the second
returns a boolean variable indicating an already present or newly created element.
Syntax of emplace_hint():
set_name.emplace(hint_position, element);
Takes a “hint_iterator” to get a hint of the position of insertion to possibly reduce
the time required to insert the element inserted. This does not affect the position of
insertion. It takes place where it is defined internally.
Example:
C++
// and emplace_hint()
#include <iostream>
int main()
{
// declaring set
set<int> st;
// declaring iterators
set<int>::iterator it = st.begin();
// inserting 24
ptr = st.emplace(24);
if (ptr.second)
cout << "The element was newly inserted";
else
cout << "\nThe set elements after 1st insertion are : ";
ptr = st.emplace(24);
if (ptr.second)
else
cout << "\nThe element was already present";
cout << "\nThe set elements after 2nd insertion are : ";
st.emplace_hint(it, 25);
cout << "\nThe set elements after 3rd insertion are : ";
Output
The element was newly inserted
The set elements after 1st insertion are : 24
The element was already present
The set elements after 2nd insertion are : 24
The set elements after 3rd insertion are : 24 25
Time Complexity of Insertion in Set: O(logN)
Deletion in STL Set
We can delete elements from a set container using erase() function. It is a member
function of std::set class. It can be used in the following ways:
Syntax 1:
set_name.erase(value);
Erases the value mentioned in its argument. reorders the set after deletion.
Syntax 2:
set_name.erase(iterator);
Erases the value at the position pointed by the iterator mentioned in its argument.
Syntax 3:
set_name.erase(begin_iterator, end_iterator);
Erases the range of elements starting from “begin_iterator” to the “end_iterator”.
Example:
C++
#include <iostream>
int main()
// declaring set
set<int> st;
// declaring iterators
set<int>::iterator it;
set<int>::iterator it1;
set<int>::iterator it2;
st.insert(i * 5);
++it;
st.erase(it);
cout << "The set elements after 1st deletion are : ";
st.erase(40);
++it;
++it;
++it;
++it;
// deletes 25 - last(45)
st.erase(it, st.end());
cout << "\nThe set elements after 3rd deletion are : ";
Output
The set elements after insertion are : 5 10 15 20 25 30 35 40 45
The set elements after 1st deletion are : 5 15 20 25 30 35 40 45
The set elements after 2nd deletion are : 5 15 20 25 30 35 45
The set elements after 3rd deletion are : 5 15 20
Prerequisite: Set
A Set is a container implemented in C++ language in STL and has a concept similar
to how the set is defined in mathematics. The fact that separates the set from the other
containers is that it contains only the distinct elements and elements can be traversed
in sorted order. Having the stronghold on sets is useful in competitive programming
and solving algorithmic problems. The insertion and deletion in STL sets are
discussed in this article.
Insertion in STL Set
We can insert elements in an STL set container using two member functions of
std::set:
1. Using insert() function
2. Using emplace() function
The insert() function is used to insert the elements in the set. After insertion, the
reordering of elements takes place and the set is sorted. This function can be
implemented in 3 ways.
Syntax 1:
set_name.insert(element);
This function inserts the element in the set. The insertion only takes place when the
element passed is not already in the set. It returns a pointer pair. The first element
points to the elements already present or newly inserted. The second element returns
the boolean status “true” or “false”.
Syntax 2:
set_name.insert(hint_position, element);
In this implementation, the hint pointer is sent with the element to be inserted. The use
of a hint pointer is to help insert() know where the actual insertion has to take place.
Hence, trying to reduce the time to allocate the element. The hint pointer does not
force the insertion at a specific position. This function returns the pointer to the
position where the element is inserted.
Syntax 3:
set_name.insert(begin_iterator, end_iterator);
This type of insertion is required to insert the elements of other containers into the
set. The repeated elements are not inserted if they are present in the source container.
Example:
C++
#include <iostream>
int main()
// declaring set
set<int> st;
// declaring iterators
set<int>::iterator it = st.begin();
// inserting 20
ptr = st.insert(20);
// inserted
if (ptr.second)
else
cout << "The element was already present";
cout << "\nThe set elements after 1st insertion are : ";
st.insert(it, 24);
cout << "\nThe set elements after 2nd insertion are : ";
cout << "\nThe set elements after 3rd insertion are : ";
Output
The element was newly inserted
The set elements after 1st insertion are : 20
The set elements after 2nd insertion are : 20 24
The set elements after 3rd insertion are : 20 24 25 26
2. Insertion Using emplace() Function
The emplace() is also used to insert the element into the Set. This function is similar
to “insert()” discussed above, the only difference being that the “in-place”
construction of the element takes place at the position of element insertion contrary
to insert() which copies or movies existing objects.
Syntax of emplace():
set_name.emplace(element);
It increases the size of the set by 1 and returns a pointer pair whose first element of
which is an iterator pointing to the position of the inserted element and the second
returns a boolean variable indicating an already present or newly created element.
Syntax of emplace_hint():
set_name.emplace(hint_position, element);
Takes a “hint_iterator” to get a hint of the position of insertion to possibly reduce
the time required to insert the element inserted. This does not affect the position of
insertion. It takes place where it is defined internally.
Example:
C++
// and emplace_hint()
#include <iostream>
int main()
// declaring set
set<int> st;
// declaring iterators
set<int>::iterator it = st.begin();
// inserting 24
ptr = st.emplace(24);
if (ptr.second)
else
cout << "\nThe set elements after 1st insertion are : ";
ptr = st.emplace(24);
if (ptr.second)
else
cout << "\nThe set elements after 2nd insertion are : ";
st.emplace_hint(it, 25);
// printing set elements after insertion
cout << "\nThe set elements after 3rd insertion are : ";
Output
The element was newly inserted
The set elements after 1st insertion are : 24
The element was already present
The set elements after 2nd insertion are : 24
The set elements after 3rd insertion are : 24 25
Time Complexity of Insertion in Set: O(logN)
Deletion in STL Set
We can delete elements from a set container using erase() function. It is a member
function of std::set class. It can be used in the following ways:
Syntax 1:
set_name.erase(value);
Erases the value mentioned in its argument. reorders the set after deletion.
Syntax 2:
set_name.erase(iterator);
Erases the value at the position pointed by the iterator mentioned in its argument.
Syntax 3:
set_name.erase(begin_iterator, end_iterator);
Erases the range of elements starting from “begin_iterator” to the “end_iterator”.
Example:
C++
int main()
// declaring set
set<int> st;
// declaring iterators
set<int>::iterator it;
set<int>::iterator it1;
set<int>::iterator it2;
st.insert(i * 5);
it = st.begin();
++it;
st.erase(it);
// printing set elements after deletion
cout << "The set elements after 1st deletion are : ";
st.erase(40);
cout << "\nThe set elements after 2nd deletion are : ";
++it;
++it;
++it;
++it;
// erasing element using range iterator
// deletes 25 - last(45)
st.erase(it, st.end());
cout << "\nThe set elements after 3rd deletion are : ";
Output
The set elements after insertion are : 5 10 15 20 25 30 35 40 45
The set elements after 1st deletion are : 5 15 20 25 30 35 40 45
The set elements after 2nd deletion are : 5 15 20 25 30 35 45
The set elements after 3rd deletion are : 5 15 20
Given a vector, find the sum of the elements of this vector using STL in C++.
Example:
Input: vec = {1, 45, 54, 71, 76, 12}
Output: 259
CPP
#include <bits/stdc++.h>
int main()
return 0;
Output
Vector: 1 45 54 71 76 12
Sum = 259
Time Complexity: It is linear in the distance between first_index and last_index i.e if
your vector contains n number of elements between two given indices , the time
complexity will be O(n).
Auxiliary Space: O(1)
The for_each() function is an STL algorithm that applies a given function to each
element in a range defined by a pair of iterators.
To find the sum of all elements in a vector using the for_each() function, we can
define a lambda function or a function object that adds each element to a running
total.
Syntax:
for_each(InputIt first, InputIt last, UnaryFunction f);
C++
#include <bits/stdc++.h>
int main()
int sum = 0;
sum += i;
});
return 0;
Output
Vector: 1 45 54 71 76 12
Sum = 259
Time Complexity: O(N), , where N is the number of elements in the range.
Auxiliary Space: O(1)
Different methods to copy in C++ STL |
std::copy(), copy_n(), copy_if(),
copy_backward()
Last Updated : 15 Sep, 2023
Various varieties of copy() exist in C++ STL that allows to perform the copy
operations in different manners, all of them having their own use. These all are
defined in header <algorithm>. This article introduces everyone to these functions for
usage in day-to-day programming.
1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy function used
to copy a range of elements from one container to another. It takes 3 arguments:
strt_iter1 : The pointer to the beginning of the source container, from where
elements have to be started copying.
end_iter1 : The pointer to the end of source container, till where elements have to
be copied.
strt_iter2 : The pointer to the beginning of destination container, to where
elements have to be started copying.
2. copy_n(strt_iter1, num, strt_iter2) : This version of copy gives the freedom to
choose how many elements have to be copied in the destination container. IT also
takes 3 arguments:
strt_iter1 : The pointer to the beginning of the source container, from where
elements have to be started copying.
num : Integer specifying how many numbers would be copied to destination
container starting from strt_iter1. If a negative number is entered, no operation is
performed.
strt_iter2 : The pointer to the beginning of destination container, to where
elements have to be started copying.
CPP
// and copy_n()
#include<iostream>
#include<vector>
using namespace std;
int main()
vector<int> v1 = { 1, 5, 7, 3, 8, 3 };
vector<int> v2(6);
vector<int> v3(6);
cout << "The new vector elements entered using copy() : ";
copy_n(v1.begin(), 4, v3.begin());
cout << "The new vector elements entered using copy_n() : ";
Output:
The new vector elements entered using copy() : 1 5 7 0 0 0
The new vector elements entered using copy_n() : 1 5 7 3 0 0
3. copy_if(): As the name suggests, this function copies according to the result of a
“condition“.This is provided with the help of a 4th argument, a function returning
a boolean value.
This function takes 4 arguments, 3 of them similar to copy() and an additional
function, which when returns true, a number is copied, else number is not copied.
4. copy_backward(): This function starts copying elements into the destination
container from backward and keeps on copying till all numbers are not copied. The
copying starts from the “strt_iter2” but in the backward direction. It also takes similar
arguments as copy().
CPP
// and copy_backward()
#include<iostream>
#include<vector>
int main()
vector<int> v1 = { 1, 5, 6, 3, 8, 3 };
vector<int> v2(6);
vector<int> v3(6);
cout << "The new vector elements entered using copy_if() : ";
cout << "The new vector elements entered using copy_backward() : ";
for(int i=0; i<v3.size(); i++)
Output:
The new vector elements entered using copy_if() : 1 5 3 3 0 0
The new vector elements entered using copy_backward() : 0 1 5 6 3 0
5. Copy using inserter():
Before copy() operation let us understand the syntax of inserter().
inserter() is used as a destination that where we want to copy the elements of the
container.
inserter() takes two parameters. The first is a container of arbitrary type and the
second is an iterator into the container.
It returns an instance of insert_iterator working on a container of arbitrary type. This
wrapper function helps in creating insert_iterator instances. Typing the name of the
%iterator requires knowing the precise full type of the container, which can be tedious
and impedes generic programming. Using this function lets you take advantage of
automatic template parameter deduction, making the compiler match the correct types
for you.
The syntax for inserter():
std::inserter(Container& x, typename Container::iterator it);
C++
#include <iostream>
#include <algorithm>
#include <vector>
int main()
vector<int>::iterator itr;
vector<int> v2;
//using inserter()
Output:
The new vector elements entered using inserter: 1 5 7 3 8 3
1. finding an element
2. lower_bound
3. upper_bound
1. binary_search:
binary_search(start_ptr, end_ptr, num): This function returns true if the element is
present in the container, else returns false. The start_ptr variable holds the starting
point of the binary search and end_ptr holds the ending position of binary search
space and num is the value to be found.
CPP
#include <bits/stdc++.h>
// Driver's code
int main()
else
else
Output
15 exists in vector
23 does not exist
Time Complexity: O(log N) – where N is the number of elements in the array.
Auxiliary Space: O(1)
2. lower_bound:
lower_bound(start_ptr, end_ptr, num):Returns pointer to the position of num if the
container contains only one occurrence of num. Returns a pointer to the first position
of num if the container contains multiple occurrences of num. Returns pointer to the
position of a number just higher than num, if the container does not contain an
occurrence of num which is the position of the number when inserted in the already
sorted array and sorted again. Subtracting the first position i.e vect.begin() from the
pointer, returns the actual index. The start_ptr variable holds the starting point of the
binary search and end_ptr holds the ending position of binary search space
and num is the value to be found.
CPP
#include <bits/stdc++.h>
// Driver's code
int main()
// for no occurrence
// single occurrence
// prints 2
- arr1.begin();
// multiple occurrence
// prints 2
- arr2.begin();
// no occurrence
- arr3.begin();
cout << endl;
Output
The position of 20 using lower_bound (in single occurrence case) : 2
The position of 20 using lower_bound (in multiple occurrence case) : 2
The position of 20 using lower_bound (in no occurrence case) : 2
Time Complexity: O(log N) – where N is the number of elements in the array.
Auxiliary Space: O(1)
3. upper_bound:
upper_bound(start_ptr, end_ptr, num): Returns pointer to the position of next
higher number than num if the container contains one occurrence of num. Returns
pointer to the first position of the next higher number than the last occurrence of num
if the container contains multiple occurrences of num. Returns pointer to position of
next higher number than num if the container does not contain an occurrence of
num. Subtracting the first position i.e vect.begin() from the pointer, returns the actual
index. The start_ptr variable holds the starting point of the binary search
and end_ptr holds the ending position of binary search space and num is the value to
be found.
CPP
#include <bits/stdc++.h>
int main()
// for no occurrence
// single occurrence
// prints 3
cout << "The position of 20 using upper_bound"
- arr1.begin();
// multiple occurrence
// prints 4
- arr2.begin();
- arr3.begin();
Output
The position of 20 using upper_bound (in single occurrence case) : 3
The position of 20 using upper_bound (in multiple occurrence case) : 4
The position of 20 using upper_bound (in no occurrence case) : 2
Time Complexity: O(log N) – where N is the number of elements in the array.
Auxiliary Space: O(1)
Quickly check if two STL vectors contain
same elements or not
Last Updated : 16 Jul, 2021
C++14
#include<bits/stdc++.h>
int main()
vector<int> v4;
vector<int> v5;
return 0;
Output:
Equal
Not Equal
Not Equal
Equal
Prerequisite : Find day of the week for given date
Problem: To print the calendar of any given year. The program should be such that it
can prints the calendar of any input year.
Implementation:
CPP
// of an year
#include<bits/stdc++.h>
For e.g-
Index Day
0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday*/
4, 6, 2, 4 };
/*
0 January
1 February
2 March
3 April
4 May
5 June
6 July
7 August
8 September
9 October
10 November
11 December */
};
return (months[monthNumber]);
a month
0 January 31
2 March 31
3 April 30
4 May 31
5 June 30
6 July 31
7 August 31
8 September 30
9 October 31
10 November 30
11 December 31
*/
// January
if (monthNumber == 0)
return (31);
// February
if (monthNumber == 1)
// 29 days
if (year % 400 == 0 ||
return (29);
else
return (28);
// March
if (monthNumber == 2)
return (31);
// April
if (monthNumber == 3)
return (30);
// May
if (monthNumber == 4)
return (31);
// June
if (monthNumber == 5)
return (30);
// July
if (monthNumber == 6)
return (31);
// August
if (monthNumber == 7)
return (31);
// September
if (monthNumber == 8)
return (30);
// October
if (monthNumber == 9)
return (31);
// November
if (monthNumber == 10)
return (30);
// December
if (monthNumber == 11)
return (31);
int days;
// month - i
printf("\n ------------%s-------------\n",
getMonthName (i).c_str());
int k;
printf(" ");
for (int j = 1; j <= days; j++)
printf("%5d", j);
if (++k > 6)
k = 0;
printf("\n");
if (k)
printf("\n");
current = k;
}
return;
int main()
printCalendar(year);
return (0);
Output:
Calendar - 2016
------------January-------------
Sun Mon Tue Wed Thu Fri Sat
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
------------February-------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29
------------March-------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
------------April-------------
Sun Mon Tue Wed Thu Fri Sat
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
------------May-------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
------------June-------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
------------July-------------
Sun Mon Tue Wed Thu Fri Sat
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
------------August-------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
------------September-------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
------------October-------------
Sun Mon Tue Wed Thu Fri Sat
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
------------November-------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
------------December-------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Time Complexity– O(1) . The time taken doesn’t depends on the input year. It is
same for any given year.
Auxiliary Space – O(1)
C++ Program to Print Current Day, Date and
Time
Last Updated : 05 Mar, 2023
In order to facilitate finding the current local day, date, and time, C++ has defined
several functions in the header file, so functions that will help us in achieving our
objective of finding the local day, date, and time are: time():
It is used to find the current calendar time.
Its return type is time_t, which is an arithmetic data type capable of storing time
returned by this function.
If its argument is not NULL, then it assigns its argument the same value as its
return value.
Also, Calendar dates are displayed on the screen together with the day, date, and time
that are current. All the date and time-related functions and variables in C++ are found
in the ctime library.
localtime()
It uses the argument of time(), which has the same value as the return value of
time(), to fill a structure having date and time as its components, with
corresponding time in the local timezone.
asctime()
It is used to convert the contents in the structure filled by local time into a human-
readable version which finally returns the day, date, and time in the given format:
Day Month Date hh:mm:ss Year
Example:
C++
#include <iostream>
int main()
time_t tt;
// localtime()
// Applying time()
time(&tt);
// Using localtime()
ti = localtime(&tt);
cout << "Current Day, Date and Time is = "
<< asctime(ti);
return 0;
Output
Current Day, Date and Time is = Thu Dec 29 06:35:15 2022
gmtime() Function in C
Last Updated : 06 Oct, 2023
The gmtime() function in C takes a pointer to type t_time value which represents type
in seconds and converts it to struct tm. In this article, we will learn gmtime()
Function in the C programming language.
The struct tm type can hold the individual components of time in UTC(Universal
Time Coordinated) or GMT time (i.e., the time in the GMT timezone) time zones. The
C gmtime() function is defined in <ctime> header file.
Syntax of gmtime()
tm* gmtime ( const time_t* current_time )
The hours can be accessed using tm_hour
The minutes can be accessed using tm_min
The seconds can be accessed using tm_sec
Parameters
#include <stdio.h>
#include <time.h>
int main()
// object
time_t current_time;
// pointer
time(¤t_time);
ptime = gmtime(¤t_time);
printf("Current time:\n");
ptime->tm_sec);
ptime->tm_sec);
return 0;
}
Output
Current time:
Beijing ( China ):20:00:04
Delhi ( India ): 7:00:04
Example 2
C
// gmtime() function
#include <stdio.h>
#include <time.h>
int main()
// object
time_t current_time;
// pointer
time(¤t_time);
ptime = gmtime(¤t_time);
printf("Current time:\n");
return 0;
Output
Current time:
Monrovia ( Liberia ) :11:45:36
Buenos Aires ( Argentina ) : 8:45:36
Here, we will see how to find the quotient and remainder using a C++ program.
The quotient is the result of dividing a number (dividend) by another number
(divisor). The remainder is the value left after division when the dividend is not
completely divisible by the divisor. For example,
The Modulo Operator will be used to calculate the Remainder and Division Operator
will be used to calculate the Quotient.
Quotient = Dividend / Divisor;
Remainder = Dividend % Divisor;
C++ Program to Find Quotient and Remainder
C++
// and remainder
#include <bits/stdc++.h>
// Driver code
int main()
return 0;
Output
Enter Dividend & Divisor: The Quotient = 0
The Remainder = 32767
In this article, we will learn to write a C++ program to find the size of int, float,
double, and char. It is important to know the size of different data types especially
when working with large datasets to optimize memory usage.
The size of a variable can be determined using sizeof() operator in C++. The syntax
of size of operator is:
sizeof(dataType);
To find the size of the four datatypes:
1. The four types of variables are defined as integerType, floatType, doubleType, and
charType.
2. The size of the variables is calculated using the sizeof() operator.
C++ Program to Find the Size of a Data Types
C++
#include <iostream>
int main()
{
int integerType;
char charType;
float floatType;
double doubleType;
<< "\n";
cout << "Size of char is: " << sizeof(charType) << "\n";
<< "\n";
// Calculate and Print
<< "\n";
return 0;
Output
Size of int is: 4
Size of char is: 1
Size of float is: 4
Size of double is: 8
Complexity Analysis
-2,147,483,648 to
int 4 %d
2,147,483,647
-2,147,483,648 to
long int 4 %ld
2,147,483,647
2.22507e-308 to
double 8 %lf
1.79769e+308
C++
#include <bits/stdc++.h>
using namespace std;
if (name.length() == 0)
return;
// we do typecasting
}
// Driver code
int main()
printInitials(name);
return 0;
Output:
K J
Time Complexity: O(n), Here n is the length of the string.
Auxiliary Space: O(1), As constant extra space is used.
Another possible solution is given as follows:
C++
// above approach
#include <bits/stdc++.h>
{
if (name.length() == 0)
return;
// every word
// X is an object of stringstream
stringstream X(name);
whitespace is found. */
// Driver code
int main()
printInitials(name);
return 0;
Output:
K J
#include <bits/stdc++.h>
// and b >= 0
if (b == 0)
return 1;
int answer = a;
int increment = a;
int i, j;
answer += increment;
increment = answer;
return answer;
// Driver Code
int main()
return 0;
}
// This code is contributed by rathbhupendra
Output :
125
Time Complexity: O(a * b)
Auxiliary Space: O(1)
Method 2 (Using Recursion)
Recursively add a to get the multiplication of two numbers. And recursively multiply
to get a raise to the power b.
C++
#include<bits/stdc++.h>
// A recursive function
// to get x*y
if(y)
return (x + multiply(x,
y - 1));
else
return 0;
if(b)
return multiply(a,
pow(a, b - 1));
else
return 1;
// Driver Code
int main()
getchar();
return 0;
Output :
125
Time Complexity: O(b)
Auxiliary Space: O(b)
Method 3 (Using bit masking)
we can a^n (let’s say 3^5) as 3^4 * 3^0 * 3^1 = 3^, so we can represent 5 as its binary
i.e. 101
C++
#include <iostream>
int ans = 1;
while(n > 0)
// bit of n
// ans and a
if(last_bit)
ans = ans*a;
}
// Make a equal to square of a as on
a = a * a;
n = n >> 1;
return ans;
// Driver code
int main()
return 0;
Examples:
Input : a = 1, b = -2, c = 1
Output: Roots are real and same
1
Input : a = 1, b = 7, c = 12
Output: Roots are real and different
-3, -4
Input : a = 1, b = 1, c = 1
Output: Roots are complex
-0.5 + i1.73205
-0.5 – i1.73205
Recommended: Please solve it on “PRACTICE” first, before moving on to the
solution.
Below is the direct formula for finding the roots of the quadratic equation.
int d = b * b - 4 * a * c;
double sqrt_val = sqrt(abs(d));
if (d > 0) {
cout << "Roots are real and different ";
cout << (double)(-b + sqrt_val) / (2 * a) << " "
<< (double)(-b - sqrt_val) / (2 * a);
}
else if (d == 0) {
cout << "Roots are real and same ";
cout << -(double)b / (2 * a);
}
// d < 0
else {
cout << "Roots are complex ";
cout << -(double)b / (2 * a) << " + i"
<< sqrt_val / (2 * a) << " "
<< -(double)b / (2 * a) << " - i"
<< sqrt_val / (2 * a);
}
}
// Driver code
int main()
{
int a = 1, b = -7, c = 12;
// Function call
findRoots(a, b, c);
return 0;
}
Output
Roots are real and different 4 3
Generate Random Double Numbers in C++
Last Updated : 16 Feb, 2023
Double is a data type just like a float but double has 2x more precision than float. One
bit for the sign, 11 bits for the exponent and 52* bits for the value constitute the 64-bit
IEEE 754 double precision Floating Point Number known as “double.” Double has 15
decimal digits of precision.
In this article, we generate random double numbers in C++.
The random double number can be generated using a few methods which are
mentioned below:
1. Using random() function
2. Using uniform_real_distribution and default_random_engine.
Using the random function is the method where we get random integers and by using
them we create a random double number by performing certain operations in it. You
can set lower and upper bounds in it.
random(): It generate a random integer.
Example:
C++
#include <iostream>
#include <time.h>
// Driver Code
int main()
double lower_bound = 0;
srandom(time(NULL));
+ (upper_bound - lower_bound)
* (random() % max_rand)
/ max_rand;
return 0;
Output
35.9952
When we want to find random numbers after defining the upper and lower bound then
we can use this method.
uniform_real_distribution: The random library now includes the uniform real
distribution class, whose member functions generate random real numbers or
continuous values with uniform probability from a specified input range.
default_random_engine: This class of pseudo-random number generators produces
random numbers.
min(): It gives back the lowest value specified by the operator ().
max(): It gives back the highest value specified by the operator ().
operator(): A fresh random number is given back.
Example:
C++
// uniform_real_distribution and
// default_random_engine
#include <iostream>
#include <random>
// Driver Code
int main()
// bounds
double lower_bound = 0;
uniform_real_distribution<double> unif(lower_bound,
upper_bound);
default_random_engine re;
// Getting a random double value
return 0;
Output
13.1538
The task is to hide and Show the console window of a C++ program. The program for
the same is given below.
Note: The results of the following program can only be seen when it is executed on a
console.
Example:
C++
#include <windows.h>
void countdown()
Sleep(1000);
Sleep(1000);
Sleep(1000);
int main()
{
countdown();
HWND window;
AllocConsole();
ShowWindow(window, 0);
countdown();
ShowWindow(window, 1);
Output:
Explanation: The above program counts from 3 to 1 before the Console Window
disappears. After the window has disappeared, the ShowWindow helps the program
so that the Console Window reappears again after counting from 3 to 1(executing the
countdown function).
The execution of the program can be understood by understanding the key functions
of the program.
#include<windows.h> – The windows.h header in C++ programming languages
are specifically designed for windows and contain a very large number of windows
specific functions.
AllocConsole()- AllocConsole initializes standard input, standard output, and
standard error handles for the new console.
ShowWindow()- Sets the specified window’s show state.
FindWindowA()– Takes string parameters and checks whose class name and
window name match the specified strings
How to Run a C++ Program Without
Namespace?
Last Updated : 02 Nov, 2022
#include <iostream>
#include <string>
int main()
return 0;
Output
geeksforgeeks
Maps are associative containers that store elements in a mapped fashion. Each
element has a key value and a mapped value. No two mapped values can have the
same key values. Maps are implemented by self-balancing search trees. In C++ STL it
uses Red-Black Tree.
Here we are going to implement a custom Map class which has an integer value as
the key and the value stored corresponding to any key is also of integer type.
We will implement it using the AVL tree. To implement the map, we will first create
a header file which will incorporate the functionalities of a map class. Below is the
basic structure of the Map class:
Structure of Map class:
The structure of the AVL tree depends upon the structure of the node:
Each node has pointers for the left child, the right child, and the parent.
Each node has three values first (which is the key), second (which is the value to
the corresponding key) and depth (height of the subtree for the node).
The map class also has a static value cnt which stores the number of elements
present in the map and a static node root, which is the root of the tree.
Store this in a header file (say map.h)
C++
class Map {
};
C++
insert(first)->second = second;
else
temp->second = second;
C++
cnt++;
Map* newnode = create(first);
if (root == nullptr) {
root = newnode;
return root;
prev = temp;
temp = temp->left;
temp = temp->right;
else {
free(newnode);
cnt--;
// updatable
return temp;
prev->left = newnode;
else
prev->right = newnode;
newnode->par = prev;
return newnode;
return insert(key)->second;
C++
temp = temp->left;
else {
temp = temp->right;
return temp;
return iterator(first);
C++
if (temp != nullptr) {
temp->second = second;
C++
const Map* iterator(int first) const
temp = temp->left;
else
temp = temp->right;
return temp;
if (temp != nullptr)
return temp->second;
return 0;
return search(key);
C++
Map* prev = 0;
cnt--;
prev = temp;
temp = temp->left;
temp = temp->right;
if (temp == nullptr) {
cnt++;
return;
}
free(temp);
root = nullptr;
return;
Map* l = inorderPredecessor(temp->left);
Map* r = inorderSuccessor(temp->right);
if (l == 0 && r == 0) {
if (prev == 0) {
root = 0;
else {
if (prev->left == temp) {
prev->left = 0;
else {
prev->right = 0;
}
free(temp);
balance(prev);
return;
Map* start;
if (l != 0) {
if (l == temp->left) {
l->right = temp->right;
if (l->right != 0) {
l->right->par = l;
start = l;
else {
if (l->left != 0) {
l->left->par = l->par;
}
start = l->par;
l->par->right = l->left;
l->right = temp->right;
l->par = 0;
if (l->right != 0) {
l->right->par = l;
l->left = temp->left;
temp->left->par = l;
if (prev == 0) {
root = l;
else {
if (prev->left == temp) {
prev->left = l;
l->par = prev;
}
else {
prev->right = l;
l->par = prev;
free(temp);
balance(start);
return;
else {
if (r == temp->right) {
r->left = temp->left;
if (r->left != 0) {
r->left->par = r;
start = r;
else {
if (r->right != 0) {
r->right->par = r->par;
start = r->par;
r->par->left = r->right;
r->left = temp->left;
r->par = 0;
if (r->left != 0) {
r->left->par = r;
r->right = temp->right;
temp->right->par = r;
if (prev == 0) {
root = r;
else {
if (prev->right == temp) {
prev->right = r;
r->par = prev;
}
else {
prev->left = r;
r->par = prev;
free(temp);
balance(start);
return;
C++
// If key is found
if (temp != nullptr)
return 1;
return 0;
C++
int size(void) {
return cnt;
C++
bool empty(void)
if (root == 0)
return true;
return false;
C++
void clear(void)
erase(root->first);
C++
if (root == 0)
return;
if (head->left != 0) {
iterate(head->left);
if (head->right != 0) {
iterate(head->right);
// map.h
#include <iostream>
class Map {
private:
// so that we do not
temp = temp->left;
// Go to right otherwise
else {
temp = temp->right;
return temp;
}
// Returns the pointer to element
temp = temp->left;
else {
temp = temp->right;
return temp;
}
// The const property is used to keep the
// int&[]operator(int) const"
if (temp != nullptr) {
return temp->second;
return 0;
}
// Utility function to return the Map* object
newnode->first = first;
newnode->second = 0;
newnode->left = nullptr;
newnode->right = nullptr;
newnode->par = nullptr;
newnode->depth = 1;
return newnode;
void right_rotation(Map* x)
Map* y = x->left;
x->left = y->right;
if (y->right != nullptr) {
y->right->par = x;
x->par->right = y;
y->par = x->par;
y->right = x;
x->par = y;
void left_rotation(Map* x)
Map* y = x->right;
x->right = y->left;
if (y->left != nullptr) {
y->left->par = x;
x->par->left = y;
}
x->par->right = y;
y->par = x->par;
y->left = x;
x->par = y;
// If left skewed
if (depthf(node->left)
- depthf(node->right) > 1) {
// If "depth" of left subtree of
if (depthf(node->left->left)
> depthf(node->left->right)) {
node->depth
= max(depthf(node->right) + 1,
depthf(node->left->right) + 1);
node->left->depth
= max(depthf(node->left->left) + 1,
depthf(node) + 1);
right_rotation(node);
// greater than
// left subtree of left child
else {
node->left->depth = max(
depthf(node->left->left) + 1,
depthf(node->left->right->left)
+ 1);
node->depth
= max(depthf(node->right) + 1,
depthf(node->left->right->right) + 1);
node->left->right->depth
= max(depthf(node) + 1,
depthf(node->left) + 1);
left_rotation(node->left);
right_rotation(node);
// If right skewed
else if (depthf(node->left)
if (depthf(node->right->right)
> depthf(node->right->left)) {
node->depth
= max(depthf(node->left) + 1,
depthf(node->right->left) + 1);
node->right->depth
= max(depthf(node->right->right) + 1,
depthf(node) + 1);
left_rotation(node);
else {
node->right->depth = max(
depthf(node->right->right) + 1,
depthf(node->right->left->right) + 1);
node->depth = max(
depthf(node->left) + 1,
depthf(node->right->left->left) + 1);
node->right->left->depth
= max(depthf(node) + 1,
depthf(node->right) + 1);
right_rotation(node->right);
left_rotation(node);
}
// Balancing the tree about the "node"
int d = node->depth;
node = node->par;
if (node->depth < d + 1) {
node->depth = d + 1;
if (node == root
&& depthf(node->left)
- depthf(node->right) > 1) {
if (depthf(node->left->left)
> depthf(node->left->right)) {
root = node->left;
else {
root = node->left->right;
helper(node);
break;
&& depthf(node->left)
- depthf(node->right)
< -1) {
if (depthf(node->right->right)
> depthf(node->right->left)) {
root = node->right;
else {
root = node->right->left;
helper(node);
break;
}
helper(node);
if (node == nullptr)
// If it is null node
return 0;
return node->depth;
{
cnt++;
if (root == nullptr) {
root = newnode;
return root;
prev = temp;
temp = temp->left;
temp = temp->right;
else {
free(newnode);
cnt--;
return temp;
}
prev->left = newnode;
else {
prev->right = newnode;
newnode->par = prev;
balance(newnode);
return newnode;
if (head == nullptr)
return head;
head = head->right;
return head;
if (head == nullptr)
return head;
head = head->left;
return head;
}
public:
return insert(key)->second;
}
// methods/functions cannot be
// member variables
return search(key);
if (temp != nullptr) {
return 1;
return 0;
}
// Returns number of elements in the map
int size(void) {
return cnt;
cnt--;
temp->first != first) {
prev = temp;
temp = temp->left;
if (temp == nullptr) {
cnt++;
return;
free(temp);
root = nullptr;
return;
Map* l
= inorderPredecessor(temp->left);
Map* r
= inorderSuccessor(temp->right);
if (prev == nullptr) {
root = nullptr;
}
else {
if (prev->left == temp) {
prev->left = nullptr;
else {
prev->right = nullptr;
free(temp);
balance(prev);
return;
Map* start;
if (l != nullptr) {
if (l == temp->left) {
l->right = temp->right;
if (l->right != nullptr) {
l->right->par = l;
}
start = l;
else {
if (l->left != nullptr) {
l->left->par = l->par;
start = l->par;
l->par->right = l->left;
l->right = temp->right;
l->par = nullptr;
if (l->right != nullptr) {
l->right->par = l;
l->left = temp->left;
temp->left->par = l;
if (prev == nullptr) {
root = l;
}
else {
if (prev->left == temp) {
prev->left = l;
l->par = prev;
else {
prev->right = l;
l->par = prev;
free(temp);
balance(start);
return;
else {
if (r == temp->right) {
r->left = temp->left;
if (r->left != nullptr) {
r->left->par = r;
start = r;
else {
if (r->right != nullptr) {
r->right->par = r->par;
start = r->par;
r->par->left = r->right;
r->left = temp->left;
r->par = nullptr;
if (r->left != nullptr) {
r->left->par = r;
r->right = temp->right;
temp->right->par = r;
if (prev == nullptr) {
root = r;
else {
if (prev->right == temp) {
prev->right = r;
r->par = prev;
else {
prev->left = r;
r->par = prev;
free(temp);
balance(start);
return;
}
// Returns if the map is empty or not
bool empty(void)
if (root == nullptr)
return true;
return false;
if (temp != nullptr) {
temp->second = second;
}
// Deleting the root of
// is not empty
void clear(void)
erase(root->first);
if (root == nullptr)
return;
if (head->left != nullptr) {
iterate(head->left);
}
cout << head->first << ' ';
if (head->right != nullptr) {
iterate(head->right);
return iterator(first);
if (temp == nullptr) {
insert(first)->second = second;
else {
temp->second = second;
};
int Map::cnt = 0;
Now save it as a header file say map.h to include it in other codes and implement the
functionalities.
How to Execute the built Custom Map
Mentioned below is the procedure to be followed for implementing the map:
First create a header file for map (map.h)
Then store the header in the same folder in which the files implementing the map
are stored.
Include the map header in the files which will implement the map class.
Compile and run the files implementing map.
Examples to show the use of Custom Map
The following programmes demonstrate the execution for the Map class by creating
its functionalities.
Example 1: Programs to demonstrate the use of insert(), accessing any key and
update() methods:
C++
#include "map.h"
#include <iostream>
int main()
Map map;
map[132] = 3;
map[34] = 5;
map[42] = -97;
map[22] = 10;
map[12] = 42;
map.insert(-2,44);
map.insert(0,90);
// accessing elements
<<map[42]<<endl;
<<map[-2]<<endl;
<<map[12]<<endl;
map[42] = -32;
map.insert(-2,8);
map.update(12,444);
// accessing elements
<<map[42]<<endl;
<<map[-2]<<endl;
<<map[12]<<endl;
return 0;
Output:
#include <iostream>
int main()
Map map;
map[132] = 3;
map[34] = 5;
map[42] = -97;
map[22] = 10;
map[12] = 42;
map.iterate();
map.erase(22);
map.clear();
map.iterate();
return 0;
Output:
#include "map.h"
#include <iostream>
int main()
Map map;
map[132] = 3;
map[34] = 5;
map[42] = -97;
<<map[132]<<endl;
it->second = 98;
cout<<"Value at 132 after updating = "
<<map[132]<<endl;
// in the map is 0
cout<<"Count of 77 = "<<map.count(77)<<endl;
// in the map is 1
cout<<"Count of 34 = "<<map.count(34)<<endl;
map.clear();
return 0;
Output:
Given N numbers with no duplicates, count the number of unique triplets (ai, aj,
ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in
the triplet are unique.
Examples:
Input : a[] = {1, 3, 5, 10, 14, 15};
Output : 2
Explanation : {1, 14, 15} and {5, 10, 15} are the
unique triplets whose XOR is 0.
{1, 14, 15} and all other combinations of
1, 14, 15 are considered as 1 only.
C++
#include <bits/stdc++.h>
unordered_set<int> s;
s.insert(a[i]);
int count = 0;
xr != a[j])
count++;
// returns answer
return count / 3;
return 0;
Output:
2
Time Complexity: O(n2)
Auxiliary Space: O(n) for unordered_set
Python programming/examples
Python Program to Print Hello
world!
To understand this example, you should have the knowledge of the
following Python programming topics:
How to Get Started With Python?
Python Basic Input and Output
Source Code
# This program prints Hello, world!
print('Hello, world!')
Run Code
Output
Hello, world!
In this program, we have used the built-in print() function to print the
string Hello, world! on our screen.
By the way, a string is a sequence of characters. In Python, strings are
enclosed inside single quotes, double quotes, or triple quotes.
Python Program to Add Two
Numbers
To understand this example, you should have the knowledge of the
following Python programming topics:
Python Basic Input and Output
Python Data Types
Python Operators
In the program below, we've used the + operator to add two numbers.
Example 1: Add Two Numbers
# This program adds two numbers
num1 = 1.5
num2 = 6.3
Output
The program below calculates the sum of two numbers entered by the user.
Example 2: Add Two Numbers With User Input
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
Output
In this program, we asked the user to enter two numbers and this program
displays the sum of two numbers entered by user.
We use the built-in function input() to take the input. Since, input() returns
a string, we convert the string into number using the float() function. Then, the
numbers are added.
Alternative to this, we can perform this addition in a single statement without
using any variables as follows.
Output
Output
In this program, we store the number in num and find the square root using
the ** exponent operator. This program works for all positive real numbers.
But for negative or complex numbers, it can be done as follows.
Source code: For real or complex numbers
# Find square root of real or complex numbers
# Importing the complex math module
import cmath
num = 1+2j
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}
+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
Run Code
Output
In this program, we use the sqrt() function in the cmath (complex math)
module.
Note: If we want to take complex number as input directly, like 3+4j , we have
to use the eval() function instead of float().
The eval() method can be used to convert complex numbers as input to
the complex objects in Python. To learn more, visit Python eval() function.
s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
Source Code
# Python Program to find the area of triangle
a = 5
b = 6
c = 7
Output
In this program, area of the triangle is calculated when three sides are given
using Heron's formula.
If you need to calculate area of a triangle depending upon the input from the
user, input() function can be used.
Also Read:
Python float()
Python String Interpolation
ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0
(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)
Source Code
# Solve the quadratic equation ax**2 + bx + c = 0
a = 1
b = 5
c = 6
Output
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)
Source Code
# Program to generate a random number between 0 and 9
print(random.randint(0,9))
Run Code
Output
Note that we may get different output because this program generates
random number in range 0 and 9. The syntax of this function is:
random.randint(a,b)
This returns a number N in the inclusive range [a,b] , meaning a <= N <= b ,
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
Run Code
Output
Your turn: Modify the above program to convert miles to kilometers using the
following formula and run it.
Source Code
# Python Program to convert temperature in celsius to fahrenheit
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %
(celsius,fahrenheit))
Run Code
Output
37.5 degree Celsius is equal to 99.5 degree Fahrenheit
Here, we have used the if...elif...else statement. We can do the same thing
using nested if statements as follows.
Source Code: Using Nested if
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Run Code
Output 1
Enter a number: 2
Positive number
Output 2
Enter a number: 0
Zero
Output 1
Enter a number: 43
43 is Odd
Output 2
Enter a number: 18
18 is Even
In this program, we ask the user for the input and check if the number is odd
or even. Please note that { } is a replacement field for num .
Python Program to Check Leap
Year
To understand this example, you should have the knowledge of the
following Python programming topics:
Python Operators
Python if...else Statement
A leap year is exactly divisible by 4 except for century years (years ending
with 00). The century year is a leap year only if it is perfectly divisible by 400.
For example,
Source Code
# Python program to check if year is a leap year or not
year = 2000
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))
Run Code
Output
You can change the value of year in the source code and run it again to test
this program.
Output
Note: To test the program, change the values of num1 , num2 and num3 .
Python Program to Check Prime
Number
To understand this example, you should have the knowledge of the
following Python programming topics:
Python if...else Statement
Python for Loop
Python break and continue
A positive integer greater than 1 which has no other factors except 1 and the
number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as
they do not have any other factors. But 6 is not prime (it is composite) since, 2
x 3 = 6.
num = 29
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
Output
29 is a prime number
In this program, we have checked if num is prime or not. Numbers less than or
equal to 1 are not prime numbers. Hence, we only proceed if the num is greater
than 1.
We check if num is exactly divisible by any number from 2 to num - 1 . If we find
a factor in that range, the number is not prime, so we set flag to True and
break out of the loop.
Outside the loop, we check if flag is True or False .
if num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
A positive integer greater than 1 which has no other factors except 1 and the
number itself is called a prime number.
2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6
is not prime (it is composite) since, 2 x 3 = 6.
Source Code
# Python program to display all the prime numbers within an interval
lower = 900
upper = 1000
Output
Here, we store the interval as lower for lower interval and upper for upper
interval using Python range(), and printed prime numbers in that range. Visit
this page to learn how to check whether a number is prime or not.
Python Program to Find the
Factorial of a Number
To understand this example, you should have the knowledge of the
following Python programming topics:
Python if...else Statement
Python for Loop
Python Recursion
The factorial of a number is the product of all the integers from 1 to that
number.
For example, the factorial of 6 is 1*2*3*4*5*6 = 720 . Factorial is not defined for
negative numbers, and the factorial of zero is one, 0! = 1 .
factorial = 1
Output
Note: To test the program for a different number, change the value of num .
Here, the number whose factorial is to be found is stored in num , and we check
if the number is negative, zero or positive using if...elif...else statement. If
the number is positive, we use for loop and range() function to calculate the
factorial.
iteration factorial*i (returned value)
i=1 1*1=1
i=2 1*2=2
i=3 2*3=6
i=4 6 * 4 = 24
i=5 24 * 5 = 120
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
# recursive call to the function
return (x * factorial(x-1))
In the above example, factorial() is a recursive function that calls itself. Here,
the function will recursively call itself by decreasing the value of the x .
Python Program to Display the
multiplication Table
To understand this example, you should have the knowledge of the
following Python programming topics:
Python for Loop
Python Basic Input and Output
In the program below, we have used the for loop to display the multiplication
table of 12.
Source Code
# Multiplication table (from 1 to 10) in Python
num = 12
Output
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
Here, we have used the for loop along with the range() function to iterate 10
times. The arguments inside the range() function are (1, 11). Meaning, greater
than or equal to 1 and less than 11.
We have displayed the multiplication table of variable num (which is 12 in our
case). You can change the value of num in the above program to test for other
values.
The first two terms are 0 and 1. All other terms are obtained by adding the
preceding two terms. This means to say the nth term is the sum of (n-1)th and
(n-2)th term.
Source Code
# Program to display the Fibonacci sequence up to n-th term
Output
abcd... = an + bn + cn + dn + ...
# initialize sum
sum = 0
Output 1
Output 2
Here, we ask the user for a number and check if it is an Armstrong number.
We need to calculate the sum of the cube of each digit. So, we initialize the
sum to 0 and obtain each digit number by using the modulus operator %. The
remainder of a number when it is divided by 10 is the last digit of that number.
We take the cubes using exponent operator.
Finally, we compare the sum with the original number and conclude that it is
Armstrong number if they are equal.
# initialize sum
sum = 0
You can change the value of num in the source code and run again to test it.
Python Program to Find Armstrong
Number in an Interval
To understand this example, you should have the knowledge of the
following Python programming topics:
Python if...else Statement
Python while Loop
Source Code
# Sum of natural numbers up to num
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
Run Code
Output
Note: To test the program for a different number, change the value of num .
Initially, the sum is initialized to 0. And, the number is stored in variable num .
Then, we used the while loop to iterate until num becomes zero. In each
iteration of the loop, we have added the num to sum and the value of num is
decreased by 1.
We could have solved the above problem without using a loop by using the
following formula.
n*(n+1)/2
terms = 10
Output
Note: To test for different number of terms, change the value of terms variable
Output
The decimal system is the most widely used number system. However,
computers only understand binary. Binary, octal and hexadecimal number
systems are closely related, and we may require to convert decimal into these
systems.
The decimal system is base 10 (ten symbols, 0-9, are used to represent a
number) and similarly, binary is base 2, octal is base 8 and hexadecimal is
base 16.
Output
Note: To test the program for other decimal numbers, change the value
of dec in the program.
In this program, we have used built-in functions bin(), oct() and hex() to
convert the given decimal number into respective number systems.
abcd... = an + bn + cn + dn + ...
For example,
Visit this page to learn how you can check whether a number is an Armstrong
number or not in Python.
Source Code
# Program to check Armstrong numbers in a certain interval
lower = 100
upper = 2000
# order of number
order = len(str(num))
# initialize sum
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
Run Code
Output
153
370
371
407
1634
Here, we have set the lower limit 100 in variable lower and upper limit 2000 in
variable upper using Python range(). We have used for loop to iterate from
variable lower to upper . In iteration, the value of lower is increased by 1 and
checked whether it is an Armstrong number or not.
You can change the range and test out by changing the
variables lower and upper . Note, the variable lower should be lower
than upper for this program to work properly.
Source Code
# Sum of natural numbers up to num
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)
Run Code
Output
Note: To test the program for a different number, change the value of num .
Initially, the sum is initialized to 0. And, the number is stored in variable num .
Then, we used the while loop to iterate until num becomes zero. In each
iteration of the loop, we have added the num to sum and the value of num is
decreased by 1.
We could have solved the above problem without using a loop by using the
following formula.
n*(n+1)/2
terms = 10
Output
Note: To test for different number of terms, change the value of terms variable.
Python Program to Find Numbers
Divisible by Another Number
To understand this example, you should have the knowledge of the
following Python programming topics:
Python Lambda/Anonymous Function
Python List
Output
The decimal system is the most widely used number system. However,
computers only understand binary. Binary, octal and hexadecimal number
systems are closely related, and we may require to convert decimal into these
systems.
The decimal system is base 10 (ten symbols, 0-9, are used to represent a
number) and similarly, binary is base 2, octal is base 8 and hexadecimal is
base 16.
Source Code
# Python program to convert decimal into other number systems
dec = 344
Output
Note: To test the program for other decimal numbers, change the value
of dec in the program.
In this program, we have used built-in functions bin(), oct() and hex() to
convert the given decimal number into respective number systems.
These functions take an integer (in decimal) and return a string.
c = 'p'
print("The ASCII value of '" + c + "' is", ord(c))
Run Code
Output
Note: To test this program for other characters, change the character
assigned to the c variable.
Here we have used ord() function to convert a character to an integer (ASCII
value). This function returns the Unicode code point of that character.
Unicode is also an encoding technique that provides a unique number to a
character. While ASCII only encodes 128 characters, the current Unicode has
more than 100,000 characters from hundreds of scripts.
Your turn: Modify the code above to get characters from their corresponding
ASCII values using the chr() function as shown below.
>>> chr(65)
'A'
>>> chr(120)
'x'
>>> chr(ord('S') + 1)
'T'
# define a function
def compute_hcf(x, y):
num1 = 54
num2 = 24
Output
The H.C.F. is 6
Here, two integers stored in variables num1 and num2 are passed to
the compute_hcf() function. The function computes the H.C.F. these two
numbers and returns it.
In the function, we first determine the smaller of the two numbers since the
H.C.F can only be less than or equal to the smallest number. We then use
a for loop to go from 1 to that number.
In each iteration, we check if our number perfectly divides both the input
numbers. If so, we store the number as H.C.F. At the completion of the loop,
we end up with the largest number that perfectly divides both the numbers.
The above method is easy to understand and implement but not efficient. A
much more efficient method to find the H.C.F. is the Euclidean algorithm.
Euclidean algorithm
This algorithm is based on the fact that H.C.F. of two numbers divides their
difference as well.
In this algorithm, we divide the greater by smaller and take the remainder.
Now, divide the smaller by this remainder. Repeat until the remainder is 0.
For example, if we want to find the H.C.F. of 54 and 24, we divide 54 by 24.
The remainder is 6. Now, we divide 24 by 6 and the remainder is 0. Hence, 6
is the required H.C.F.
The least common multiple (L.C.M.) of two numbers is the smallest positive
integer that is perfectly divisible by the two given numbers.
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
num1 = 54
num2 = 24
Output
Note: To test this program, change the values of num1 and num2 .
This program stores two number in num1 and num2 respectively. These numbers
are passed to the compute_lcm() function. The function returns the L.C.M of two
numbers.
In the function, we first determine the greater of the two numbers since the
L.C.M. can only be greater than or equal to the largest number. We then use
an infinite while loop to go from that number and beyond.
In each iteration, we check if both the numbers perfectly divide our number. If
so, we store the number as L.C.M. and break from the loop. Otherwise, the
number is incremented by 1 and the loop continues.
The above program is slower to run. We can make it more efficient by using
the fact that the product of two numbers is equal to the product of the least
common multiple and greatest common divisor of those two numbers.
while(y):
x, y = y, x % y
return x
num1 = 54
num2 = 24
# define a function
def compute_hcf(x, y):
num1 = 54
num2 = 24
Output
The H.C.F. is 6
Here, two integers stored in variables num1 and num2 are passed to
the compute_hcf() function. The function computes the H.C.F. these two
numbers and returns it.
In the function, we first determine the smaller of the two numbers since the
H.C.F can only be less than or equal to the smallest number. We then use
a for loop to go from 1 to that number.
In each iteration, we check if our number perfectly divides both the input
numbers. If so, we store the number as H.C.F. At the completion of the loop,
we end up with the largest number that perfectly divides both the numbers.
The above method is easy to understand and implement but not efficient. A
much more efficient method to find the H.C.F. is the Euclidean algorithm.
Euclidean algorithm
This algorithm is based on the fact that H.C.F. of two numbers divides their
difference as well.
In this algorithm, we divide the greater by smaller and take the remainder.
Now, divide the smaller by this remainder. Repeat until the remainder is 0.
For example, if we want to find the H.C.F. of 54 and 24, we divide 54 by 24.
The remainder is 6. Now, we divide 24 by 6 and the remainder is 0. Hence, 6
is the required H.C.F.
Also Read:
Python Program to Find LCM
Python Program to Find the Factors
of a Number
To understand this example, you should have the knowledge of the
following Python programming topics:
Python if...else Statement
Python for Loop
Python User-defined Functions
Source Code
# Python Program to find the factors of a number
num = 320
print_factors(num)
Run Code
Output
Note: To find the factors of another number, change the value of num .
In this program, the number whose factor is to be found is stored in num , which
is passed to the print_factors() function. This value is assigned to the
variable x in print_factors() .
In the function, we use the for loop to iterate from i equal to x . If x is perfectly
divisible by i , it's a factor of x .
Also Read:
Python Program to Find Numbers Divisible by Another Number
Python range()
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
Output
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no
In this program, we ask the user to choose an operation. Options 1, 2, 3, and
4 are valid. If any other input is given, Invalid Input is displayed and the loop
continues until a valid option is selected.
Two numbers are taken and an if...elif...else branching is used to execute
a particular section. User-defined
functions add() , subtract() , multiply() and divide() evaluate respective
operations and display the output.
Also Read:
Python if else
Python while loop
# importing modules
import itertools, random
Output
You got:
5 of Heart
1 of Heart
8 of Spade
12 of Spade
4 of Spade
Here we have used the standard modules itertools and random that comes
with Python.
yy = 2014 # year
mm = 11 # month
# To take month and year input from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
Output
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
You can change the value of variables yy and mm and run it to test this
program for other dates.
The first two terms are 0 and 1. All other terms are obtained by adding the
preceding two terms.This means to say the nth term is the sum of (n-1)th and
(n-2)th term.
Source Code
# Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
Output
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Run Code
Output
Note: To test the program for another number, change the value of num .
The factorial of a number is the product of all the integers from 1 to that
number.
For example, the factorial of 6 is 1*2*3*4*5*6 = 720 . Factorial is not defined for
negative numbers and the factorial of zero is one, 0! = 1.
Source Code
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
Output
Note: To find the factorial of another number, change the value of num .
Source Code
# Function to print binary number using recursion
def convertToBinary(n):
if n > 1:
convertToBinary(n//2)
print(n % 2,end = '')
# decimal number
dec = 34
convertToBinary(dec)
print()
Run Code
Output
100010
You can change the variable dec in the above program and run it to test out for
other values.
We can perform matrix addition in various ways in Python. Here are a couple
of them.
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in result:
print(r)
Run Code
Output
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
In this program we have used nested for loops to iterate through each row
and each column. At each point, we add the corresponding elements in the
two matrices and store it in the result.
Source Code: Matrix Addition using Nested List
Comprehension
# Program to add two matrices using list comprehension
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
for r in result:
print(r)
Run Code
The output of this program is the same as above. We have used nested list
comprehension to iterate through each element in the matrix.
List comprehension allows us to write concise codes and we must try to use
them frequently in Python. They are very helpful.
For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. The
first row can be selected as X[0] . And, the element in the first-row first column
can be selected as X[0][0] .
X = [[12,7],
[4 ,5],
[3 ,8]]
result = [[0,0,0],
[0,0,0]]
for r in result:
print(r)
Run Code
Output
[12, 4, 3]
[7, 5, 8]
In this program, we have used nested for loops to iterate through each row
and each column. At each point we place the X[i][j] element into result[j]
[i] .
X = [[12,7],
[4 ,5],
[3 ,8]]
for r in result:
print(r)
Run Code
The output of this program is the same as above. We have used nested list
comprehension to iterate through each element in the matrix.
Python Program to Multiply Two
Matrices
To understand this example, you should have the knowledge of the
following Python programming topics:
Python for Loop
Python List
Python Matrices and NumPy Arrays
For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix.
The first row can be selected as X[0] . And, the element in first row, first
column can be selected as X[0][0] .
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for r in result:
print(r)
Run Code
Output
In this program, we have used nested for loops to iterate through each row
and each column. We accumulate the sum of products in the result.
This technique is simple but computationally expensive as we increase the
order of the matrix.
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row
in X]
for r in result:
print(r)
Run Code
The output of this program is the same as above. To understand the above
code we must first know about built-in function zip() and unpacking argument
list using * operator.
We have used nested list comprehension to iterate through each element in
the matrix. The code looks complicated and unreadable at first. But once you
get the hang of list comprehensions, you will probably not go back to nested
loops.
Python Program to Check Whether
a String is Palindrome or Not
To understand this example, you should have the knowledge of the
following Python programming topics:
Python if...else Statement
Python Strings
String Methods
my_str = 'aIbohPhoBiA'
Output
Note: To test the program, change the value of my_str in the program.
In this program, we have taken a string stored in my_str .
In such cases, we may first want to clean up the string and remove all the
punctuation marks. Here is an example of how it is done.
Source Code
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
Output
Source Code
# Program to sort alphabetically the words form a string provided by the user
Output
In this program, we store the string to be sorted in my_str . Using the split()
method the string is converted into a list of words. The split() method splits the
string at whitespaces.
The list of words is then sorted using the sort() method, and all the words are
displayed.
Python offers a datatype called set whose elements must be unique. It can be
used to perform different set operations like union, intersection, difference and
symmetric difference.
Source Code
# Program to perform different set operations like in mathematics
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
Output
In this program, we take two different sets and perform different set operations
on them. This can equivalently done by using set methods.
# string of vowels
vowels = 'aeiou'
print(count)
Run Code
Output
Here, we have taken a string stored in ip_str . Using the method casefold() ,
print(count)
Run Code
When we want to send the same invitations to many people, the body of the
mail does not change. Only the name (and maybe address) needs to be
changed.
Mail merge is a process of doing this. Instead of writing each mail separately,
we have a template for body of the mail and a list of names that we merge
together to form all the mails.
For this program, we have written all the names in separate lines in the file
"names.txt". The body is in the "body.txt" file.
We open both the files in reading mode and iterate over each name using
a for loop. A new file with the name "[ name ].txt" is created, where name is the
name of that person.
We use the strip() method to clean up leading and trailing whitespaces
(reading a line from the file also reads the newline '\n' character). Finally, we
write the content of the mail into this file using the write() method.
Most of the file formats have headers (initial few bytes) which contain useful
information about the file.
For example, jpeg headers contain information like height, width, number of
color (grayscale or RGB) etc. In this program, we find the resolution of a jpeg
image reading these headers, without using any external library.
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into
it"""
# calculate height
height = (a[0] << 8) + a[1]
# calculate width
width = (a[0] << 8) + a[1]
jpeg_res("img1.jpg")
Output
In this program, we opened the image in binary mode. Non-text files must be
open in this mode. The height of the image is at 164th position followed by
width of the image. Both are 2 bytes long.
Note that this is true only for JPEG File Interchange Format (JFIF) standard. If
your image is encode using other standard (like EXIF), the code will not work.
We convert the 2 bytes into a number using bitwise shifting operator <<.
Finally, the resolution is displayed.
We do not feed the data from the file all at once, because some files are very
large to fit in memory all at once. Breaking the file into small chunks will make
the process memory efficient.
def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""
message = hash_file("track1.mp3")
print(message)
Output
633d7356947eec543c50b76a1852f92427f4dca9
In this program, we open the file in binary mode. Hash functions are available
in the hashlib module. We loop till the end of the file using a while loop. On
reaching the end, we get empty bytes object.
In each iteration, we only read 1024 bytes (this value can be changed
according to our wish) from the file and update the hashing function.
* *
* * *
* * * *
* * * * *
Source Code
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print()
Run Code
First, we get the height of the pyramid rows from the user.
In the first loop, we iterate from i = 0 to i = rows .
print(dict_1 | dict_2)
Run Code
Output
In Python 3.9 and later versions, the | operator can be used to merge
dictionaries.
Note: If there are two keys with the same name, the merged dictionary
contains the value of the latter key.
print({**dict_1, **dict_2})
Run Code
Output
Note: The above code works for Python 3.5 and above versions.
dict_3 = dict_2.copy()
dict_3.update(dict_1)
print(dict_3)
Run Code
Output
Here, we have first copied the elements of dict_2 to dict_3 using the dictionary
copy() method. Then, we updated dict_3 with the values of dict_1 using
the dictionary update() method.
Python Program to Safely Create a
Nested Directory
To understand this example, you should have the knowledge of the
following Python programming topics:
Python Directory and Files Management
Python Modules
Python Exception Handling
Directory Structure
Example 1: Using pathlib.Path.mkdir
For python 3.5 and above, you can use pathlib.Path.mkdir to create a nested
directory.
By default, parents is set False . In this case, if the parent directory is not
present, then FileNotFoundError is thrown. For example, if you want to create a
nested directory /folder1/folder2/folder3 , and folder1 (parent) does not exist
already, then FileNotFoundError is raised by default. So, we set it to True .
Note: You should provide the full path (absolute path) of the directory (not
relative path). If the directory already exists, the above code does not raise an
exception.
import os
os.makedirs("/root/dirA/dirB")
Using method makedirs() from module os , a nested directory can be created in
a simple way.
The parameter passed is the nested directory we wanted to create.
You should provide the full path (absolute path) of the directory (not relative
path). If the directory already exists, the above code does not raise an
exception.
import distutils.dir_util
distutils.dir_util.mkpath("/root/dirA/dirB")
You should provide the full path (absolute path) of the directory (not the
relative path). If the directory already exists, the above code does not raise an
exception.
try:
os.makedirs("/dirA/dirB")
except FileExistsError:
print("File already exists")
0 21
1 44
2 35
3 11
Using enumerate() , we can print both the index and the values.
Pass two loop variables index and val in the for loop. You can give any name
to these variables.
Print the required variables inside the for loop block.
The function of enumerate() is to add a counter (i.e. index ) to the iterate and
return it.
Output
1 21
2 44
3 35
4 11
Output
0 21
1 44
2 35
3 11
Output
[1, 2, 3, 4, 5, 6, 7]
Using list comprehension access the sublist from my_list , then access each
element of the sublist.
Each element num is stored in flat_list .
flat_list = []
for sublist in my_list:
for num in sublist:
flat_list.append(num)
print(flat_list)
Run Code
Output
[1, 2, 3, 4, 5, 6, 7]
Access each element of the sublist using a nested loop and append that
element to flat_list .
flat_list = list(itertools.chain(*my_list))
print(flat_list)
Run Code
Output
[1, 2, 3, 4, 5, 6, 7]
chain() method from itertools module returns each element of each iterable
(i.e. sub lists ).
list() converts those returned values into a list.
Example 4: Using sum()
my_list = [[1], [2, 3], [4, 5, 6, 7]]
Output
[1, 2, 3, 4, 5, 6, 7]
Provide two arguments to the sum() method: my_list and an empty list
(i.e. [ ] ).
Output
[1, 2, 3, 4, 5, 6, 7]
In the above example, reduce() applies the lambda function to all the elements
of my_list .
print(my_list[:])
Run Code
Output
[1, 2, 3, 4, 5]
If you simply use : , you will get all the elements of the list. This is similar
to print(my_list) .
Get all the Items After a Specific Position
my_list = [1, 2, 3, 4, 5]
print(my_list[2:])
Run Code
Output
[3, 4, 5]
If you want to get all the elements after a specific index, you can mention that
index before : as shown in example above.
In the above example, elements at index 2 and all the elements after index 2
are printed.
print(my_list[:2])
Run Code
Output
[1, 2]
This example lets you get all the elements before a specific index. Mention
that index after : .
In the example, the items before index 2 are sliced. Item on index 2 is
excluded.
print(my_list[2:4])
Run Code
Output
[3, 4]
If you want to get all the elements between two specific indices, you can
mention them before and after : .
In the above example, my_list[2:4] gives the elements between 2nd and the
4th positions. The starting position (i.e. 2) is included and the ending position
(i.e. 4) is excluded.
Output
[1, 3, 5]
If you want to get elements at specified intervals, you can do it by using two : .
In the above example, the items at interval 2 starting from index 0 are sliced.
If you want the indexing to start from the last item, you can use negative
sign - .
my_list = [1, 2, 3, 4, 5]
print(my_list[::-2])
Run Code
Output
[5, 3, 1]
The items at interval 2 starting from the last index are sliced.
If you want the items from one position to another, you can mention them
from start to stop .
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4:2])
Run Code
Output
[2, 4]
Output
a juice
b grill
c corn
Using a for loop, pass two loop variables key and value for
iterable dt.items() . items() returns the key:value pairs.
Print key and value .
Example 2: Access both key and value without using
items()
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}
Output
a juice
b grill
c corn
Print the loop variable key and value at key (i.e. dt[key] ).
Output
a juice
b grill
c corn
Output
a
b
c
juice
grill
corn
You can use keys() and values() to explicitly return keys and values of the
dictionary respectively.
Python Program to Sort a Dictionary
by Value
To understand this example, you should have the knowledge of the
following Python programming topics:
Python Dictionary
print(sorted_dt)
Run Code
Output
{6: 3, 5: 4, 1: 6}
Here, key=lambda item: item[1] returns the values of each key:value pair.
From each key:value pair of dt.item() , sorted() sorts the items based on
values.
Learn more about sorted() and its parameter key at Python sorted().
Example 2: Sort only the values
dt = {5:4, 1:6, 6:3}
sorted_dt_value = sorted(dt.values())
print(sorted_dt_value)
Run Code
Output
[3, 4, 6]
In this example, sorted() is used for sorted values only. The values are fed
into sorted() using dt.values() .
Output
the list is empty
Output
In this example, length of list is used to check if there is any element in the list.
If the length of a list is 0, then the list is empty.
Multiple exceptions can be caught using a tuple . The errors can be passed
through a tuple as shown in example below.
Multiple exceptions as a parenthesized tuple
string = input()
try:
num = int(input())
print(string+num)
except (TypeError, ValueError) as e:
print(e)
Run Code
Input
a
2
Output
Here, we try to catch two types of exceptions TypeError and ValueError , which
are passed as inside a tuple in the except block.
In the above example, string and an integer cannot be added, so TypeError is
caught.
Let's see another example with a different exception.
Input
a
b
Output
In the above example, the second input should have been an integer, but we
passed a string 'b' . Therefore, ValueError is raised.
The first parameter of copyfile() is the path of the source file and the second
parameter is the path of the destination file. The content of the destination file
is replaced with the content of the source file.
There are other methods copy() , cop2() , and copyfileobj() which serve the
same purpose with some metadata changes.
Preserves Supports Directory as Copies Supports file
Method
Permissions Destination Metadata object
copyfile() No No No No
copyfileobj() No No No Yes
Output
[1, 'a', 3, 4, 5]
Output
[1, 'a', 2, 3]
Output
[1, 2, 3, 'a']
If you want the unique items from a concatenated list, you can
use list() and set(). set() selects the unique values and list() converts the set
into list.
list_2.extend(list_1)
print(list_2)
Run Code
Output
[1, 2, 3, 1, 'a']
Using extend() , you can concatenate a list to another list as shown in example
above.
Using in keyword
my_dict = {1: 'a', 2: 'b', 3: 'c'}
if 2 in my_dict:
print("present")
Run Code
Output
present
You can use not in if you want to check if a key is not present in the
dictionary.
chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))
Run Code
Output
chunk_size = 2
list_chunked = [my_list[i:i + chunk_size] for i in range(0, len(my_list),
chunk_size)]
print(list_chunked)
Run Code
Output
my_list = [1,2,3,4,5,6,7,8,9]
print(np.array_split(my_list, 5))
Run Code
Output
[array([1, 2]), array([3, 4]), array([5, 6]), array([7, 8]), array([9])]
array_split() is a numpy method that splits a list into equal sized chunks.
Here, the number of chunks is 5.
Output
<class 'int'>
1500
Output
<class 'float'>
1500.4
Output
<class 'int'>
1500
If the string is a float numeral, you can convert it into a float type using float() ,
Programiz
The working of the above line of code is shown in the figure below.
\x1b calls a function. You can also use \033 for the same purpose.
38;2;r;g;b helps to set RGB color. 5;86;243 are the rgb color for blue (the color
of the logo of Programiz).
m is the function name. Here, m means SGR (Select Graphics Rendition)
function.
For more information regarding the ANSI escape code, you can refer to ANSI
escape code.
print(colored('Programiz', 'blue'))
Run Code
Output
Programiz
Using the module termcolor, you can get the desired output. Also, you can set
different styles of the text using this module.
The first parameter of colored() is the text and the second parameter is the
color.
print(type(datetime_object))
print(datetime_object)
Run Code
Output
<class 'datetime.datetime'>
2011-03-11 11:31:00
Using strptime() , date and time in string format can be converted to datetime
type. The first parameter is the string and the second is the date time format
specifier.
One advantage of converting to date format is one can select the month or
date or time individually.
If you want to learn more about the directives and strptime() , please go
to Python strptime() - string to datetime object.
print(date_time)
print(type(date_time))
Run Code
Output
2011-03-11 11:31:00
<class 'datetime.datetime'>
Using dateutil module, parse() can be used to convert a string into date time
format. The only parameter used is the string.
Python Program to Get the Last
Element of the List
To understand this example, you should have the knowledge of the
following Python programming topics:
Python List
Output
When you use negative indexing, the counting starts from 1 not 0 as shown in
the figure below.
List indexing in Python
If you want the first 1st element, you can use my_list[-5] .
of a String
To understand this example, you should have the knowledge of the
following Python programming topics:
Python Strings
Using String slicing
my_string = "I love python."
# prints "love"
print(my_string[2:6])
Output
love
love python.
I love python
String slicing works similar to list slicing. The working of above code can be
understood in the following points.
[2:6]
You need to specify the starting index and the ending index of the substring.
In this case, love starts at index 2 and ends at index 6.
[2:]
honda 1948
mercedes 1926
ford 1903
Source Code
with open("data_file.txt") as f:
content_list = f.readlines()
Output
If you want to remove the new lines (' \n '), you can use strip().
Example 2: Using for loop and list comprehension
with open('data_file.txt') as f:
content_list = [line for line in f]
print(content_list)
print(content_list)
Run Code
Output
Another way to achieve the same thing is using a for loop. In each iteration,
you can read each line of f object and store it in content_list as shown in the
example above.
Also Read:
Python for Loop
Python List Comprehension
Python Program to Randomly
Select an Element From the List
To understand this example, you should have the knowledge of the
following Python programming topics:
Python List
Output
31
Output
Using choice() method of secrets module, you can select a random element
from the list.
It is cryptographically safer than the random module.
Using float()
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
print(isfloat('s12'))
print(isfloat('1.123'))
Run Code
Output
False
True
Here, we have used try except in order to handle the ValueError if the string is
not a float.
In the function isfloat() , float() tries to convert num to float. If it is successful,
then the function returns True .
Using count() method, pass the item to be counted. As shown above, 'a' is
passed, which gives the total number of occurrences of character 'a' .
honda 1948
mercedes 1926
ford 1903
mercedes 1926
Open the file in append 'a' mode, and write to it using write() method.
Inside write() method, a string "new text" is passed. This text is seen on the
file as shown above.
If you want to learn more about different types of file opening modes, please
refer to Python file I/O.
del my_dict[31]
print(my_dict)
Run Code
Output
print(my_dict.pop(31))
print(my_dict)
Run Code
Output
a
{21: 'b', 14: 'c'}
Pass the key 31 as an argument to the pop() method. It deletes the key:value
pair with key as 31 as shown in the output.
pop() also returns the value of the key passed.
print(my_string)
Run Code
Output
print(my_string)
Run Code
Output
If you use (" ") syntax, you need to specify the newlines explicitly using \n .
Example 3: Using \
my_string = "The only way to \n" \
"learn to program is \n" \
"by writing code."
print(my_string)
Run Code
Output
You can use \ as in the above example code to write a multiline string.
Output
('/path/file', '.ext')
.ext
os.path.splitext() gives a tuple with one item as the name of the file along
with the path and the other is the extension of the file. If you want the file
extension only, you can print it as shown above file_details[1] .
Output
.ext
Using suffix attribute from pathlib module, we can get the extension of a file.
In the above example, .ext is the extension of file file.ext .
Note: It works for python 3.4 and above.
start = time.time()
print(23*2.3)
end = time.time()
print(end - start)
Run Code
Output
52.9
3.600120544433594e-05
In order to calculate the time elapsed in executing a code, the time module
can be used.
Save the timestamp at the beginning of the code start using time() .
Save the timestamp at the end of the code end .
Find the difference between the end and start, which gives the execution time.
start = timer()
print(23*2.3)
end = timer()
print(end - start)
Run Code
Output
52.9
6.355400000000039e-05
Also Read:
Python Program to Create a Countdown Timer
Python Program to Get the Class
Name of an Instance
To understand this example, you should have the knowledge of the
following Python programming topics:
Python Object Oriented Programming
Python Classes and Objects
v = Vehicle()
print(v.__class__.__name__)
Run Code
Output
Vehicle
v = Vehicle()
print(type(v).__name__)
Run Code
Output
Vehicle
Using attribute __name__ with type(), you can get the class name of an
instance/object as shown in the example above. type() gives the class of
object v and __name__ gives the class name.
Output
We have two lists: index and languages . They are first zipped and then
converted into a dictionary.
The zip() function takes iterables (can be zero or more), aggregates them in
a tuple, and returns it.
Likewise, dict() gives the dictionary.
Output
class Triangle(Polygon):
def area(self):
pass
obj_polygon = Polygon()
obj_triangle = Triangle()
Output
True
False
True
True
print(my_string.strip())
Run Code
Output
Python
strip() removes the leading and trailing characters including the whitespaces
from a string.
However, if you have characters in the string like '\n' and you want to remove
only the whitespaces, you need to specify it explicitly on the strip() method
as shown in the following code.
my_string = " \nPython "
print(my_string.strip(" "))
Run Code
Output
Python
print(output)
Run Code
Output
Hello python
Output
file
print(os.path.splitext(file_name))
Run Code
Output
('file', '.ext')
print(Path('/root/file.ext').stem)
Run Code
Output
file
Using stem attribute of Path module, the file name can be extracted as shown
above.
It works for python 3.4 and above.
Also Read:
Python Program to Get the Full Path of the Current Working Directory
Python Program to Extract Extension From the File Name
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
Output
Day.MONDAY
MONDAY
1
Here, we have class Day with the object Enum as its argument. name and value
are the attributes of Enum which give the name and value of the
member MONDAY respectively.
You can refer to the official documentation of enum for more information.
Python Program to Return Multiple
Values From a Function
To understand this example, you should have the knowledge of the
following Python programming topics:
Python Functions
Output
('John', 'Armin')
John Armin
When you return multiple values using comma(s), they are returned in the
form of a tuple. As shown in the code above, two
strings "John" and "Armin" are returned with a single return statement.
Example 2: Using a dictionary
def name():
n1 = "John"
n2 = "Armin"
names = name()
print(names)
Run Code
Output
When you return values using a dictionary, it is easy for you to keep track of
the returned values using the keys. The return statement returns the two
variables in the form a dictionary.
honda 1948
mercedes 1926
ford 1903
Source Code
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print(file_len("my_file.txt"))
Run Code
Output
print(num_of_lines)
Run Code
Output
os.chdir("my_dir")
Output
c.txt
b.txt
a.txt
Using glob module, you can search for files with certain extensions.
os.chdir("my_dir") sets the current working directory to /my_dir .
Using a for loop, you can search for files with .txt extension using glob() .
Example 2: Using os
import os
Output
a.txt
b.txt
c.txt
Using os.walk
import os
Output
c.txt
b.txt
a.txt
file = pathlib.Path('abc.py')
print("Last modification time: %s" % time.ctime(os.path.getmtime(file)))
print("Last metadata change time or path creation time: %s" %
time.ctime(os.path.getctime(file)))
Run Code
Output
getmtime() gives the last modification time whereas getctime() gives the last
metadata change time in Linux/Unix and path creation time in Windows.
Example 2: Using stat() method
import datetime
import pathlib
fname = pathlib.Path('abc.py')
print("Last modification time: %s" %
datetime.datetime.fromtimestamp(fname.stat().st_mtime))
print("Last metadata change time or path creation time: %s" %
datetime.datetime.fromtimestamp(fname.stat().st_ctime))
Run Code
Output
Output
/Users/username
/Users/username
Using the pathlib module, you can get the current working directory.
Pass the file's name in Path() method.
parent gives the logical parent of the path and absolute() gives the absolute
path of the file.
pathlib.Path().absolute() gives the current working directory.
Output
/Users/username
/Users/username
Output
1 a
2 b
3 c
Using zip() method, you can iterate through two lists parallel as shown above.
The loop runs until the shorter list stops (unless other conditions are passed).
list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']
print("\n")
Output
1 a
2 b
3 c
1 a
2 b
3 c
4 None
Using the zip_longest() method of itertools module, you can iterate through
two parallel lists at the same time. The method lets the loop run until the
longest list stops.
file_stat = os.stat('my_file.txt')
print(file_stat.st_size)
Run Code
Output
34
Using stat() from the os module, you can get the details of a file. Use
the st_size attribute of stat() method to get the file size.
The unit of the file size is byte .
Example 2: Using pathlib module
from pathlib import Path
file = Path('my_file.txt')
print(file.stat().st_size)
Run Code
Output
34
Using the pathlib module, you can do the same thing as shown above. The
unit of the file size is byte .
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))
Run Code
Output
4321
1. First, the remainder of the num divided by 10 is stored in the variable digit .
num is then divided by 10 so that now it only contains the first three digits: 123.
2. After second iteration, digit equals 3, reversed equals 4 * 10 + 3 = 43 and num
= 12 .
3. After third iteration, digit equals 2, reversed equals 43 * 10 + 2 = 432 and num
= 1.
5. Now num = 0 , so the test expression num != 0 fails and while loop exits.
reversed already contains the reversed number 4321.
Output
654321
Using the string slicing concept, you can get reverse the string. ::-
result = 1
while exponent != 0:
result *= base
exponent-=1
Output
Answer = 81
In this program, base and exponent are assigned values 3 and 4 respectively.
Using the while loop, we keep on multiplying the result by base until
the exponent becomes zero.
In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 *
3 * 3 = 81 .
result = 1
Output
Answer = 81
Here, instead of using a while loop, we've used a for loop.
Both programs above do not work if you have a negative exponent. For that,
you need to use the pow() function in the Python library.
Also Read: Python range()
Output
Answer = 0.012345679012345678
pow() accepts two arguments: base and exponent. In the above example, 3
raised to the power -4 is calculated using pow() .
Python Program to Count the
Number of Digits Present In a
Number
To understand this example, you should have the knowledge of the
following Python programming topics:
Python while Loop
Python for Loop
while num != 0:
num //= 10
count += 1
Output
Number of digits: 4
In this program, the while loop is iterated until the test expression num != 0 is
evaluated to 0 (false).
1. After the first iteration, num will be divided by 10 and its value will be 345.
Then, the count is incremented to 1.
2. After the second iteration, the value of num will be 34 and the count is
incremented to 2.
3. After the third iteration, the value of num will be 3 and the count is incremented
to 3.
4. After the fourth iteration, the value of num will be 0 and the count is incremented
to 4.
5. Then the test expression is evaluated to false and the loop terminates.
Output
In the above example, we first convert the integer value into string by
using str(). Then, we find the length of the string using len().
Two strings are said to be anagram if we can form one string by arranging the
characters of another string. For example, Race and Care. Here, we can form
Race by arranging the characters of Care.
Output
Output
Programiz is Lit
cap_string = my_string.capitalize()
print(cap_string)
Run Code
Output
Programiz is lit
For example: the number of ways in which characters from yup can be
selected are yup , ypu , uyp , upy , puy , pyu , and not selecting any.
We will perform the same in the following examples.
if i == len(string):
print("".join(string))
# swap
words[i], words[j] = words[j], words[i]
get_permutation(words, i + 1)
print(get_permutation('yup'))
Run Code
Output
yup
ypu
uyp
upy
puy
pyu
None
In each iteration of the for loop, each character of yup is stored in words .
The elements of words are swapped. In this way, we achieve all different
combinations of characters.
Output
def countdown(time_sec):
while time_sec:
mins, secs = divmod(time_sec, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)
Run Code
The divmod() method takes two numbers and returns a pair of numbers (a
tuple) consisting of their quotient and remainder.
end='\r' overwrites the output for each iteration.
The value of time_sec is decremented at the end of each iteration.
my_string = "Programiz"
my_char = "r"
for i in my_string:
if i == my_char:
count += 1
print(count)
Run Code
Output
In the above example, we have found the count of 'r' in 'Programiz' . The for-
loop loops over each character of my_string and the if condition checks if each
character of my_string is 'r' . The value of count increases if there is a match.
print(my_string.count(my_char))
Run Code
Output
print(list(set(list_1)))
Run Code
Output
[1, 2, 4, 6]
In the above example, we first convert the list into a set, then we again
convert it into a list. Set cannot have a duplicate item in it, so set() keeps only
an instance of the item.
print(list(set(list_1) ^ set(list_2)))
Run Code
Output
[4, 6, 7, 8]
In the above example, the items that are present in both lists are removed.
Firstly, both lists are converted to two sets to remove the duplicate items from
each list.
Then, ^ gets the symmetric difference of two lists (excludes the overlapping
elements of two sets).
Using decode()
print(b'Easy \xE2\x9C\x85'.decode("utf-8"))
Run Code
Output
Easy ✅
Using decode() , you can convert bytes into string. Here, we have used utf-8 for
decoding. \xE2\x9C\x85 is the utf-8 code for ✅.
1. Python Program to Print Hello world!
2. Python Program to Add Two Numbers
3. Python Program to Find the Square Root
4. Python Program to Calculate the Area of a Triangle
5. Python Program to Solve Quadratic Equation
6. Python Program to Swap Two Variables
7. Python Program to Generate a Random Number
8. Python Program to Convert Kilometers to Miles
9. Python Program to Convert Celsius To Fahrenheit
10. Python Program to Check if a Number is Positive, Negative or 0
11. Python Program to Check if a Number is Odd or Even
12. Python Program to Check Leap Year
13. Python Program to Find the Largest Among Three Numbers
14. Python Program to Check Prime Number
15. Python Program to Print all Prime Numbers in an Interval
16. Python Program to Find the Factorial of a Number
17. Python Program to Display the multiplication Table
18. Python Program to Print the Fibonacci sequence
19. Python Program to Check Armstrong Number
20. Python Program to Find Armstrong Number in an Interval
21. Python Program to Find the Sum of Natural Numbers
22. Python Program to Display Powers of 2 Using Anonymous Function
23. Python Program to Find Numbers Divisible by Another Number
24. Python Program to Convert Decimal to Binary, Octal and Hexadecimal
25. Python Program to Find ASCII Value of Character
26. Python Program to Find HCF or GCD
27. Python Program to Find LCM
28. Python Program to Find the Factors of a Number
29. Python Program to Make a Simple Calculator
30. Python Program to Shuffle Deck of Cards
31. Python Program to Display Calendar
32. Python Program to Display Fibonacci Sequence Using Recursion
33. Python Program to Find Sum of Natural Numbers Using Recursion
34. Python Program to Find Factorial of Number Using Recursion
35. Python Program to Convert Decimal to Binary Using Recursion
36. Python Program to Add Two Matrices
37. Python Program to Transpose a Matrix
38. Python Program to Multiply Two Matrices
39. Python Program to Check Whether a String is Palindrome or Not
40. Python Program to Remove Punctuations From a String
41. Python Program to Sort Words in Alphabetic Order
42. Python Program to Illustrate Different Set Operations
43. Python Program to Count the Number of Each Vowel
44. Python Program to Merge Mails
45. Python Program to Find the Size (Resolution) of an Image
46. Python Program to Find Hash of File
47. Python Program to Create Pyramid Patterns
48. Python Program to Merge Two Dictionaries
49. Python Program to Safely Create a Nested Directory
50. Python Program to Access Index of a List Using for Loop
51. Python Program to Flatten a Nested List
52. Python Program to Slice Lists
53. Python Program to Iterate Over Dictionaries Using for Loop
54. Python Program to Sort a Dictionary by Value
55. Python Program to Check If a List is Empty
56. Python Program to Catch Multiple Exceptions in One Line
57. Python Program to Copy a File
58. Python Program to Concatenate Two Lists
59. Python Program to Check if a Key is Already Present in a Dictionary
60. Python Program to Split a List Into Evenly Sized Chunks
61. Python Program to Parse a String to a Float or Int
62. Python Program to Print Colored Text to the Terminal
63. Python Program to Convert String to Datetime
64. Python Program to Get the Last Element of the List
65. Python Program to Get a Substring of a String
66. Python Program to Print Output Without a Newline
67. Python Program Read a File Line by Line Into a List
68. Python Program to Randomly Select an Element From the List
69. Python Program to Check If a String Is a Number (Float)
70. Python Program to Count the Occurrence of an Item in a List
71. Python Program to Append to a File
72. Python Program to Delete an Element From a Dictionary
73. Python Program to Create a Long Multiline String
74. Python Program to Extract Extension From the File Name
75. Python Program to Measure the Elapsed Time in Python
76. Python Program to Get the Class Name of an Instance
77. Python Program to Convert Two Lists Into a Dictionary
78. Python Program to Differentiate Between type() and isinstance()
79. Python Program to Trim Whitespace From a String
80. Python Program to Get the File Name From the File Path
81. Python Program to Represent enum
82. Python Program to Return Multiple Values From a Function
83. Python Program to Get Line Count of a File
84. Python Program to Find All File with .txt Extension Present Inside a Directory
85. Python Program to Get File Creation and Modification Date
86. Python Program to Get the Full Path of the Current Working Directory
87. Python Program to Iterate Through Two Lists in Parallel
88. Python Program to Check the File Size
89. Python Program to Reverse a Number
90. Python Program to Compute the Power of a Number
91. Python Program to Count the Number of Digits Present In a Number
92. Python Program to Check If Two Strings are Anagram
93. Python Program to Capitalize the First Character of a String
94. Python Program to Compute all the Permutation of the String
95. Python Program to Create a Countdown Timer
96. Python Program to Count the Number of Occurrence of a Character in String
97. Python Program to Remove Duplicate Element From a List
98. Python Program to Convert Bytes to a String