Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2104

C Language Syllabus

1. Basic of C: Keywords, Identifiers, Data types, Variables, Constants, Input/ Output,


Operators, Storage Classes, Format Specifiers

 Keywords & Identifier


 Variables & Constants
 C Data Types
 C Input/Output
 C Comments
 C Operators
 C Introduction Examples

2. Control Statements: if-else, for, while, do-whileloop, break, continue

 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

5. Strings: Library functions, Pointers & Strings

 C Programming String
 C String Functions
 C String Examples

6. Structures & Union

 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

#include<stdio.h> /*# is a pre processor directive- directed to stdio.h (header file)

#incluide<conio.h> /*#include is a standard form of including header file from C library

/* main function

void main () /*# include<stdio.h> is a statement which tells the compiler to insert

{ the contents of stdio at that particular place.


/*start a program

clrscr(); /*header files 1) #include<stdio.h> 2)#include (math.h>

int a,b,c; 3)#include<stdlib.h> 4)#include <conio.h>

/*program statment

printf(“enter the value of a”); /*conio.h is s C header file used mostly by MS-DOS compilers

scanf(%d”,&a); to provide console input/output. It is not part of the C

printf(enter the value of b”); standard library or ISO C,

scanf(%d”,&b);

c=a+b;

printf(“addition=%d”,c);

getch(); /* end of program

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

// printf() displays the content inside the double quotes

printf("Hello, World! \n");

return 0;

Output: Hello, World

Command Description

It is a preprocessor command which consists of a standard input


#include <stdio.h>
output header file(stdio.h) before compiling a C program.

The main function from where execution of any C program


int main()
starts.

{ Indicates the beginning of the main function.

Any content inside “/* */” will not be used for compilation
/*_some_comments_*/
and execution.

printf(“Hello_World! “); Prints the output on the screen.

getch(); Used for any character input from keyboard.

return 0; Terminates a C program or main function and returns 0.


} Indicates the end of the main function.

How does a C Program Work?

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.

C Keywords and Identifiers

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

C accepts both lowercase and uppercase alphabets as variables and


functions.

Digits

0 1 2 3 4 5 6 7 8 9

Special Characters

Special Characters in C Programming

, < > . _

( ) ; $ :

% [ ] # ?

' & { } "


^ ! * / |

- \ ~ +

White space Characters


Blank space, newline, horizontal tab, carriage return and form feed.

C Keywords

Keywords are predefined, reserved words used in programming that have


special meanings to the compiler. Keywords are part of the syntax and they
cannot be used as an identifier. For example:

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

auto double int struct

break else long switch

case enum register typedef

char extern return union


continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

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.

Identifiers must be unique. They are created to give a unique name to an


entity to identify it during the execution of the program. For example:

int money;
double accountBalance;

Here, money and accountBalance are identifiers.


Also remember, identifier names must be different from keywords. You cannot
use int as an identifier because int is a keyword.
C Variables, Constants and Literals

Variables

In programming, a variable is a container (storage area) to hold data.

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:

int playerScore = 95;

Here, playerScore is a variable of int type. Here, the variable is assigned an


integer value 95 .

The value of a variable can be changed, hence the name variable.

char ch = 'a';
// some code
ch = 'l';

Rules for naming a variable

1. A variable name can only have letters (both uppercase and lowercase letters),
digits and underscore.

2. The first letter of a variable should be either a letter or an underscore.


3. There is no rule on how long a variable name (identifier) can be. However,
you may run into problems in some compilers if the variable name is longer
than 31 characters.

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:

int number = 5; // integer variable


number = 5.5; // error
double number; // error

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

An integer is a numeric literal(associated with numbers) without any fractional


or exponential part. There are three types of integer literals in C programming:

 decimal (base 10)

 octal (base 8)

 hexadecimal (base 16)

For example:

Decimal: 0, -9, 22 etc

Octal: 021, 077, 033 etc

Hexadecimal: 0x7f, 0x2a, 0x521 etc

In C programming, octal starts with a 0 , and hexadecimal starts with a 0x .

2. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an


exponent form. For example:

-2.0
0.0000234

-0.22E-5

Note: E-5 = 10-5

3. Characters

A character literal is created by enclosing a single character inside single


quotation marks. For example: 'a' , 'm' , 'F' , '2' , '}' etc.

4. Escape Sequences

Sometimes, it is necessary to use characters that cannot be typed or has


special meaning in C programming. For example: newline(enter), tab,
question mark etc.

In order to use these characters, escape sequences are used.


Escape Sequences

Escape Sequences Character

\b Backspace

\f Form feed

\n Newline

\r Return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\' Single quotation mark

\" Double quotation mark

\? 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

A string literal is a sequence of characters enclosed in double-quote marks.


For example:

"good" //string constant

"" //null string constant

" " //string constant of six white space

"x" //string constant having a single character.

"Earth is round\n" //prints string with a newline

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,

const double PI = 3.14;

Notice, we have added keyword const .

Here, PI is a symbolic constant; its value cannot be changed.


const double PI = 3.14;
PI = 2.9; //Error

You can also define a constant using the #define preprocessor directive. We
will learn about it in C Macros tutorial.

C Data Types

In C programming, data types are declarations for variables. This determines


the type and size of data associated with variables. For example,

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.

Type Size (bytes) Format Specifier

int at least 2, usually 4 %d , %i

char 1 %c

float 4 %f
Type Size (bytes) Format Specifier

double 8 %lf

short int 2 usually %hd

unsigned int at least 2, usually 4 %u

long int at least 4, usually 8 %ld , %li

long long int at least 8 %lld , %lli

unsigned long int at least 4 %lu

unsigned long long int at least 8 %llu

signed char 1 %c

unsigned char 1 %c

long double at least 10, usually 12 or 16 %Lf


int

Integers are whole numbers that can have both zero, positive and negative
values but no decimal values. For example, 0 , -5 , 10

We can use int for declaring an integer variable.

int id;

Here, id is a variable of type integer.


You can declare multiple variables at once in C programming. For example,

int id, age;

The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states
from -2147483648 to 2147483647 .

float and double

float and double are used to hold real numbers.

float salary;
double price;

In C, floating-point numbers can also be represented in exponential. For


example,

float normalizationFactor = 22.442e2;

What's the difference between float and double ?


The size of float (single precision float data type) is 4 bytes. And the size
of double (double precision float data type) is 8 bytes.

char

Keyword char is used for declaring character type variables. For example,

char test = 'h';

The size of the character variable is 1 byte

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 .

Note that, you cannot create variables of void type.

short and long

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;

printf("size of short = %d bytes\n", sizeof(a));


printf("size of long = %d bytes\n", sizeof(b));
printf("size of long long = %d bytes\n", sizeof(c));
printf("size of long double= %d bytes\n", sizeof(d));
return 0;
}
Run Code

size of short = 2 bytes

size of long = 8 bytes

size of long long = 8 bytes

size of long double= 16 bytes

=== Code Execution Successful ===


signed and unsigned

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

// invalid code: unsigned int cannot hold negative integers


unsigned int num = -35;

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 -

231 to 231-1 , whereas variable x can hold values from 0 to 232-1 .

Derived Data Types


Data types that are derived from fundamental data types are derived types.
For example: arrays, pointers, function types, structures, etc.

We will learn about these derived data types in later tutorials.

 bool type
 Enumerated type

 Complex types

C Input Output (I/O)


C Output
In C programming, printf() is one of the main output function. The function
sends formatted output to the screen. For example,

Example 1: C Output
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Run Code

Output

C Programming

How does this program work?

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

Example 2: Integer Output


#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Run Code

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 .

Example 3: float and double Output


#include <stdio.h>
int main()
{
float number1 = 13.5;
double number2 = 12.4;
printf("number1 = %f\n", number1);
printf("number2 = %lf", number2);
return 0;
}
Run Code

Output

number1 = 13.500000
number2 = 12.400000

To print float , we use %f format specifier. Similarly, we use %lf to


print double values.

Example 4: Print Characters


#include <stdio.h>
int main()
{
char chr = 'a';
printf("character = %c", chr);
return 0;
}
Run Code

Output

character = a

To print char , we use %c format specifier.


C Input
In C programming, scanf() is one of the commonly used function to take input
from the user. The scanf() function reads formatted input from the standard
input such as keyboards.

Example 5: Integer Input/Output


#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Run Code

Output

Enter an integer: 4
Number = 4

Here, we have used %d format specifier inside the scanf() function to


take int input from the user. When the user enters an integer, it is stored in
the testInteger variable.

Notice, that we have used &testInteger inside scanf() . It is


because &testInteger gets the address of testInteger , and the value entered
by the user is stored in that address.
Example 6: Float and Double Input/Output
#include <stdio.h>
int main()
{
float num1;
double num2;

printf("Enter a number: ");


scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);

printf("num1 = %f\n", num1);


printf("num2 = %lf", num2);

return 0;
}
Run Code

Output

Enter a number: 12.523


Enter another number: 10.2
num1 = 12.523000
num2 = 10.200000

We use %f and %lf format specifier for float and double respectively.

Example 7: C Character I/O


#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}
Run Code

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.

Example 8: ASCII Value


#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);

// When %c is used, a character is displayed


printf("You entered %c.\n",chr);

// When %d is used, ASCII value is displayed


printf("ASCII value is %d.", chr);
return 0;
}
Run Code

Output

Enter a character: g
You entered g.
ASCII value is 103.

I/O Multiple Values

Here's how you can take multiple inputs from the user and display them.

#include <stdio.h>
int main()
{
int a;
float b;

printf("Enter integer and then a float: ");

// Taking multiple inputs


scanf("%d%f", &a, &b);

printf("You entered %d and %f", a, b);


return 0;
}
Run Code

Output

Enter integer and then a float: -3


3.4
You entered -3 and 3.400000
Format Specifiers for I/O
As you can see from the above examples, we use

 %d for int

 %f for float

 %lf for double

 %c for char

Here's a list of commonly used C data types and their format specifiers.

Data Type Format Specifier

int %d

char %c

float %f

double %lf

short int %hd

unsigned int %u

long int %li

long long int %lli


Data Type Format Specifier

unsigned long int %lu

unsigned long long int %llu

signed char %c

unsigned char %c

long double %Lf

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

// print Hello World to the screen


printf("Hello World");
return 0;
}
Run Code

Hello World

=== Code Execution Successful ===


Here, // print Hello World to the screen is a comment in C programming.
Comments are completely ignored by C compilers.

Types of Comments
There are two ways to add comments in C:

1. // - Single Line Comment


2. /*...*/ - Multi-line Comment

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

// create integer variable


int age = 25;

// print the age variable


printf("Age: %d", age);

return 0;
}

Output
Age: 25

In the above example, // create integer variable and // print the age

variable are two single line comments.


We can also use the single line comment along with the code. For example,

int age = 25; // create integer variable

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.

To write multi-line comments, we use the /*....*/ symbol. For example,


/* This program takes age input from the user
It stores it in the age variable
And, print the value using printf() */

#include <stdio.h>

int main() {

int age;

printf("Enter the age: ");


scanf("%d", &age);

printf("Age = %d", age);


return 0;
}
Run Code

Output

Enter the age: 24


Age = 24

In this type of comment, the C compiler ignores everything from /* to */.

Note: Remember the keyboard shortcut to use comments:


 Single Line comment: ctrl + / (windows) and cmd + / (mac)

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

2. Using Comments for debugging


While debugging there might be situations where we don't want some part of
the code. For example,
In the program below, suppose we don't need data related to height. So,
instead of removing the code related to height, we can simply convert them
into comments.

// Program to take age and height input

#include <stdio.h>

int main() {

int age;
// double height;

printf("Enter the age: ");


scanf("%d", &age);

// printf("Enter the height: ");


// scanf("%lf", &height);

printf("Age = %d", age);


// printf("\nHeight = %.1lf", height);

return 0;
}
Run Code

Enter the age: 25

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

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division
Operator Meaning of Operator

% remainder after division (modulo division)

Example 1: Arithmetic Operators


// Working of arithmetic operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, 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("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 operators + , - and * computes addition, subtraction, and multiplication


respectively as you might have expected.
In normal calculation, 9/4 = 2.25 . However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is also
an integer. The compiler neglects the term after the decimal point and shows
answer 2 instead of 2.25 .

The modulo operator % computes the remainder. When a=9 is divided by b=4 ,

the remainder is 1 . The % operator can only be used with integers.


Suppose a = 5.0 , b = 2.0 , c = 5 and d = 2. Then in C programming,

// Either one of the operands is a floating-point number

a/b = 2.5

a/d = 2.5

c/b = 2.5

// Both operands are integers

c/d = 2

C Increment and Decrement Operators


C programming has two operators increment ++ and decrement -- to change
the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the
value by 1. These two operators are unary operators, meaning they only
operate on a single operand.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);


printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

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 =

Operator Example Same as

= 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

Example 3: Assignment Operators


// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;

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

A relational operator checks the relationship between two operands. If the


relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.


Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1


Operator Meaning of Operator Example

<= Less than or equal to 5 <= 3 is evaluated to 0

Example 4: Relational Operators


// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);


printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a > b);
printf("%d > %d is %d \n", a, c, a > c);
printf("%d < %d is %d \n", a, b, a < b);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);

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

An expression containing logical operator returns either 0 or 1 depending


upon whether expression results true or false. Logical operators are
commonly used in decision making in C programming.
Operator Meaning Example

Logical AND. True only if all If c = 5 and d = 2 then, expression


&&
operands are true ((c==5) && (d>5)) equals to 0.

Logical OR. True only if If c = 5 and d = 2 then, expression


||
either one operand is true ((c==5) || (d>5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression !(c==5)


!
operand is 0 equals to 0.

Example 5: Logical Operators


// Working of logical operators

#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", 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

Explanation of logical operator program


 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c >

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

During computation, mathematical operations like: addition, subtraction,


multiplication, division, etc are converted to bit-level which makes processing
faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right


Visit bitwise operator in C to learn more.
Other Operators

Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

The sizeof operator

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

Size of int = 4 bytes


Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

Other operators such as ternary operator ?: , reference operator & ,


dereference operator * and member selection operator -> will be discussed in
later tutorials.

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?

The if statement evaluates the test expression inside the parenthesis () .

 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

To learn more about when test expression is evaluated to true (non-zero


value) and false (0), check relational and logical operators.

Example 1: if statement
// Program to display a number if it is negative

#include <stdio.h>
int main() {
int number;

printf("Enter an integer: ");


scanf("%d", &number);

// true if number is less than 0


if (number < 0) {
printf("You entered %d.\n", number);
}

printf("The if statement is easy.");

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
}

How if...else statement works?

If the test expression is evaluated to true,

 statements inside the body of if are executed.


 statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,

 statements inside the body of else are executed


 statements inside the body of if are skipped from execution.

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

// True if the remainder is 0


if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",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.

Syntax of if...else Ladder

if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}

Example 3: C if...else Ladder


// Program to relate two integers using =, > or < symbol

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

//checks if number1 is greater than number2.


else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
}

//checks if both test expressions are false


else {
printf("Result: %d < %d",number1, number2);
}

return 0;
}
Run Code

Output

Enter two integers: 12


23
Result: 12 < 23

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

if (number1 >= number2) {


if (number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
else {
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}

return 0;
}
Run Code

Enter two integers: 2 4

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.

C programming has three types of loops:

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:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}

How for loop works?

 The initialization statement is executed only once.

 Then, the test expression is evaluated. If the test expression is evaluated to


false, the for loop is terminated.
 However, if the test expression is evaluated to true, statements inside the
body of the for loop are executed, and the update expression is updated.
 Again the test expression is evaluated.

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

Working of for loop

Example 1: for loop


// Print numbers from 1 to 10
#include <stdio.h>

int main() {
int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}
Run Code

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.

Example 2: for loop


// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
int main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);
// for loop terminates when num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d", sum);

return 0;
}
Run Code

Output

Enter a positive integer: 10


Sum = 55

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.

C while and do...while Loop


In programming, loops are used to repeat a block of code until a specified
condition is met.
C programming has three types of loops.

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
}

How while loop works?

 The while loop evaluates the testExpression inside the parentheses () .

 If testExpression is true, statements inside the body of while loop are


executed. Then, testExpression is evaluated again.
 The process goes on until testExpression is evaluated to false.
 If testExpression is false, the loop terminates (ends).
To learn more about test expressions (when testExpression is evaluated
to true and false), check out relational and logical operators.

Flowchart of while loop

Working of while loop

Example 1: while loop


// Print numbers from 1 to 5

#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

Here, we have initialized i to 1.


1. When i = 1, the test expression i <= 5 is true. Hence, the body of
the while loop is executed. This prints 1 on the screen and the value of i is
increased to 2 .
2. Now, i = 2, the test expression i <= 5 is again true. The body of
the while loop is executed again. This prints 2 on the screen and the value
of i is increased to 3 .
3. This process goes on until i becomes 6. Then, the test expression i <= 5 will
be false and the loop terminates.

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

How do...while loop works?

 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

Working of do...while loop

Example 2: do...while loop


// Program to add numbers until the user enters zero

#include <stdio.h>
int main() {
double number, sum = 0;

// the body of the loop is executed at least once


do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}
Run Code
Output

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

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

So, if the first input is a non-zero number, that number is added to


the sum variable and the loop continues to the next iteration. This process is
repeated until the user enters 0 .
But if the first input is 0, there will be no second iteration of the loop
and sum becomes 0.0 .

Outside the loop, we print the value of sum .

C break and continue


C break
The break statement ends the loop immediately when it is encountered. Its
syntax is:
break;

The break statement is almost always used with if...else statement inside
the loop.

How break statement works?

Working
of break in C

Example 1: break statement


// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, the loop terminates
#include <stdio.h>

int main() {
int i;
double number, sum = 0.0;

for (i = 1; i <= 10; ++i) {


printf("Enter n%d: ", i);
scanf("%lf", &number);

// if the user enters a negative number, break the loop


if (number < 0.0) {
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf", sum);

return 0;
}
Run Code

Output

Enter n1: 2.4


Enter n2: 4.5
Enter n3: 3.4
Enter n4: -3
Sum = 10.30

This program calculates the sum of a maximum of 10 numbers. Why a


maximum of 10 numbers? It's because if the user enters a negative number,
the break statement is executed. This will end the for loop, and the sum is
displayed.
In C, break is also used with the switch statement. This will be discussed in the
next tutorial.
C continue
The continue statement skips the current iteration of the loop and continues
with the next iteration. Its syntax is:

continue;

The continue statement is almost always used with the if...else statement.

How continue statement works?

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;

for (i = 1; i <= 10; ++i) {


printf("Enter a n%d: ", i);
scanf("%lf", &number);

if (number < 0.0) {


continue;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf", sum);

return 0;
}
Run Code

Output

Enter n1: 1.1


Enter n2: 2.2
Enter n3: 5.5
Enter n4: 4.4
Enter n5: -3.4
Enter n6: -45.5
Enter n7: 34.5
Enter n8: -4.2
Enter n9: -1000
Enter n10: 12
Sum = 59.70

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
}

How does the switch statement work?


The expression is evaluated once and compared with the values of
each case label.
 If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to constant2 ,

statements after case constant2: are executed until break is encountered.


 If there is no match, the default statements are executed.

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;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&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;

// operator doesn't match any case constant +, -, *, /


default:
printf("Error! operator is not correct");
}

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

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

Finally, the break statement terminates the switch statement.

C goto Statement
The goto statement allows us to transfer control of the program to the
specified label .

Syntax of goto Statement

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

Example: goto Statement


// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.

#include <stdio.h>

int main() {

const int maxInput = 100;


int i;
double number, average, sum = 0.0;

for (i = 1; i <= maxInput; ++i) {


printf("%d. Enter a number: ", i);
scanf("%lf", &number);

// go to jump if the user enters a negative number


if (number < 0.0) {
goto jump;
}
sum += number;
}

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

Reasons to avoid goto

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.

Should you use goto?

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:

 create a circle function

 create a color function

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:

 Standard library functions


 User-defined functions

Standard library functions


The standard library functions are built-in functions in C programming.

These functions are defined in header files. For example,

 The printf() is a standard library function to send formatted output to the


screen (display output on the screen). This function is defined in
the stdio.h header file.
Hence, to use the printf() function, we need to include the stdio.h header file
using #include <stdio.h> .

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

... .. ...

... .. ...

The execution of a C program begins from the main() function.


When the compiler encounters functionName(); , control of the program jumps
to

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

Note, function names are identifiers and should be unique.

This is just an overview of user-defined functions. Visit these pages to learn


more on:
 User-defined Function in C programming
 Types of user-defined Functions

Advantages of user-defined function


1. The program will be easier to understand, maintain and debug.

2. Reusable codes that can be used in other programs

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

Example: User-defined function


Here is an example to add two integers. To perform this task, we have created
an user-defined addNumbers() .

#include <stdio.h>
int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call


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

return 0;
}

int addNumbers(int a, int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

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

returnType functionName(type1 argument1, type2 argument2, ...);

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

2. return type of the function is int

3. two arguments of type int are passed to the function


The function prototype is not needed if the user-defined function is defined
before the main() function.

Calling a function
Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

functionName(argument1, argument2, ...);

In the above example, the function call is made using addNumbers(n1,

n2); statement inside the main() function.


Function definition
Function definition contains the block of code to perform a specific task. In our
example, adding two numbers and returning it.

Syntax of function definition

returnType functionName(type1 argument1, type2 argument2, ...)

//body of the function

When a function is called, the control of the program is transferred to the


function definition. And, the compiler starts executing the codes inside the
body of a function.

Passing arguments to a function


In programming, argument refers to the variable passed to the function. In the
above example, two variables n1 and n2 are passed during the function call.
The parameters a and b accepts the passed arguments in the function
definition. These arguments are called formal parameters of the function.
Passing Argument to Function

The type of arguments passed to a function and the formal parameters must
match, otherwise, the compiler will throw an error.

If n1 is of char type, a also should be of char type. If n2 is of float type,


variable b also should be of float type.
A function can also be called without passing an argument.
Return Statement
The return statement terminates the execution of a function and returns a
value to the calling function. The program control is transferred to the calling
function after the return statement.

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 Statement of Function


Syntax of return statement

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.

Types of User-defined Functions in


C Programming
These 4 programs below check whether the integer entered by the user is a
prime number or not.

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.

Example 1: No Argument Passed and No Return Value


#include <stdio.h>

void checkPrimeNumber();

int main() {
checkPrimeNumber(); // argument is not passed
return 0;
}

// return type is void meaning doesn't return any value


void checkPrimeNumber() {
int n, i, flag = 0;

printf("Enter a positive integer: ");


scanf("%d",&n);

// 0 and 1 are not prime numbers


if (n == 0 || n == 1)
flag = 1;

for(i = 2; i <= n/2; ++i) {


if(n%i == 0) {
flag = 1;
break;
}
}

if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
Run Code

\Enter a positive integer: 3 4

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.

Example 2: No Arguments Passed But Returns a


Value
#include <stdio.h>
int getInteger();

int main() {

int n, i, flag = 0;

// no argument is passed
n = getInteger();

// 0 and 1 are not prime numbers


if (n == 0 || n == 1)
flag = 1;

for(i = 2; i <= n/2; ++i) {


if(n%i == 0){
flag = 1;
break;
}
}

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;

printf("Enter a positive integer: ");


scanf("%d",&n);

return n;
}
Run Code

Enter a positive integer: 5

5 is a prime number.

The empty parentheses in the n = getInteger(); statement indicates that no


argument is passed to the function. And, the value returned from the function
is assigned to n .
Here, the getInteger() function takes input from the user and returns it. The
code to check whether a number is prime or not is inside the main() function.

Example 3: Argument Passed But No Return Value


#include <stdio.h>
void checkPrimeAndDisplay(int n);

int main() {

int n;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the function


checkPrimeAndDisplay(n);
return 0;
}

// return type is void meaning doesn't return any value


void checkPrimeAndDisplay(int n) {
int i, flag = 0;

// 0 and 1 are not prime numbers


if (n == 0 || n == 1)
flag = 1;

for(i = 2; i <= n/2; ++i) {


if(n%i == 0){
flag = 1;
break;
}
}

if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
Run Code

Enter a positive integer: 0

0 is not a prime number.

The integer value entered by the user is passed to


the checkPrimeAndDisplay() function.
Here, the checkPrimeAndDisplay() function checks whether the argument passed
is a prime number or not and displays the appropriate message.

Example 4: Argument Passed and Returns a Value


#include <stdio.h>
int checkPrimeNumber(int n);

int main() {

int n, flag;

printf("Enter a positive integer: ");


scanf("%d",&n);

// n is passed to the checkPrimeNumber() function


// the returned value is assigned to the flag variable
flag = checkPrimeNumber(n);

if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);

return 0;
}

// int is returned from the function


int checkPrimeNumber(int n) {

// 0 and 1 are not prime numbers


if (n == 0 || n == 1)
return 1;

int i;

for(i=2; i <= n/2; ++i) {


if(n%i == 0)
return 1;
}

return 0;
}
Run Code

Enter a positive integer: 1

1 is not a prime number


The input from the user is passed to the checkPrimeNumber() function.
The checkPrimeNumber() function checks whether the passed argument is prime
or not.
If the passed argument is a prime number, the function returns 0. If the
passed argument is a non-prime number, the function returns 1. The return
value is assigned to the flag variable.
Depending on whether flag is 0 or 1, an appropriate message is printed from
the main() function.

Which approach is better?


Well, it depends on the problem you are trying to solve. In this case, passing
an argument and returning a value from the function (example 4) is better.

A function should perform a specific task. The checkPrimeNumber() function


doesn't take input from the user nor it displays the appropriate message. It
only checks whether a number is prime or not.

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

The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if...else statement (or similar approach) can be


used where one branch makes the recursive call, and other doesn't.

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);

int main() {
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}

int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}

Output

Enter a positive integer:3


sum = 6

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

Recursion makes program elegant. However, if performance is vital, use loops


instead as recursion is usually much slower.

That being said, recursion is an important concept. It is frequently used in data


structure and algorithms. For example, it is common to use recursion in
problems such as tree traversal.

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.

There are 4 types of storage class:

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

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


printf("C programming");
}

// Error: i is not declared at this point


printf("%d", i);
return 0;
}
Run Code

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

In the above example, n1 is local to main() and n2 is local 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.

Example 1: Global Variable


#include <stdio.h>
void display();

int n = 5; // global variable

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.

Example 2: Static Variable


#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}
Run Code

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

How to declare an array?

dataType arrayName[arraySize];
For example,

float mark[5];

Here, we declared an array, mark , of floating-point type. And its size is 5.


Meaning, it can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed
once it is declared.

Access Array Elements


You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0] ,

the second element is mark[1] and so on.

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]

 Suppose the starting address of mark[0] is 2120d. Then, the address of


the mark[1] will be 2124d. Similarly, the address of mark[2] will be 2128d and
so on.
This is because the size of a float is 4 bytes.

How to initialize an array?


It is possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

You can also initialize an array like this.

int mark[] = {19, 10, 8, 17, 9};

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

Change Value of Array elements

int mark[5] = {19, 10, 8, 17, 9}

// make the value of the third element to -1


mark[2] = -1;

// make the value of the fifth element to 0


mark[4] = 0;

Input and Output Array Elements


Here's how you can take input from the user and store it in an array element.

// take input and store it in the 3rd element


scanf("%d", &mark[2]);

// take input and store it in the ith element


scanf("%d", &mark[i-1]);

Here's how you can print an individual element of an array.

// print the first element of the array


printf("%d", mark[0]);

// print the third element of the array


printf("%d", mark[2]);

// print ith element of the array


printf("%d", mark[i-1]);

Example 1: Array Input/Output


// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array

#include <stdio.h>

int main() {

int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}
Run Code
Output

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.

Example 2: Calculate Average


// Program to find the average of n numbers using arrays

#include <stdio.h>

int main() {

int marks[10], i, n, sum = 0;


double average;

printf("Enter number of elements: ");


scanf("%d", &n);

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


printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum variable
sum += marks[i];
}

// explicitly convert sum to double


// then calculate average
average = (double) sum / n;

printf("Average = %.2lf", average);

return 0;
}
Run Code

Output

Enter number of elements: 5


Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39.60

Here, we have computed the average of n numbers entered by the user.

Access elements out of its bound!

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can access the array elements from testArray[0] to testArray[9] .


Now let's say if you try to access testArray[12] . The element is not available.
This may cause unexpected output (undefined behavior). Sometimes you
might get an error and some other time your program may run correctly.
Hence, you should never access elements of an array outside of its bound.

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

Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];

Here, the array y can hold 24 elements.

Initializing a multidimensional array


Here is how you can initialize two-dimensional and three-dimensional arrays:

Initialization of a 2d array

// Different ways to initialize two-dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};

int c[][3] = {{1, 3, 0}, {-1, 5, 9}};


int c[2][3] = {1, 3, 0, -1, 5, 9};

Initialization of a 3d array

You can initialize a three-dimensional array in a similar way to a two-


dimensional array. Here's an example,

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

Example 1: Two-dimensional array to store and print values


// C program to store temperature of two cities of a week and display it.
#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main()
{
int temperature[CITY][WEEK];

// Using nested loop to store values in a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");

// Using nested loop to display vlues of a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;
}
Run Code

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

Example 2: Sum of two matrices


// C program to find the sum of two matrices of order 2*2

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
// adding corresponding elements of two arrays
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

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


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}
Run Code

Output

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

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("Enter 12 values: \n");

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


{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}

// Printing values with the proper index.

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

Pass arrays to a function in C


In C programming, you can pass an entire array to functions. Before we learn
that, let's see how you can pass individual elements of an array to functions.
Pass Individual Array Elements
Passing array elements to a function is similar to passing variables to a
function.

Example 1: Pass Individual Array Elements


#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}

int main() {
int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}
Run Code

Output

Here, we have passed array parameters to the display() function in the same
way we pass variables to a function.

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
We can see this in the function definition, where the function parameters are
individual variables:

void display(int age1, int age2) {


// code
}

Example 2: Pass Arrays to Functions


// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]);

int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()


result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}

float calculateSum(float num[]) {


float sum = 0.0;

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


sum += num[i];
}

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

However, notice the use of [] in the function definition.

float calculateSum(float num[]) {


... ..
}

This informs the compiler that you are passing a one-dimensional array to the
function.

Pass Multidimensional Arrays to a Function


To pass multidimensional arrays to a function, only the name of the array is
passed to the function (similar to one-dimensional arrays).

Example 3: Pass two-dimensional arrays


#include <stdio.h>
void displayNumbers(int num[2][2]);

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

// pass multi-dimensional array to a function


displayNumbers(num);

return 0;
}

void displayNumbers(int num[2][2]) {


printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
Run Code

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

This signifies that the function takes a two-dimensional array as an argument.


We can also pass arrays with more than 2 dimensions as a function
argument.
When passing two-dimensional arrays, it is not mandatory to specify the
number of rows in the array. However, the number of columns should always
be specified.

For example,

void displayNumbers(int num[][2]) {


// code
}

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

// Notice the use of & before var


printf("address of var: %p", &var);
return 0;
}

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

Here is how we can declare pointers.

int* p;

Here, we have declared a pointer p of int type.


You can also declare pointers in these ways.

int *p1;
int * p2;

Let's take another example of declaring pointers.

int* p1, p2;

Here, we have declared a pointer p1 and a normal variable p2 .

Assigning addresses to Pointers

Let's take an example.

int* pc, c;
c = 5;
pc = &c;

Here, 5 is assigned to the c variable. And, the address of c is assigned to


the pc pointer.
Get Value of Thing Pointed by Pointers

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.

Changing Value Pointed by Pointers

Let's take an example.

int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1

We have assigned the address of c to the pc pointer.


Then, we changed the value of c to 1. Since pc and the address of c is the
same, *pc gives us 1.
Let's take another example.

int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1

We have assigned the address of c to the pc pointer.


Then, we changed *pc to 1 using *pc = 1; . Since pc and the address of c is
the same, c will be equal to 1.
Let's take one more example.

int* pc, c, d;
c = 5;
d = -15;

pc = &c; printf("%d", *pc); // Output: 5


pc = &d; printf("%d", *pc); // Ouptut: -15

Initially, the address of c is assigned to the pc pointer using pc = &c; .

Since c is 5, *pc gives us 5.


Then, the address of d is assigned to the pc pointer using pc = &d; . Since d is -
15, *pc gives us -15.

Example: Working of Pointers

Let's take a working example.


#include <stdio.h>
int main()
{
int* pc, c;

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 pointer pc: 2686784


Content of pointer pc: 22

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Value of c: 2
Explanation of the program
1. int* pc, c;

Here, a pointer pc and a normal variable c , both of type int , is created.


Since pc and c are not initialized at initially, pointer pc points to either no
address or a random address. And, variable c has an address but contains
random garbage value.

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;

This assigns the address of variable c to the pointer pc .

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.

Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c . Then,

int c, *pc;

// pc is address but c is not


pc = c; // Error

// &c is address but *pc is not


*pc = &c; // Error

// both &c and pc are addresses


pc = &c; // Not an error

// both c and *pc are values


*pc = c; // Not an error

Here's an example of pointer syntax beginners often find confusing.

#include <stdio.h>
int main() {
int c = 5;
int *p = &c;

printf("%d", *p); // 5
return 0;
}

Why didn't we get an error when using int *p = &c; ?

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;

Relationship Between Arrays and


Pointers
Before you learn about the relationship between arrays and pointers, be sure
to check these two topics:

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

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


printf("&x[%d] = %p\n", i, &x[i]);
}

printf("Address of array x: %p", x);

return 0;
}

Output

&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448

There is a difference of 4 bytes between two consecutive elements of array x .


It is because the size of int is 4 bytes (on our compiler).
Notice that, the address of &x[0] and x is the same. It's because the variable
name x points to the first element of the array.

Relation between Arrays and Pointers

From the above example, it is clear that &x[0] is equivalent to x . And, x[0] is
equivalent to *x .
Similarly,

 &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1) .

 &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2) .

 ...

 Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i) .

Example 1: Pointers and Arrays

#include <stdio.h>
int main() {

int i, x[6], sum = 0;

printf("Enter 6 numbers: ");

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


// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);

// Equivalent to sum += x[i]


sum += *(x+i);
}

printf("Sum = %d", sum);

return 0;
}

When you run the program, the output will be:

Enter 6 numbers: 2
3
4
4
12
4
Sum = 29

Here, we have declared an array x of 6 elements. To access elements of the


array, we have used pointers.

In most contexts, array names decay to pointers. In simple words, array


names are converted to pointers. That's the reason why you can use pointers
to access elements of arrays. However, you should remember that pointers
and arrays are not the same.
There are a few cases where array names don't decay to pointers. To learn
more, visit: When does array name doesn't decay into a pointer?

Example 2: Arrays and Pointers

#include <stdio.h>
int main() {

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


int* ptr;

// ptr is assigned the address of the third element


ptr = &x[2];

printf("*ptr = %d \n", *ptr); // 3


printf("*(ptr+1) = %d \n", *(ptr+1)); // 4
printf("*(ptr-1) = %d", *(ptr-1)); // 2

return 0;
}

When you run the program, the output will be:

*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2

In this example, &x[2] , the address of the third element, is assigned to


the ptr pointer. Hence, 3 was displayed when we printed *ptr .

And, printing *(ptr+1) gives us the fourth element. Similarly, printing *(ptr-

1) gives us the second element.

C Pass Addresses and Pointers


In C programming, it is also possible to pass addresses as arguments to
functions.

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:

Example: Pass Addresses to Functions


#include <stdio.h>
void swap(int *n1, int *n2);

int main()
{
int num1 = 5, num2 = 10;

// address of num1 and num2 is passed


swap( &num1, &num2);

printf("num1 = %d\n", num1);


printf("num2 = %d", num2);
return 0;
}

void swap(int* n1, int* n2)


{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
Run Code

When you run the program, the output will be:

num1 = 10
num2 = 5

The address of num1 and num2 are passed to the swap() function
using swap(&num1, &num2); .

Pointers n1 and n2 accept these arguments in the function definition.

void swap(int* n1, int* n2) {


... ..
}

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 .

Example 2: Passing Pointers to Functions


#include <stdio.h>

void addOne(int* ptr) {


(*ptr)++; // adding 1 to *ptr
}

int main()
{
int* p, i = 10;
p = &i;
addOne(p);

printf("%d", *p); // 11
return 0;
}
Run Code

Here, the value stored at p , *p , is 10 initially.


We then passed the pointer p to the addOne() function. The ptr pointer gets
this address in the addOne() function.
Inside the function, we increased the value stored at ptr by 1 using (*ptr)++; .

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.

To allocate memory dynamically, library functions


are malloc() , calloc() , realloc() and free() are used. These functions are
defined in the <stdlib.h> header file.

C malloc()
The name "malloc" stands for memory allocation.

The malloc() function reserves a block of memory of the specified number of


bytes. And, it returns a pointer of void which can be casted into pointers of any
form.
Syntax of malloc()

ptr = (castType*) malloc(size);

Example

ptr = (float*) malloc(100 * sizeof(float));

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

ptr = (castType*)calloc(n, size);

Example:
ptr = (float*) calloc(25, sizeof(float));

The above statement allocates contiguous space in memory for 25 elements


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

Example 1: malloc() and free()


// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &n);

ptr = (int*) malloc(n * sizeof(int));

// if memory cannot be allocated


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);

// deallocating the memory


free(ptr);

return 0;
}
Run Code

Output

Enter number of elements: 3


Enter elements: 100
20
36
Sum = 156

Here, we have dynamically allocated the memory for n number of int .


Example 2: calloc() and free()
// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);

ptr = (int*) calloc(n, sizeof(int));


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}
Run Code

Output

Enter number of elements: 3


Enter elements: 100
20
36
Sum = 156
C realloc()
If the dynamically allocated memory is insufficient or more than required, you
can change the size of previously allocated memory using
the realloc() function.

Syntax of realloc()

ptr = realloc(ptr, x);

Here, ptr is reallocated with a new size x .

Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Addresses of previously allocated memory:\n");


for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);

printf("\nEnter the new size: ");


scanf("%d", &n2);

// rellocating the memory


ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory:\n");


for(i = 0; i < n2; ++i)
printf("%pc\n", ptr + i);

free(ptr);

return 0;
}
Run Code

Output

Enter size: 2
Addresses of previously allocated memory:
26855472
26855476

Enter the new size: 4


Addresses of newly allocated memory:
26855472
26855476
26855480
26855484

C Programming Strings
In C programming, a string is a sequence of characters terminated with a null
character \0 . For example:

char c[] = "c string";

When the compiler encounters a sequence of characters enclosed in the


double quotation marks, it appends a null character \0 at the end by default.
Memory Diagram

How to declare a string?


Here's how you can declare strings:

char s[5];

String Declaration in C

Here, we have declared a string of 5 characters.

How to initialize strings?


You can initialize strings in a number of ways.

char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};


String Initialization in C

Let's take another example:

char c[5] = "abcde";

Here, we are trying to assign 6 characters (the last character is '\0' ) to


a char array having 5 characters. This is bad and you should never do this.

Assigning Values to Strings


Arrays and strings are second-class citizens in C; they do not support the
assignment operator once it is declared. For example,

char c[100];
c = "C programming"; // Error! array type is not assignable.

Note: Use the strcpy() function to copy the string instead.

Read String from the user


You can use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it
encounters whitespace (space, newline, tab, etc.).

Example 1: scanf() to read a string

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Output

Enter name: Dennis Ritchie


Your name is Dennis.

Even though Dennis Ritchie was entered in the above program,


only "Dennis" was stored in the name string. It's because there was a space
after Dennis .

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.

Example 2: fgets() and puts()

#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

Enter name: Tom Hanks


Name: Tom Hanks

Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string

The sizeof(name) results to 30. Hence, we can take a maximum of 30


characters as input which is the size of the name string.
To print the string, we have used puts(name); .
Note: The gets() function can also be to take input from the user. However, it
is removed from the C standard.

It's because gets() allows you to input any length of characters. Hence, there
might be a buffer overflow.

Passing Strings to Functions


Strings can be passed to a function in a similar way as arrays. Learn more
about passing arrays to a function.

Example 3: Passing string to a Function

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

Strings and Pointers


Similar like arrays, string names are "decayed" to pointers. Hence, you can
use pointers to manipulate elements of the string. We recommended you to
check C Arrays and Pointers before you check this example.

Example 4: Strings and Pointers

#include <stdio.h>

int main(void) {
char name[] = "Harry Potter";

printf("%c", *name); // Output: H


printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o

char *namePtr;

namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}

Commonly Used String Functions

 strlen() - calculates the length of a string


 strcpy() - copies a string to another
 strcmp() - compares two strings
 strcat() - concatenates two strings

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

Few commonly used string handling functions are discussed below:

Function Work of Function

strlen() computes string's length


Function Work of Function

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings

strlwr() converts string to lowercase

strupr() converts string to uppercase

Strings handling functions are defined under "string.h" header file.

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

Another way of creating a struct variable is:

struct Person {
// code
} person1, person2, p[20];

In both cases,

 person1 and person2 are struct Person variables


 p[] is a struct Person array of size 20.

Access Members of a Structure


There are two types of operators used for accessing members of a structure.

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>

// create struct with person1 variable


struct Person {
char name[50];
int citNo;
float salary;
} person1;

int main() {

// assign value to name of person1


strcpy(person1.name, "George Orwell");

// assign values to other person1 variables


person1.citNo = 1984;
person1. salary = 2500;

// print struct variables


printf("Name: %s\n", person1.name);
printf("Citizenship No.: %d\n", person1.citNo);
printf("Salary: %.2f", person1.salary);

return 0;
}
Run Code

Output

Name: George Orwell


Citizenship No.: 1984
Salary: 2500.00

In this program, we have created a struct named Person . We have also


created a variable of Person named person1 .

In main() , we have assigned values to the variables defined in Person for


the person1 object.

strcpy(person1.name, "George Orwell");


person1.citNo = 1984;
person1. salary = 2500;

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

We can use typedef to write an equivalent code with a simplified syntax:

typedef struct Distance {


int feet;
float inch;
} distances;

int main() {
distances d1, d2;
}

Example 2: C typedef
#include <stdio.h>
#include <string.h>

// struct with typedef person


typedef struct Person {
char name[50];
int citNo;
float salary;
} person;

int main() {

// create Person variable


person p1;

// assign value to name of p1


strcpy(p1.name, "George Orwell");

// assign values to other p1 variables


p1.citNo = 1984;
p1. salary = 2500;

// print struct variables


printf("Name: %s\n", p1.name);
printf("Citizenship No.: %d\n", p1.citNo);
printf("Salary: %.2f", p1.salary);

return 0;
}
Run Code

Output

Name: George Orwell


Citizenship No.: 1984
Salary: 2500.00

Here, we have used typedef with the Person structure to create an alias person .

// struct with typedef person


typedef struct Person {
// code
} person;

Now, we can simply declare a Person variable using the person alias:

// equivalent to struct Person p1


person p1;

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;

Example 3: C Nested Structures


#include <stdio.h>

struct complex {
int imag;
float real;
};

struct number {
struct complex comp;
int integer;
} num1;

int main() {

// initialize complex variables


num1.comp.imag = 11;
num1.comp.real = 5.25;
// initialize number variable
num1.integer = 6;

// print struct variables


printf("Imaginary Part: %d\n", num1.comp.imag);
printf("Real Part: %.2f\n", num1.comp.real);
printf("Integer: %d", num1.integer);

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

Here, ptr is a pointer to struct .


Example: Access members using Pointer
To access members of a structure using pointers, we use the -> operator.
#include <stdio.h>
struct person
{
int age;
float weight;
};

int main()
{
struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);

return 0;
}
Run Code

In this example, the address of person1 is stored in the personPtr pointer


using personPtr = &person1; .

Now, you can access the members of person1 using the personPtr pointer.
By the way,

 personPtr->age is equivalent to (*personPtr).age

 personPtr->weight is equivalent to (*personPtr).weight


Dynamic memory allocation of structs
Before you proceed this section, we recommend you to check C dynamic
memory allocation.
Sometimes, the number of struct variables you declared may be insufficient.
You may need to allocate memory during run-time. Here's how you can
achieve this in C programming.

Example: Dynamic memory allocation of structs


#include <stdio.h>
#include <stdlib.h>
struct person {
int age;
float weight;
char name[30];
};

int main()
{
struct person *ptr;
int i, n;

printf("Enter the number of persons: ");


scanf("%d", &n);

// allocating memory for n numbers of struct person


ptr = (struct person*) malloc(n * sizeof(struct person));

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


{
printf("Enter first name and age respectively: ");

// To access members of 1st struct person,


// ptr->name and ptr->age is used
// To access members of 2nd struct person,
// (ptr+1)->name and (ptr+1)->age is used
scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);
}

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

When you run the program, the output will be:

Enter the number of persons: 2


Enter first name and age respectively: Harry 24
Enter first name and age respectively: Gary 32
Displaying Information:
Name: Harry Age: 24
Name: Gary Age: 32

In the above example, n number of struct variables are created where n is


entered by the user.
To allocate the memory for n number of struct person , we used,

ptr = (struct person*) malloc(n * sizeof(struct person));

Then, we used the ptr pointer to access elements of person .

C Structure and Function


Similar to variables of built-in types, you can also pass structure variables to a
function.
Passing structs to functions
We recommended you to learn these tutorials before you learn how to pass
structs to functions.

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

printf("Enter name: ");

// read string input from the user until \n is entered


// \n is discarded
scanf("%[^\n]%*c", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

display(s1); // passing struct as an argument

return 0;
}

void display(struct student s) {


printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}
Run Code

Output

Enter name: Bond


Enter age: 13

Displaying information
Name: Bond
Age: 13

Here, a struct variable s1 of type struct student is created. The variable is


passed to the display() function using display(s1); statement.

Return struct from a function


Here's how you can return structure from a function:

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

printf("Enter name: ");


scanf ("%[^\n]%*c", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

return s1;
}
Run Code

Here, the getInformation() function is called using s =

getInformation(); statement. The function returns a structure of type struct

student . The returned structure is displayed from the main() function.


Notice that, the return type of getInformation() is also struct student .

Passing struct by reference


You can also pass structs by reference (in a similar way like you pass
variables of built-in type by reference). We suggest you to read pass by
reference tutorial before you proceed.
During pass by reference, the memory addresses of struct variables
are passed to the function.

#include <stdio.h>
typedef struct Complex
{
float real;
float imag;
} complex;

void addNumbers(complex c1, complex c2, complex *result);

int main()
{
complex c1, c2, result;

printf("For first number,\n");


printf("Enter real part: ");
scanf("%f", &c1.real);
printf("Enter imaginary part: ");
scanf("%f", &c1.imag);

printf("For second number, \n");


printf("Enter real part: ");
scanf("%f", &c2.real);
printf("Enter imaginary part: ");
scanf("%f", &c2.imag);

addNumbers(c1, c2, &result);


printf("\nresult.real = %.1f\n", result.real);
printf("result.imag = %.1f", result.imag);

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

For first number,


Enter real part: 1.1
Enter imaginary part: -2.4
For second number,
Enter real part: 3.4
Enter imaginary part: -3.2

result.real = 4.5
result.imag = -5.6

In the above program, three structure variables c1 , c2 and the address


of result is passed to the addNumbers() function. Here, result is passed by
reference.
When the result variable inside the addNumbers() is altered, the result variable
inside the main() function is also altered accordingly.

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.

How to define a union?


We use the union keyword to define unions. Here's an example:

union car
{
char name[50];
int price;
};

The above code defines a derived type union car .


Create union variables
When a union is defined, it creates a user-defined type. However, no memory
is allocated. To allocate memory for a given union type and work with it, we
need to create variables.

Here's how we create union variables.

union car
{
char name[50];
int price;
};

int main()
{
union car car1, car2, *car3;
return 0;
}

Another way of creating union variables is:

union car
{
char name[50];
int price;
} car1, car2, *car3;

In both cases, union variables car1 , car2 , and a union pointer car3 of union

car type are created.


Access members of a union

We use the . operator to access members of a union. And to access pointer


variables, we use the -> operator.
In the above example,

 To access price for car1 , car1.price is used.


 To access price using car3 , either (*car3).price or car3->price can be used.

Difference between unions and structures


Let's take an example to demonstrate the difference between unions and
structures:

#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

Why this difference in the size of union and structure variables?


Here, the size of sJob is 40 bytes because
 the size of name[32] is 32 bytes
 the size of salary is 4 bytes
 the size of workerNo is 4 bytes
However, the size of uJob is 32 bytes. It's because the size of a union variable
will always be the size of its largest element. In the above example, the size of
its largest element, ( name[32] ), is 32 bytes.
With a union, all members share the same memory.

Example: Accessing Union Members

#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;

int main() {
j.salary = 12.3;

// when j.workerNo is assigned a value,


// j.salary will no longer hold 12.3
j.workerNo = 100;

printf("Salary = %.1f\n", j.salary);


printf("Number of workers = %d", j.workerNo);
return 0;
}

Output

Salary = 0.0
Number of workers = 100

C File Handling
A file is a container in computer storage devices used for storing data.

Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.

 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

Binary files are mostly the .bin files in your computer.


Instead of storing data in plain text, they store it in the binary form (0's and
1's).
They can hold a higher amount of data, are not readable easily, and provides
better security than text files.

File Operations
In C, you can perform four major operations on files, either text or binary:

1. Creating a new file

2. Opening an existing file

3. Closing a file

4. Reading from and writing information to a file

Working with files


When working with files, you need to declare a pointer of type file. This
declaration is needed for communication between the file and the program.

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

If the file does not exist,


r Open for reading.
fopen() returns NULL.
Opening Modes in Standard I/O

Mod
Meaning of Mode During Inexistence of file
e

If the file does not exist,


rb Open for reading in binary mode.
fopen() returns NULL.

If the file exists, its contents are


overwritten.
w Open for writing.
If the file does not exist, it will be
created.

If the file exists, its contents are


overwritten.
wb Open for writing in binary mode.
If the file does not exist, it will be
created.

Open for append. If the file does not exist, it will be


a
Data is added to the end of the file. created.

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.

If the file does not exist,


r+ Open for both reading and writing.
fopen() returns NULL.

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.

If the file exists, its contents are


Open for both reading and writing overwritten.
wb+
in binary mode. If the file does not exist, it will be
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.

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.


Reading and writing to a text file
For reading and writing to a text file, we use the
functions fprintf() and fscanf().

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.

Example 1: Write to a text file

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

// use appropriate location if you are using MacOS or Linux


fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);

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.

Example 2: Read from a text file

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);
return 0;
}

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.

Reading and writing to a binary file


Functions fread() and fwrite() are used for reading from and writing to a file
on the disk respectively in case of binary files.

Writing to a binary file

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

2. size of data to be written in the disk

3. number of such type of data

4. pointer to the file where you want to write.


fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

#include <stdio.h>
#include <stdlib.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

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


{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}

In this program, we create a new file program.bin in the C drive.


We declare a structure threeNum with three numbers - n1, n2 and n3 , and define
it in the main function as num.
Now, inside the for loop, we store the value into the file using fwrite() .

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.

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as


above.

fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: Read from a binary file using fread()

#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

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


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

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


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(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 .

You'll get the same records you inserted in Example 3.


Getting data using fseek()
If you have many records inside a file and need to access a record at a
specific position, you need to loop through all the records before it to get the
record.

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

fseek(FILE * stream, long int offset, int whence);

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.

Different whence in fseek()

Whence Meaning

SEEK_SET Starts the offset from the beginning of the file.

SEEK_END Starts the offset from the end of the file.

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;

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


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

// Moves the cursor to the end of the file


fseek(fptr, -sizeof(struct threeNum), SEEK_END);

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


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
}
fclose(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;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

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


{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}

2. C program to read name and marks of n number of students from and


store them in a file. If the file previously exits, add the information to the
file.

#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &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);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}

3. C program to write all the members of an array of structures to a file


using fwrite(). Read the array from the file and display on the screen.

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

printf("Enter height: ");


scanf("%d", &stud1[i].height);
}
fwrite(stud1, sizeof(stud1), 1, fptr);
fclose(fptr);

fptr = fopen("file.txt", "rb");


fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
}
fclose(fptr);
}

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.

enum flag {const1, const2, ..., constN};

By default, const1 is 0, const2 is 1 and so on. You can change default values of
enum elements during declaration (if necessary).

// Changing default values of enum constants

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.

enum boolean {false, true};

enum boolean check; // declaring an enum variable

Here, a variable check of the type enum boolean is created.


You can also declare enum variables like this.

enum boolean {false, true} check;

Here, the value of false is equal to 0 and the value of true is equal to 1.

Example: Enumeration Type

#include <stdio.h>

enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}

Output

Day 4

Why enums are used?


An enum variable can take only one value. Here is an example to
demonstrate it,

#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

Size of enum variable = 4 bytes


Here, we are getting 4 because the size of int is 4 bytes.
This makes enum a good choice to work with flags.

How to use enums for flags?

Let us take an example,

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.

Also, you can add flags according to your requirements.

if (myDesign & ITALICS) {

// code for italics

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.

C Preprocessor and Macros

Working of C Preprocessor

The C preprocessor is a macro preprocessor (allows you to define macros)


that transforms your program before it is compiled. These transformations can
be the inclusion of header files, macro expansions, etc.

All preprocessing directives begin with a # symbol. For example,

#define PI 3.14

Some of the common uses of C preprocessors are:


Including Header Files: #include
The #include preprocessor is used to include header files to C programs. For
example,

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

Visit this page to learn more about using header files.

Macros using #define


A macro is a fragment of code that is given a name. You can define a macro
in C using the #define preprocessor directive.
Here's an example.

#define c 299792458 // speed of light


Here, when we use c in our program, it is replaced with 299792458 .

Example 1: #define preprocessor

#include <stdio.h>
#define PI 3.1415

int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);

// Notice, the use of PI


area = PI*radius*radius;

printf("Area=%.2f",area);
return 0;
}

Function like Macros


You can also define macros that work in a similar way as a function call. This
is known as function-like macros. For example,

#define circleArea(r) (3.1415*(r)*(r))


Every time the program encounters circleArea(argument) , it is replaced
by (3.1415*(argument)*(argument)) .

Suppose, we passed 5 as an argument then, it expands as below:

circleArea(5) expands to (3.1415*5*5)

Example 2: Using #define preprocessor

#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)

int main() {
float radius, area;

printf("Enter the radius: ");


scanf("%f", &radius);
area = circleArea(radius);
printf("Area = %.2f", 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.

It's similar to a if statement with one major difference.


The if statement is tested during the execution time to check whether a block
of code should be executed or not whereas, the conditionals are used to
include (or skip) a block of code in your program before execution.

Uses of Conditional

 use different code depending on the machine, operating system

 compile the same source file in two different programs

 to exclude certain code from the program but to keep it as a reference for
future purposes

How to use conditional?

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, #elif and #else Directive

#if expression
// conditional codes
#endif

Here, expression is an expression of integer type (can be integers, characters,


arithmetic expression, macros, and so on).
The conditional codes are included in the program only if the expression is
evaluated to a non-zero value.
The optional #else directive can be used with #if directive.

#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

The special operator #defined is used to test whether a certain macro is


defined or not. It's often used with #if directive.

#if defined BUFFER_SIZE && BUFFER_SIZE >= 2048


// codes

Predefined Macros
Here are some predefined macros in C programming.

Macro Value

__DATE__ A string containing the current date.

__FILE__ A string containing the file name.


Macro Value

__LINE__ An integer representing the current line number.

__STDC__ If follows ANSI standard C, then the value is a nonzero integer.

__TIME__ A string containing the current time.

Example 3: Get current time using __TIME__

The following program outputs the current time using __TIME__ macro.

#include <stdio.h>
int main()
{
printf("Current time: %s",__TIME__);
}

Output

Current time: 19:54:39

C Standard Library Functions


C Standard library functions or simply C Library functions are inbuilt functions
in C programming.
The prototype and data definitions of these functions are present in their
respective header files. To use these functions we need to include the header
file in our program. For example,

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.

Advantages of Using C library functions


1. They work
One of the most important reasons you should use library functions is simply
because they work. These functions have gone through multiple rigorous
testing and are easy to use.

2. The functions are optimized for performance


Since, the functions are "standard library" functions, a dedicated group of
developers constantly make them better. In the process, they are able to
create the most efficient code optimized for maximum performance.

3. It saves considerable development time


Since the general functions like printing to a screen, calculating the square
root, and many more are already written. You shouldn't worry about creating
them once again.

4. The functions are portable


With ever-changing real-world needs, your application is expected to work
every time, everywhere. And, these library functions help you in that they do
the same thing on every computer.

Example: Square root using sqrt() function


Suppose, you want to find the square root of a number.

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

// Computes the square root of num and stores in root.


root = sqrt(num);

printf("Square root of %.2f = %.2f", num, root);


return 0;
}
Run Code

When you run the program, the output will be:


Enter a number: 12
Square root of 12.00 = 3.46

Library Functions in Different Header Files


C Header Files Description

<assert.h> Program assertion functions

<ctype.h> Character type functions

<locale.h> Localization functions

<math.h> Mathematics functions

<setjmp.h> Jump functions

<signal.h> Signal handling functions

<stdarg.h> Variable arguments handling functions

<stdio.h> Standard Input/Output functions

<stdlib.h> Standard Utility functions


C Header Files Description

<string.h> String handling functions

<time.h> Date time functions

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

// Simple C program to display "Hello World"

// Header file for input output functions


#include <stdio.h>

// main function -

// where the execution of program begins

int main()

// prints hello world

printf("Hello World");

return 0;

Output
Hello World

Compiling the First C Program


Before proceeding to write the first program, the user needs to set up a C program
compiler, which would compile and execute the “Hello World” program. Here we have
used a Windows-based GCC compiler to compile and run the program. To know more on
how to set up the local GCC compiler or run using online ide refer to Setting C
Development Environment.
Step 1:This requires writing the “Hello World” program, in a text editor and saving the
file with the extension .c, for example, we have stored the program in a C-type
file HelloWorld.c.
Step 2: This includes opening CMD or command prompt line and navigating to the
directory where the file HelloWorld.c is present. Here it is present in C:\Users\Chin\
Sample.
Step 3: To compile the code execute the following command:
gcc HelloWorld.c
This would create a C-executable file with a random name given by the compiler itself.
We got the executable filename as a.
To give a user-oriented name, run the following command:
gcc -o helloworld HelloWorld.c
This would create a C-executable file by the name helloworld.
Step 4: To run the executable file to get the result, run the following command:
helloworld
Simple Calculator Program using switch Statement
Below is the C program to implement a simple calculator using a switch case statement:

 C

// C Program to make a Simple Calculator

// Using switch case

#include <stdio.h>

#include <stdlib.h>
// Driver code

int main()

char ch;

double a, b;

while (1) {

printf("Enter an operator (+, -, *, /), "

"if want to exit press x: ");

scanf(" %c", &ch);

// to exit

if (ch == 'x')

exit(0);

printf("Enter two first and second operand: ");

scanf("%lf %lf", &a, &b);

// Using switch case we will differentiate

// operations based on different operator


switch (ch) {

// For Addition

case '+':

printf("%.1lf + %.1lf = %.1lf\n", a, b, a + b);

break;

// For Subtraction

case '-':

printf("%.1lf - %.1lf = %.1lf\n", a, b, a - b);

break;

// For Multiplication

case '*':

printf("%.1lf * %.1lf = %.1lf\n", a, b, a * b);

break;

// For Division
case '/':

printf("%.1lf / %.1lf = %.1lf\n", a, b, a / b);

break;

// If operator doesn't match any case constant

default:

printf(

"Error! please write a valid operator\n");

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

 Time Complexity: O(1)


 Auxiliary Space: O(1)
C Program to Generate Multiplication Table


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

Program to Print Multiplication Table in C


There are two approaches for printing tables in c
1. Using loops and without storing them in an array
2. Using loops and a 2-D array
1. Using loops and without storing them in an array
The idea is to use the concept of looping and directly print the multiplication table
without storing them in an array.
Algorithm:
 Take the input of the number and the range of the multiplication table.
 Declare a variable to store the product.
 Use a for loop to directly multiply and print the Multiplication table.

 C

// C program to Demonstrate the

// Multiplication table of a number

#include <stdio.h>

void print_table(int range, int num)

// Declaring a variable mul to store the product.

int mul;

// For loop to calculate the Multiplication table.

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


// To store the product.

mul = num * i;

// Printing the Multiplication Table.

printf("%d * %d = %d", num, i, mul);

// Proceeding to the next line.

printf("\n");

// Driver code

int main()

// The range of the

// Multiplication table

int range = 10;


// The number to calculate the

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

// C program to demonstrate the

// Multiplication table of a number

#include <stdio.h>

void print_table(int range, int num)

// Taking two integer variables row and column

int row, col;

// Initializing row with range of the multiplication

// table.

row = range;

// Initializing column with 3.

col = 3;
// Creating a 2-D array to calculate and store the

// Multiplication Table .

int arr[row][col];

// For loop to calculate the table

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

// Storing the number in the first column.

arr[k][0] = num;

// Storing the value to be multiplied in the second

// column.

arr[k][1] = k + 1;

// Calculating and Storing the product in the third

// column.

arr[k][2] = arr[k][1] * arr[k][0];

}
// For loop to print the Multiplication table

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

printf("%d * %d = %d", arr[i][0], arr[i][1],

arr[i][2]);

printf("\n");

// Driver code

int main()

// The range of the

// Multiplication table.

int range = 10;

// The number to calculate the

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

// C program to find LCM of

// two numbers

#include <stdio.h>

// Driver code

int main()
{

int x = 15, y = 25, max;

max = (x > y) ? x : y;

// While loop to check if max variable

// is divisible by x and y

while (1) {

if (max % x == 0 && max % y == 0) {

printf("The LCM of %d and %d is %d.", x, y,

max);

break;

++max;

return 0;

Output
The LCM of 15 and 25 is 75.

Complexity Analysis

 Time complexity: O(x*y)


 Auxiliary space: O(1)
LCM of Two Numbers using GCD
In mathematics, the LCM of two numbers is the product of two numbers divided by their
GCD. So,
LCM(a, b) = (a x b) / GCD(a, b)
Refer to the article Program to Find GCD or HCF of Two Numbers to learn how to find
the GCD of two numbers.

C Program To Find LCM of Two Numbers using GCD

 C++

// C++ program to find LCM of two numbers

#include <iostream>

using namespace std;

// Recursive function to return gcd of a and b

long long gcd(long long int a, long long int b)

if (b == 0)

return a;

return gcd(b, a % b);


}

// Function to return LCM of two numbers

long long lcm(int a, int b) { return (a / gcd(a, b)) * b; }

// Driver program to test above function

int main()

int a = 15, b = 20;

cout << "LCM of " << a << " and " << b << " is "

<< lcm(a, b);

return 0;

Output
LCM of 15 and 20 is 60

Complexity Analysis

 Time complexity: O(log(min(a, b)))


 Auxiliary space: O(1)
C Program to Check Armstrong Number


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.

What is Armstrong Number


The Armstrong number can be defined as a number that is equal to the result of the
summation of the nth power of each n digit. Let’s assume we have a number XYZ which
is 3 digit number, so XYZ can be an Armstrong number if XYZ is equal to the result of
the sum of each digit of the 3rd power.
xyz.....n = xn + yn + zn
Example:
Input: 153
Output: Yes
Explanation :
153 is an Armstrong number of 3 digits, since the sum of cubes of each digit is equal to
the number itself. As shown below:
1*1*1 + 5*5*5 + 3*3*3 = 153
Input: 120
Output: No
Explanation :
120 is not a Armstrong number of 3 digits, the sum of cubes of each digit is equal to 9 but
number is 120.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input: 1253
Output: No
Explanation :
1253 is not a Armstrong Number of 4 digits, the sum of 4th power of each digit is equal
to 723 but the number is 1253.
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input: 1634
Output: Yes
Explanation :
1634 is an Armstrong number of 4 digit, the sum of 4th power of each digit is equal to the
number itself. As shown below:
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
Recommended Practice – Armstrong Numbers
C Program for Armstrong Number of Three Digits
We can simply calculate the sum of individual digits by dividing the number by 10 and
getting reminders. And if it will be equal to the number itself then it is an Armstrong
number. Here time complexity will be reduced to O(log(n)).

 C

// C program to check given number is

// Armstrong number or not using Sum

// of Digits

#include <stdio.h>

// Driver code

int main()

int n = 153;

int temp = n;

int p = 0;

// Calculating the sum of individual digits

while (n > 0) {

int rem = n % 10;


p = (p) + (rem * rem * rem);

n = n / 10;

// Condition to check whether the

// value of P equals to user input

// or not.

if (temp == p) {

printf("Yes. It is Armstrong No.");

else {

printf("No. It is not an Armstrong No.");

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

// C program to check given number

// is Armstrong number or not

// using Functions

#include <stdio.h>

// math.h is used for pow function.

#include <math.h>

// Function to calculate

// order of the number

int order(int x)

int n = 0;

while (x) {

n++;

x = x / 10;
}

return n;

// Function to check whether the

// given number is Armstrong

// number or not

int isArmstrong(int x)

// Calling order function

int n = order(x);

int temp = x, sum = 0;

while (temp) {

int r = temp % 10;

sum += pow(r, n);

temp = temp / 10;

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

C Program to Check Armstrong Number




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.

What is Armstrong Number


The Armstrong number can be defined as a number that is equal to the result of the
summation of the nth power of each n digit. Let’s assume we have a number XYZ which
is 3 digit number, so XYZ can be an Armstrong number if XYZ is equal to the result of
the sum of each digit of the 3rd power.
xyz.....n = xn + yn + zn
Example:
Input: 153
Output: Yes
Explanation :
153 is an Armstrong number of 3 digits, since the sum of cubes of each digit is equal to
the number itself. As shown below:
1*1*1 + 5*5*5 + 3*3*3 = 153
Input: 120
Output: No
Explanation :
120 is not a Armstrong number of 3 digits, the sum of cubes of each digit is equal to 9 but
number is 120.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input: 1253
Output: No
Explanation :
1253 is not a Armstrong Number of 4 digits, the sum of 4th power of each digit is equal
to 723 but the number is 1253.
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input: 1634
Output: Yes
Explanation :
1634 is an Armstrong number of 4 digit, the sum of 4th power of each digit is equal to the
number itself. As shown below:
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
Recommended Practice – Armstrong Numbers

C Program for Armstrong Number of Three Digits


We can simply calculate the sum of individual digits by dividing the number by 10 and
getting reminders. And if it will be equal to the number itself then it is an Armstrong
number. Here time complexity will be reduced to O(log(n)).

 C

// C program to check given number is

// Armstrong number or not using Sum


// of Digits

#include <stdio.h>

// Driver code

int main()

int n = 153;

int temp = n;

int p = 0;

// Calculating the sum of individual digits

while (n > 0) {

int rem = n % 10;

p = (p) + (rem * rem * rem);

n = n / 10;

// Condition to check whether the


// value of P equals to user input

// or not.

if (temp == p) {

printf("Yes. It is Armstrong No.");

else {

printf("No. It is not an Armstrong No.");

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

// C program to check given number

// is Armstrong number or not


// using Functions

#include <stdio.h>

// math.h is used for pow function.

#include <math.h>

// Function to calculate

// order of the number

int order(int x)

int n = 0;

while (x) {

n++;

x = x / 10;

return n;

}
// Function to check whether the

// given number is Armstrong

// number or not

int isArmstrong(int x)

// Calling order function

int n = order(x);

int temp = x, sum = 0;

while (temp) {

int r = temp % 10;

sum += pow(r, n);

temp = temp / 10;

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

// C Program to Display Armstrong

// numbers between 1 to 1000


#include <math.h>

#include <stdio.h>

int main()

int i, sum, num, count = 0;

printf(

"All Armstrong number between 1 and 1000 are:\n");

// This loop will run for 1 to 1000

for (i = 1; i <= 1000; i++) {

num = i;

// Count number of digits.

while (num != 0) {

num /= 10;

count++;

num = i;
sum = pow(num % 10, count)

+ pow((num % 100 - num % 10) / 10, count)

+ pow((num % 1000 - num % 100) / 100, count);

// Check for Armstrong Number

if (sum == i) {

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

// numbers between 1 to 1000

#include <stdio.h>

#include <math.h>

int main()

int i, digit1, digit2, digit3, sum, num;

printf("All Armstrong number between 1 and 1000 are:\n");

// This loop will run for 1 to 1000

for (i = 1; i <= 1000; i++)

num = i;

// All single digit numbers are Armstrong number.

if (num <= 9)

printf("%d ", num);


}

else

sum = pow(num % 10, 3) + pow((num % 100 - num % 10) / 10, 3) + pow((num %


1000 - num % 100) / 100, 3);

if (sum == i)

printf("%d ", i);

Output
All Armstrong number between 1 and 1000 are:
1 2 3 4 5 6 7 8 9 153 370 371 407

C Program to Display Armstrong Number


Between Two Intervals


A positive integer with digits a, b, c, d… is called an Armstrong number of order n if the


following condition is satisfied:
abcd... = a^n + b^n + c^n + d^n +...
Example:
153 = 1*1*1 + 5*5*5 + 3*3*3
= 1 + 125 + 27
= 153
Therefore, 153 is an Armstrong number.
To display the Armstrong number between two intervals we can use 2 different Methods
with 4 approaches:
1. Without using the pow() function
2. Using pow() function
We will keep the same input in all the mentioned approaches and get an output
accordingly.
Input: start = 1, end = 500
Output: 1, 153, 370, 371, 407
Explanation: The Armstrong number is the sum of the cubes of its digits. i.e.
1=13
153= 13 + 53 + 33
370= 33 + 73 + 03 etc.
1. Without using the pow() function
 C

// C program to demonstrate an armstrong number

// between the given intervals

#include <stdio.h>

int main()

int s = 1, e = 500, num1, n, arm = 0,

i, num2, c;
// Iterating the for loop using

// the given intervals

for (i = s; i <= e; i++) {

num1 = i;

num2 = i;

// Finding the number of digits

while (num1 != 0) {

num1 = num1 / 10;

++c;

// Finding the armstrong number

while (num2 != 0) {

n = num2 % 10;

int pow=1;

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

pow= pow*n;
arm = arm + (pow);

num2 = num2 / 10;

// If number is equal to the arm

// then it is a armstrong number

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

// armstrong number between the

// given intervals using pow()

#include <math.h>

#include <stdio.h>

// Driver code

int main()

int s = 1, e = 500, num1, n,

arm = 0, i, num2, c;

// Iterating the for loop using the

// given intervals

for (i = s; i <= e; i++) {

num1 = i;

num2 = i;
// Finding the number of digits

while (num1 != 0) {

num1 = num1 / 10;

++c;

// Finding the armstrong number

while (num2 != 0) {

n = num2 % 10;

arm = arm + pow(n, c);

num2 = num2 / 10;

// If number is equal to the arm then

// it is a armstrong number

if (arm == i) {

printf("%d\n", i);
}

arm = 0;

c = 0;

return 0;

Output
1
153
370
371
407

1. Half Pyramid Pattern of Numbers


Half pyramid pattern of numbers looks like a right-angle triangle of numbers in which the
hypotenuse is on the right side.
Pyramid Example:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
C Program to Print Half Pyramid Pattern of Numbers
 C
// C program to print right half pyramid pattern of star

#include <stdio.h>

int main()

int rows;

printf("Number of rows: ");

scanf("%d", &rows);

// first loop for printing rows

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

// second loop for printing similar number in each

// rows

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

printf("%d ", i);

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

// C program to print inverted half pyramid pattern of number

#include <stdio.h>

int main()

{
int rows;

printf("Number of rows: ");

scanf("%d", &rows);

// first loop for printing rows

for (int i = rows; i >= 1; i--) {

// second loop for printing similar number in each rows

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

printf("%d ", i);

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

// C program to print the full pyramid pattern of alphabets

#include <stdio.h>

int main()

int rows;

printf("Number of rows: ");

scanf("%d", &rows);

// first loop to print all rows

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

// inner loop 1 to print white spaces


for (int j = 1; j <= 2 * (rows - i); j++) {

printf(" ");

// inner loop 2 to print numbers

for (int k = 1; k < 2 * i; k++) {

printf("%d ", i);

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

// C program to print the pyramid pattern

#include <stdio.h>

// Print the pattern upto n

void printPattern(int n)

// Printing upper part

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

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

printf("%d", i);

printf("\n");

// printing lower part


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

for (int j = i; j > 0; j--)

printf("%d", i);

printf("\n");

// Driver Code

int main()

int n = 8;

printPattern(n);

return 0;

// This code is contributed by bhartik021.

Output
1
22
333
4444
55555
666666
7777777
88888888
7777777
666666
55555
4444
333
22
1

Time complexity: O(n^2) // For given input n


Auxiliary Space: O(1)
5. hollow pyramid of ” * ” & Numbers
This C program print the hollow pyramid means only the border part shows in the
pyramid.
Pyramid Example:
*
* *
* *
* *
* * * *
C Program to Print hollow pyramid of ” * ” & Numbers
 C

#include <stdio.h>
int main() {

int n = 5;

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

// Print leading spaces

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

printf(" ");

// Print asterisks

for (int k = 1; k <= 2 * i - 1; k++) {

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

6. Diamond Pyramid of ” * ” & Numbers


This C program print the Diamond Pyramid of ” * ” & Number. (for number just replace
Stars (*) with their interator (I) in a loop.
*
***
*****
*******
*********
*******
*****
***
*
C program to print Diamond Pyramid of ” * ” & Numbers
 C
#include <stdio.h>

int main() {

int n = 5;

// Print the top pyramid

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

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

printf(" ");

for (int k = 1; k <= 2 * i - 1; k++) {

printf("*");

printf("\n");

// Print the inverted pyramid

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


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

printf(" ");

for (int k = 1; k <= 2 * i - 1; k++) {

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

C Program To Print Triangle




Here, we will see how to print a triangle using the C program


Input:
5
Output:
*
* *
* * *
* * * *
* * * * *

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

// C program to print a triangle

#include <stdio.h>

// Driver code

int main()

int n = 6;

// ith row has i elements

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

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

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

int rows = 8, i, j, space;

for (i = rows; i >= 1; --i)

// Loop to print the blank space

for (space = 0;

space < rows - i; ++space)

printf(" ");

// Loop to print the half of

// the star triangle

for (j = i; j <= 2 * i - 1; ++j)

printf("* ");

// Loop to print the rest of

// the star triangle


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

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;

for (i = 1; i <= rows; i++)

// Loop to print the blank spaces

for (j = 1; j < i; j++)

{
printf(" ");

// Loop to print the stars

for (j = 1;

j <= (rows * 2 - (2 * i - 1));

j++)

printf("*");

// Move to the next line to

// complete the pattern

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

// C program to illustrate the above

// given pattern of numbers.


#include <stdio.h>

int main()

int n = 5, i, j, num = 1, gap;

gap = n - 1;

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

num = j;

for (i = 1; i <= gap; i++)

printf(" ");

gap--;

for (i = 1; i <= j; i++) {

printf("%d", num);
num++;

num--;

num--;

for (i = 1; i < j; i++) {

printf("%d", num);

num--;

printf("\n");

return 0;

Output
1
232
34543
4567654
567898765

Time Complexity: O(n2), where n represents the given input.


Auxiliary Space: O(1), no extra space is required, so it is a constant.
C Program To Print Character Pyramid Pattern


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

1. Using for loop


Approach 1: Assign any character 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. Then print the character based on the number of columns.
Example:
 C

// C program to print character pattern using character

#include <stdio.h>

int main()
{

int i, j;

// input entering number of rows

int rows = 5;

// taking first character of alphabet

// which is useful to print pattern

char character = 'A';

// first for loop is used to identify number rows

for (i = 0; i < rows; i++) {

// second for loop is used to identify number

// of columns based on the rows

for (j = 0; j <= i; j++) {

// printing character to get the required


// pattern

printf("%c ", character);

printf("\n");

// incrementing character value so that it

// will print the next character

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

// C program to print character pattern by

// converting number in to character

#include <stdio.h>

int main()

int i, j;

// input entering number of rows

int rows = 5;

// given a number

int number = 65;


// first for loop is used to identify number rows

for (i = 0; i < rows; i++) {

// second for loop is used to identify number

// of columns based on the rows

for (j = 0; j <= i; j++) {

// converting number in to character

char character = (char)(number);

// printing character to get the required

// pattern

printf("%c ", character);

printf("\n");

// incrementing number value so that it


// will print the next character

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.

2. Using while loops:


Approach 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.
Example:
 C

// C program to print character pattern by

// converting number into character

#include <stdio.h>
int main()

int i = 1, j = 0;

// input entering number of rows

int rows = 5;

// given a character

char character = 'A';

// while loops checks the conditions until the

// condition is false if condition is true then enters

// in to the loop and executes the statements

while (i <= rows) {

while (j <= i - 1) {

// printing character to get the required


// pattern

printf("%c ", character);

j++;

printf("\n");

// incrementing character value so that it

// will print the next character

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.

Approach 2: Printing pattern by converting given number into character


using while loop

Example:
 C

// C program to print character pattern by

// converting number in to character

#include <stdio.h>

int main()

int i = 1, j = 0;

// input entering number of rows

int rows = 5;

// given a number

int number = 65;


// while loops checks the conditions until the

// condition is false if condition is true then enters

// in to the loop and executes the statements

while (i <= rows) {

while (j <= i - 1) {

// converting number in to character

char character = (char)(number);

// printing character to get the required

// pattern

printf("%c ", character);

j++;

printf("\n");

// incrementing number value so that it


// will print the next character

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)

C Program to Print Continuous Character


Pattern


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.

1. Using for loop


Approach 1: Using Character
1. Assign any character 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. Then print the character 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 using character using for
loop:

 C

// C program to print continuous

// character pattern using

// character

#include <stdio.h>

int main()

{
int i, j;

// Number of rows

int rows = 3;

// Taking first character of alphabet

// which is useful to print pattern

char character = 'A';

// This loop is used to identify

// number rows

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

// This for loop is used to

// identify number of columns

// based on the rows

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

{
// Printing character to get

// the required pattern

printf("%c ",character);

// Incrementing character value so

// that it will print the next 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

// C program to print continuous

// character pattern by converting

// number in to character

#include <stdio.h>

// Driver code

int main()

int i, j;

// Number of rows

int rows = 5;

// Given a number

int number = 65;


// This loop is used to identify

// number of rows

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

// This loop is used to identify number

// of columns based on the rows

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

// Converting number in to character

char character = (char)(number);

// Printing character to get the

// required pattern

printf("%c ", character);

// Incrementing number value so

// that it will print the next

// character
number++;

printf("\n");

return 0;

Output
A
B C
D E F
G H I J
K L M N O

2. Using while loop:


Approach 1: Using character
The while loops check the condition until the condition is false. If the condition is true
then enter into a loop and execute the statements. Below is the C program to print
continuous character patterns using character:

 C

// C program to print the continuous

// character pattern using while loop

#include <stdio.h>
// Driver code

int main()

int i = 1, j = 0;

// Number of rows

int rows = 5;

// Given a character

char character = 'A';

while (i <= rows)

while (j <= i - 1)

// Printing character to get

// the required pattern


printf("%c ",character);

j++;

// Incrementing character value

// so that it will print the next

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

// C program to print continuous

// character pattern by converting

// 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 (i <= rows)

while (j <= i - 1)

// Converting number in to character

char character = (char)(number);

// Printing character to get the

// required pattern

printf("%c ",character);

j++;

// Incrementing number value so

// that it will print the next

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

// a Hollow Star Pyramid

#include <stdio.h>

int main()

int i, space, n = 5, j = 0;

// first for loop is used to

// iterate number of rows

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

// second for loop is used to print spaces

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

printf(" ");
}

// third for loop is used

// to print the required

// pattern

for (j = 0; j <= 2 * i; j++) {

if (j == 0 || j == 2 * i)

printf("*");

else

printf(" ");

// print the new line after every row

printf("\n");

// used to print last row

for (i = 0; i < 2 * n - 1; i++) {

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.

Using For Loop


Approach:
The approach is to use three loops:
1. One is to control the number of rows.
2. The second is to control the blank spaces.
3. The third is to control the number of columns.
Then by using concepts of the nested loop one can easily print the pattern.
Algorithm:
1. Take the Input of row value for the Inverted Pyramid.
2. We need to use three loops one is the outer loop to change the line and two inner
loops one to print the star and the other to print the space.
3. The outer loop iterate row times and print a newline after completing the inner loop.
4. The first inner loop is used to print the space from 1 to (current_row -1).
5. The second inner loop is used to print the star ( “*” ) at first and last column (i.e
length _of_row * 2 – (2 * Current_row – 1)) .
6. The second loop iterates from 1 to the last column.
Below is the C program to print an inverted hollow star pyramid using for loop:

 C

// C program to print an inverted hollow

// star pyramid using for loop

#include <stdio.h>

void pattern_fun(int row)

// To iterate through the rows

for (int j = 1; j <= row; j++)

// To print the beginning spaces

for (int sp = 1; sp <= j - 1; sp++)


{

printf(" ");

// Iterating from jth column to

// last column (row*2 - (2*j - 1))

int last_col = (row * 2 - (2 * j - 1));

// To iterate through column

for (int k = 1; k <= last_col; k++)

// To Print all star for first

// row (j==1) jth column (k==1)

// and for last column

// (row*2 - (2*j - 1))

if (j == 1 || k == 1)

printf("*");

else if (k == last_col)
printf("*");

else

printf(" ");

// Proceeding to next row.

printf("\n");

// Driver code

int main()

// Number of rows

int row = 7;

// Calling the function to

// print the pattern.

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

// C program to print an inverted

// hollow star pyramid using while

// loop

#include <stdio.h>

void pattern_fun(int row)

// Declaring and initializing


// the loop control variables.

int j = 1;

int sp = 1;

int k = 1;

// To iterate through the rows

while (j <= row)

// Initializing the space

// control variable.

sp = 1;

// To print the beginning spaces

while (sp <= j - 1)

printf(" ");

// Incrementing the value


sp++;

// Iterating from jth column to

// last column (row*2 - (2*j - 1))

int last_col = (row * 2 - (2 * j - 1));

// Initializing the column control

// variable.

k = 1;

// To iterate through column

while (k <= last_col)

// To Print all star for first

// row (j==1) jth column (k==1)

// and for last column

// (row*2 - (2*j - 1))


if (j == 1 || k == 1)

printf("*");

else if (k == last_col)

printf("*");

else

printf(" ");

// Incrementing the value

k++;

// Proceeding to next row.

printf("\n");

// Incrementing the value

j++;

}
// Driver code

int main()

// Number of rows

int row = 4;

// Calling the function to

// print the pattern.

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

Approach 1: Using for loop


Example:
 C

// C Program To Print Hollow Diamond

// Pattern using for loop

#include <stdio.h>

int main()

{
int n = 5, rows, columns;

// for loop is used to identify

// the number of rows and

// it is used to print upper triangle

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

// used for printing the spaces

for (columns = n; columns > rows; columns--) {

printf(" ");

// print star

printf("*");

// again print the spaces

for (columns = 1; columns < (rows - 1) * 2;

columns++) {
printf(" ");

if (rows == 1) {

printf("\n");

else {

printf("*\n");

// for loop is used to identify

// the number of rows and

// it is used to print lower triangle

for (rows = n - 1; rows >= 1; rows--) {

// used for printing the spaces

for (columns = n; columns > rows; columns--) {

printf(" ");

}
// print star

printf("*");

for (columns = 1; columns < (rows - 1) * 2;

columns++) {

printf(" ");

if (rows == 1) {

printf("\n");

else {

printf("*\n");

return 0;

Output
*
* *
* *
* *
* *
* *
* *
* *
*

Method : Using while loop


Example:
 C

// C Program To Print Hollow Diamond

// Pattern using while loop

#include <stdio.h>

int main()

int n = 5, rows = 1, columns;

// while loop is used to identify

// the number of rows and

// it is used to print upper triangle

while (rows <= n) {


columns = n;

// used for printing the spaces

while (columns > rows) {

printf(" ");

columns--;

// print star

printf("*");

columns = 1;

while (columns < (rows - 1) * 2) {

printf(" ");

columns++;

if (rows == 1) {

printf("\n");

}
else {

printf("*\n");

rows++;

// while loop is used to identify

// the number of rows and

// it is used to print lower triangle

rows = n - 1;

while (rows >= 1) {

columns = n;

// used for printing the spaces

while (columns > rows) {

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

// C program to print full

// diamond shape pyramid

#include <stdio.h>

// Prints diamond pattern

void printDiamond(int n)

int space = n - 1;

// Run loop till the number

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

// Loop for the initially space

// before the star printing

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

printf(" ");

// Print the i+1 stars

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

printf("* ");

printf("\n");

space--;

// Repeat again in the reverse order

space = 0;
// run a loop till number of rows

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

// Loop for the initially space

// before the star printing

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

printf(" ");

// Print the i stars

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

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.

C program to Print Pascal’s Triangle


 C

// C program to print Pascal’s Triangle


// using combinations in O(n^2) time

// and O(1) extra space function

#include <stdio.h>

void printPascal(int n)

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

for (int space = 1; space <= n - line; space++)

printf(" ");

// used to represent C(line, i)

int coef = 1;

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

// The first value in a line

// is always 1

printf("%4d", coef);

coef = coef * (line - i) / i;

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

Time Complexity: O(n2)


Auxiliary Space: O(1)
C Program to Print Floyd’s Triangle Pyramid
Patterns


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.

Floyd’s Triangle of natural numbers

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Floyd’s triangle of alphabets

a
b c
d e f
g h i j

Star Floyd pattern

*
* *
* * *
* * * *

1. Floyd’s triangle using for loop


 C

// C program to Demonstrate Floyd's Triangle

// Using for loop

#include <stdio.h>

void floyd(int n)

int i, j = 1;

// Condition printing the number of element

for (i = 1; i <= (n * (n + 1)) / 2; i++) {

printf("%d ", i);

// condition for row of number of element printing

if (i == (j * (j + 1)) / 2) {

printf("\n");

j++;
}

int main() { floyd(6); }

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

// C program to Demonstrate Floyd's Triangle

// Using while loop

#include <stdio.h>

void floyd(int n)

int i = 1, j = 1;
// condition for number of element

while (i <= (n * (n + 1)) / 2) {

printf("%d ", i);

// condition for what element has to print and

// how many times

if (i == (j * (j + 1)) / 2) {

printf("\n");

j++;

i++;

int main() { floyd(6); }

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

// C program to Demonstrate Floyd's Triangle

// Using recursion

#include <stdio.h>

int row = 1, i = 1;

void floyd(int n)

// base condition

if (n == 0)

return;

for (int j = 1; j <= row; j++)

printf("%d ", i++);

row++;

printf("\n");

floyd(n - 1);
}

int main() { floyd(6); }

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

// C program to Demonstrate Reverse Floyd's

// Triangle Using for loop

#include <iostream>

using namespace std;

void reverse_floyd(int n)

// total number of elements


int i = n * (n + 1) / 2;

// condition for printing them

while (i > 0) {

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

printf("%d ", i--);

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

// C program to Demonstrate Star Floyd's

// Triangle Using for loop

#include <stdio.h>

void floyd(int n)

int i, j = 1;

for (i = 1; i <= (n * (n + 1)) / 2; i++) {

printf("* ");

if (i == (j * (j + 1)) / 2) {

printf("\n");

j++;

int main() { floyd(6); }

Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
Time Complexity: O(n2)
Auxiliary Space: O(1)
6. Alphabets Floyd’s triangle using for loop
 C

// C program to Demonstrate Alphabet Floyd's

// Triangle Using for loop

#include <stdio.h>

void alpha_floyd(int n)

int k = 'a';

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

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

printf("%c ", k++);

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

Using the concepts of the Nested loop


The approach is to previously calculate the maximum value which is to be present in the
pattern and then decrease it using the decrement operator, and then we can specify rows
and columns using the concepts of the Nested loop.

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

// C program to demonstrate reversing

// of floyd's triangle

#include <stdio.h>

void Reverse_Floyd(int row)

// Calculating the maximum value

int max_val = row * (row + 1) / 2;

// Initializing num with the max value

int num = max_val;


// The outer loop maintains,

// the number of rows.

for (int i = row; i >= 1; i--) {

// The inner loop maintains,

// the number of column.

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

// To print the numbers.

printf("%d ", num);

// To keep decreasing the value

// of numbers.

num--;

// To proceed to next line.


printf("\n");

int main()

int row = 5; // The number of Rows to be printed.

// Calling the Function.

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.

Approaches to Check Prime number


using 3 different approaches:
1. Using for loop for prime number.
2. Using for loop for not prime number.
3. Using while loop for prime number.
Example:
Input: n = 7
Output: 7 is a prime number

1. Using For Loop

Below is the C program to check prime numbers using for loop:


 C

// C program to demonstrate whether

// a number is prime or not using

// for loop

#include <stdio.h>

// Defining the function


int primenumber(int number)

int i;

// Condition for checking the

// given number is prime or

// not

for (i = 2; i <= number / 2; i++)

if (number % i != 0)

continue;

else

return 1;

return 0;

// Driver code
int main()

int num = 7, res = 0;

// Calling the function

res = primenumber(num);

if (res == 0)

printf("%d is a prime number", num);

else

printf("%d is not a prime number", num);

Output
7 is a prime number

2. Using For Loop for Not Prime Number

Below is the C program to check whether a number is prime or not using for loop:
 C

// C program to demonstrate whether

// a number is prime or not using


// for loop

#include <stdio.h>

// Defining the function

int primenumber(int number)

int i;

// Condition for checking

// the given number is prime

// number or not

for (i = 2; i <= number - 1; i++)

if (number % i == 0)

return 0;

return 1;

}
// Driver code

int main()

int num = 4, res;

// Calling the function

res = primenumber(num);

if (res == 1)

printf("%d is a prime number", num);

else

printf("%d is not a prime number", num);

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

// C program to demonstrate whether

// a number is prime or not using

// while loop

#include <stdio.h>

// Defining the function

int primenumber(int number)

// Condition for checking the

// given number is prime or

// not

int i = 2;

while (i <= number / 2)

{
if (number % i == 0)

return 0;

else

i++;

return 1;

// Driver code

int main()

int num = 7, prime;

// Calling the function

prime = primenumber(num);

// Printing the result

if (prime == 1)
printf("%d is a prime number", num);

else

printf("%d is not a prime number", num);

return 0;

Output
7 is a prime number

C Program to Display Prime Numbers Between


Two Intervals Using Functions


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

Using For Loop

Below is the C program to display prime numbers between two intervals using functions
and for loop:

 C

// C Program to demonstrate Prime Numbers

// Between Two Intervals Using for

// loop in a function
#include <stdio.h>

// User-defined function to check

// prime number

int checkPrimeNumber(int number)

int i, f = 1;

// Condition for finding the

// prime numbers between the

// given intervals

for (i = 2; i <= number / 2; ++i)

if (number % i == 0)

f = 0;

break;

}
}

return f;

// Driver code

int main()

int num1 = 2, num2 = 10, j, f;

printf("Prime numbers between %d and %d are: ",

num1, num2);

for (j = num1; j < num2; ++j)

// if flag is equal to 1 then

// it is a prime number

// calling the function

f = checkPrimeNumber(j);
if (f == 1)

// Printing the result

printf("%d ", j);

return 0;

Output
Prime numbers between 2 and 10 are: 2 3 5 7

Using While Loop

Below is the C program to display prime numbers between two intervals using functions
and while loop:

 C

// C Program to demonstrate Prime Numbers

// Between Two Intervals Using for


// loop in a function

#include <stdio.h>

int isPrime(int number)

int i;

// condition for finding the

// prime numbers between the

// given intervals

for (i = 2; i <= number / 2; i++) {

// if the number is divisible

// by 1 and self then it

// is prime number

if (number % i == 0) {

return 0;

}
}

return 1;

// Driver code

int main()

int num1 = 2, num2 = 10;

printf("The prime numbers between %d to %d are: ",

num1, num2);

while (num1 <= num2)

// calling the function

if (isPrime(num1))

{
// printing the result

printf("%d, ", num1);

num1++;

return 0;

Output
The prime numbers between 2 to 10 are: 2, 3, 5, 7,

C Program for Quadratic Equation Roots




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

2. If D = 0, Roots are real and the same

3.If D < 0, Roots are complex

Program to Find Roots of a Quadratic Equation


 C

// C program to find roots of

// a quadratic equation

#include <math.h>
#include <stdio.h>

#include <stdlib.h>

// Prints roots of quadratic

// equation ax*2 + bx + x

void findRoots(int a, int b, int c)

// If a is 0, then equation is

// not quadratic, but linear

if (a == 0) {

printf("Invalid");

return;

int d = b * b - 4 * a * c;

double sqrt_val = sqrt(abs(d));

if (d > 0) {
printf("Roots are real and different\n");

printf("%f\n%f", (double)(-b + sqrt_val) / (2 * a),

(double)(-b - sqrt_val) / (2 * a));

else if (d == 0) {

printf("Roots are real and same\n");

printf("%f", -(double)b / (2 * a));

else // d < 0

printf("Roots are complex\n");

printf("%f + i%f\n%f - i%f", -(double)b / (2 * a),

sqrt_val / (2 * a), -(double)b / (2 * a),

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

Complexity Analysis

Time Complexity: O(log(D)), where D is the discriminant of the given quadratic


equation.
Auxiliary Space: O(1)
C Program to Check Whether a Number Can
Be Express as Sum of Two Prime Numbers


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

// C program to check whether a

// number can be expressed as sum

// of two prime numbers

#include <stdio.h>

// Function to check prime number

int isPrime(int n)

int i, isPrime = 1;

// 0 and 1 are not prime numbers


if (n == 0 || n == 1) {

isPrime = 0;

else {

for (i = 2; i <= n / 2; ++i) {

if (n % i == 0) {

isPrime = 0;

break;

return isPrime;

// Driver code

int main()

{
int n = 7, i, flag = 0;

for (i = 2; i <= n / 2; ++i) {

// condition for i to be a

// prime number

if (isPrime(i) == 1) {

// condition for n-i to

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

// C program to find the sum of n

// natural numbers using recursion

#include <stdio.h>

// Returns the sum of first n

// natural numbers

int recSum(int n)

// Base condition
if (n <= 1)

return n;

// Recursive call

return n + recSum(n - 1);

// Driver code

int main()

int n = 10;

printf("Sum = %d ", recSum(n));

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.

Recommended Practice – LCM And GCD Try It!

Using Simple Method


To find the GCD of two numbers we will first find the minimum of the two numbers and
then find the highest common factor of that minimum which is also the factor of the other
number.
Algorithm

 Declare a variable result and initialize it with the minimum of a and b.


 Run a while loop till the result > 0.
 Check if both a and b are divisible by result by using the modulo operator (%), and
break the loop.
 Otherwise, decrement result by 1 in each iteration until a common divisor is found or
the result becomes 0.
 After the while loop, the result variable will hold the gcd of two numbers. Return the
value of the result.
C Program to Find GCD or HCF of Two Numbers
 C

// C program to find GCD of two numbers

#include <math.h>

#include <stdio.h>

// Function to return gcd of a and b

int gcd(int a, int b)

// Find Minimum of a and b

int result = ((a < b) ? a : b);

while (result > 0) {

// Check if both a and b are divisible by result

if (a % result == 0 && b % result == 0) {


break;

result--;

// return gcd of a nd b

return result;

// Driver program to test above function

int main()

int a = 98, b = 56;

printf("GCD of %d and %d is %d ", a, b, gcd(a, b));

return 0;

// This code is contributed by Suruchi Kumari

Output
GCD of 98 and 56 is 14
Complexity Analysis

 Time Complexity: O(min(a,b))


 Auxiliary Space: O(1) or constant
C Program to Reverse a Stack using
Recursion


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!

Reverse a stack using Recursion


The idea of the solution is to hold all values in Function Call Stack until the stack
becomes empty. When the stack becomes empty, insert all held items one by one at the
bottom of the stack.
Illustration:
Below is the illustration of the above approach
 Let given stack be
1

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

Follow the steps mentioned below to implement the idea:


 Create a stack and push all the elements in it.
 Call reverse(), which will pop all the elements from the stack and pass the popped
element to function insert_at_bottom()
 Whenever insert_at_bottom() is called it will insert the passed element at the bottom
of the stack.
 Print the stack
Below is the implementation of the above approach:

 C

// C program to reverse a

// stack using recursion

#include <stdio.h>

#include <stdlib.h>

#define bool int

// structure of a stack node

struct sNode {

char data;
struct sNode* next;

};

// Function Prototypes

void push(struct sNode** top_ref, int new_data);

int pop(struct sNode** top_ref);

bool isEmpty(struct sNode* top);

void print(struct sNode* top);

// Below is a recursive function

// that inserts an element

// at the bottom of a stack.

void insertAtBottom(struct sNode** top_ref, int item)

if (isEmpty(*top_ref))

push(top_ref, item);

else {
// Hold all items in Function Call

// Stack until we reach end of the

// stack. When the stack becomes

// empty, the isEmpty(*top_ref)becomes

// true, the above if part is executed

// and the item is inserted at the bottom

int temp = pop(top_ref);

insertAtBottom(top_ref, item);

// Once the item is inserted

// at the bottom, push all

// the items held in Function

// Call Stack

push(top_ref, temp);

// Below is the function that


// reverses the given stack using

// insertAtBottom()

void reverse(struct sNode** top_ref)

if (!isEmpty(*top_ref)) {

// Hold all items in Function

// Call Stack until we

// reach end of the stack

int temp = pop(top_ref);

reverse(top_ref);

// Insert all the items (held in

// Function Call Stack)

// one by one from the bottom

// to top. Every item is

// inserted at the bottom

insertAtBottom(top_ref, temp);

}
}

// Driver Code

int main()

struct sNode* s = NULL;

push(&s, 4);

push(&s, 3);

push(&s, 2);

push(&s, 1);

printf("

Original Stack ");

print(s);

reverse(&s);

printf("

Reversed Stack ");

print(s);
return 0;

// Function to check if

// the stack is empty

bool isEmpty(struct sNode* top)

return (top == NULL) ? 1 : 0;

// Function to push an item to stack

void push(struct sNode** top_ref, int new_data)

// allocate node

struct sNode* new_node

= (struct sNode*)malloc(sizeof(struct sNode));


if (new_node == NULL) {

printf("Stack overflow

");

exit(0);

// put in the data

new_node->data = new_data;

// link the old list

// off the new node

new_node->next = (*top_ref);

// move the head to

// point to the new node

(*top_ref) = new_node;

}
// Function to pop an item from stack

int pop(struct sNode** top_ref)

char res;

struct sNode* top;

// If stack is empty then error

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

void print(struct sNode* top)

printf("

");

while (top != NULL) {

printf(" %d ", top->data);

top = top->next;

Learn Data Structures & Algorithms with GeeksforGeeks

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 Program To Calculate the Power of a Number


A simple solution to calculate the power would be to multiply x exactly n times. We can
do that by using a simple for or while loop.

 C

// C program for the above approach

#include <stdio.h>

// Naive iterative solution to

// calculate pow(x, n)
long power(int x, unsigned n)

// Initialize result to 1

long long pow = 1;

// Multiply x for n times

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

pow = pow * x;

return pow;

// Driver code

int main(void)

int x = 2;
unsigned n = 3;

// Function call

int result = power(x, n);

printf("%d", result);

return 0;

Output
8

Complexity Analysis

 Time Complexity: O(n), to iterate n times.


 Auxiliary Space: O(1)
C Program – Arrays
How to pass a 2D array as a parameter in C?


This post is an extension of How to dynamically allocate a 2D array in C?


A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D
array to a function can be difficult to remember. One important thing for passing
multidimensional arrays is, first array dimension does not have to be specified. The
second (and any subsequent) dimensions must be given
1) When both dimensions are available globally (either as a macro or as a global
constant).

 C

#include <stdio.h>

const int M = 3;

const int N = 3;

void print(int arr[M][N])

int i, j;

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

for (j = 0; j < N; j++)

printf("%d ", arr[i][j]);

int main()

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

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;

void print(int arr[][N], int m)

int i, j;

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

for (j = 0; j < N; j++)

printf("%d ", arr[i][j]);

}
int main()

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

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

// The following program works only if your compiler is C99 compatible.

#include <stdio.h>

// n must be passed before the 2D array

void print(int m, int n, int arr[][n])

{
int i, j;

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

for (j = 0; j < n; j++)

printf("%d ", arr[i][j]);

int main()

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

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>

void print(int *arr, int m, int n)

int i, j;

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

for (j = 0; j < n; j++)

printf("%d ", *((arr+i*n) + j));

int main()

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

int m = 3, n = 3;

// We can also use "print(&arr[0][0], m, n);" and "print((int *)arr[0], m, n);"

print((int *)arr, m, n);

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;

void print(int (*arr)[M])

int i, j;

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

for (j = 0; j < M; j++)

printf("%d ", arr[i][j]);

int main()

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

print(arr);
return 0;

Output
1 2 3 4 5 6 7 8 9

C Program to Find Largest Element in an Array




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

// C program to find maximum in

// arr[] of size n

#include <stdio.h>

// C function to find maximum

// in arr[] of size n

int largest(int arr[], int n)

int i;

// Initialize maximum element

int max = arr[0];


// Traverse array elements from

// second and compare every

// element with current max

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

if (arr[i] > max)

max = arr[i];

return max;

// Driver code

int main()

int arr[] = { 10, 324, 45, 90, 9808 };

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

printf("Largest in given array is %d", largest(arr, n));

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

Maximum and minimum of an array using Linear search:


Initialize values of min and max as minimum and maximum of the first two elements
respectively. Starting from 3rd, compare each element with max and min, and change
max and min accordingly (i.e., if the element is smaller than min then change min, else if
the element is greater than max then change max, else ignore the element)
Below is the implementation of the above approach:

 C

/* structure is used to return two values from minMax() */

#include<stdio.h>

struct pair

int min;

int max;

};

struct pair getMinMax(int arr[], int n)

struct pair minmax;

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;

/* If there are more than one elements, then initialize min

and max*/

if (arr[0] > arr[1])

minmax.max = arr[0];

minmax.min = arr[1];

else

minmax.max = arr[1];

minmax.min = arr[0];

}
for (i = 2; i<n; i++)

if (arr[i] > minmax.max)

minmax.max = arr[i];

else if (arr[i] < minmax.min)

minmax.min = arr[i];

return minmax;

/* Driver program to test above function */

int main()

int arr[] = {1000, 11, 445, 1, 330, 3000};

int arr_size = 6;
struct pair minmax = getMinMax (arr, arr_size);

printf("nMinimum element is %d", minmax.min);

printf("nMaximum element is %d", minmax.max);

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

/* structure is used to return two values from minMax() */

#include <stdio.h>

struct pair {

int min;

int max;

};

struct pair getMinMax(int arr[], int low, int high)

struct pair minmax, mml, mmr;

int mid;

// If there is only one element

if (low == high) {

minmax.max = arr[low];

minmax.min = arr[low];

return minmax;
}

/* If there are two elements */

if (high == low + 1) {

if (arr[low] > arr[high]) {

minmax.max = arr[low];

minmax.min = arr[high];

else {

minmax.max = arr[high];

minmax.min = arr[low];

return minmax;

/* If there are more than 2 elements */

mid = (low + high) / 2;

mml = getMinMax(arr, low, mid);


mmr = getMinMax(arr, mid + 1, high);

/* compare minimums of two parts*/

if (mml.min < mmr.min)

minmax.min = mml.min;

else

minmax.min = mmr.min;

/* compare maximums of two parts*/

if (mml.max > mmr.max)

minmax.max = mml.max;

else

minmax.max = mmr.max;

return minmax;

/* Driver program to test above function */


int main()

int arr[] = { 1000, 11, 445, 1, 330, 3000 };

int arr_size = 6;

struct pair minmax = getMinMax(arr, 0, arr_size - 1);

printf("nMinimum element is %d", minmax.min);

printf("nMaximum element is %d", minmax.max);

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.

Maximum and minimum of an array by comparing in pairs:


If n is odd then initialize min and max as the first element.
If n is even then initialize min and max as minimum and maximum of the first two
elements respectively.
For the rest of the elements, pick them in pairs and compare their maximum and
minimum with max and min respectively.
Below is the implementation of the above approach:

 C

#include<stdio.h>

/* structure is used to return two values from minMax() */

struct pair

int min;

int max;

};

struct pair getMinMax(int arr[], int n)

struct pair minmax;


int i;

/* If array has even number of elements then

initialize the first two elements as minimum and

maximum */

if (n%2 == 0)

if (arr[0] > arr[1])

minmax.max = arr[0];

minmax.min = arr[1];

else

minmax.min = arr[0];

minmax.max = arr[1];

i = 2; /* set the starting index for loop */


}

/* If array has odd number of elements then

initialize the first element as minimum and

maximum */

else

minmax.min = arr[0];

minmax.max = arr[0];

i = 1; /* set the starting index for loop */

/* In the while loop, pick elements in pair and

compare the pair with max and min so far */

while (i < n-1)

if (arr[i] > arr[i+1])

{
if(arr[i] > minmax.max)

minmax.max = arr[i];

if(arr[i+1] < minmax.min)

minmax.min = arr[i+1];

else

if (arr[i+1] > minmax.max)

minmax.max = arr[i+1];

if (arr[i] < minmax.min)

minmax.min = arr[i];

i += 2; /* Increment the index by 2 as two

elements are processed in loop */

return minmax;

}
/* Driver program to test above function */

int main()

int arr[] = {1000, 11, 445, 1, 330, 3000};

int arr_size = 6;

struct pair minmax = getMinMax (arr, arr_size);

printf("nMinimum element is %d", minmax.min);

printf("nMaximum element is %d", minmax.max);

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

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

// Header file for input output functions

#include <iostream>

using namespace std;

// Main() function: where the execution of

// program begins

int main()

// Prints hello world

cout << "Hello World";

return 0;

Output
Hello World

C++ Program to Print Your Own Name





Here, we will see how to input a name and print it as the output using a C++ program.
Below are the examples:
Input: GeeksforGeeks
Output: GeeksforGeeks
Input: Alex
Output: Alex
Below is the C++ program to print the name as output:

 C++

// C++ program to print name

// as output

#include <iostream>

using namespace std;

// Driver code

int main()

string name;

cout << "Enter the name: ";

cin >> name;

cout << "Entered name is: " <<


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

// C++ program to demonstrate the

// cin object

#include <iostream>

using namespace std;


// Driver Code

int main()

int i;

// Take input using cin

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

// C++ program to demonstrate the taking

// multiple inputs from the user

#include <iostream>

using namespace std;

// Driver Code

int main()

string name;

int age;

// Take multiple input using cin

cin >> name >> age;


// Print output

cout << "Name : " << name << endl;

cout << "Age : " << age << endl;

return 0;

Input:

Output:

How to Read and Print an Integer value in C++




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

// C++ program to take an integer

// as input and print it

#include <iostream>

using namespace std;

// Driver code

int main()

// Declare the variables

int num;

// Input the integer

cout << "Enter the integer: ";

cin >> num;


// Display the integer

cout << "Entered integer is: " << 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++ Program to Add Two Numbers Using the Addition Operator

 C++

// C++ program to add two number

// using addition operator

#include <iostream>

using namespace std;

// Function to return sum

// of two number

int addTwoNumber(int A, int B)

// Return sum of A and B

return A + B;

// Driver Code
int main()

// Given two number

int A = 4, B = 11;

// Function call

cout << "sum = " << addTwoNumber(A, B);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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++ Program to Add Two Numbers Using the Subtraction Operator

 C++

// C++ program to add two number


// using subtraction operator

#include <iostream>

using namespace std;

// Function to return sum

// of two number

int addTwoNumber(int A, int B)

// Return sum of A and B

return A - (-B);

// Driver Code

int main()

// Given two number

int A = 4, B = 11;
// Function call

cout << "sum = " << addTwoNumber(A, B);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to add two number using

// increment/decrement operator
#include <iostream>

using namespace std;

// Function to return sum

// of two number

int addTwoNumber(int A, int B)

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

// Given two number

int A = 4, B = 11;

// Function call

cout << "sum = " << addTwoNumber(A, B);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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++ Program to Add Two Numbers Using printf() Function

 C++

// C++ program to add two number

// using printf method

#include <iostream>

using namespace std;

// Function to return sum

// of two number

int addTwoNumber(int A, int B)

// Return sum of A and B

return printf("%*s%*s", A, "", B, "");

// Driver Code
int main()

// Given two number

int A = 4, B = 11;

// Function call

printf("sum = %d", addTwoNumber(A, B));

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

 Run a loop till B becomes 0.


 Inside loop:
 carry = A & B calculates the carry by performing a bitwise AND operation
between A and B.
 A = A ^ B calculates the sum of A and B without considering any carry.
This operation uses bitwise XOR to add A and B without carrying.
 B = carry << 1 calculates the carry for the next iteration by shifting the
carry one position to the left. This is because, in the next iteration, the carry
will need to be added to the sum.
 Return A that holds the sum of two numbers.

C++ Program to Add Two Numbers Using the Half Adder Method

 C++

// C++ program to add two number

// using half adder method

#include <iostream>

using namespace std;

// Function to return sum

// of two number

int addTwoNumber(int A, int B)

// Iterate till there is no carry

while (B != 0) {

// Carry now contains common

// set bits of A and B


int carry = A & B;

// Sum of bits of A and B

// where at least one of the

// bits is not set

A = A ^ B;

// Carry is shifted by one so

// that adding it to A gives

// the required sum

B = carry << 1;

return A;

// Driver Code

int main()
{

// Given two number

int A = 4, B = 11;

// Function call

printf("sum = %d", addTwoNumber(A, B));

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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++ Program to Add Two Numbers Using Exponential and Logarithm

 C++

// C++ program to add two number


// using log and exponential

#include <bits/stdc++.h>

using namespace std;

// Function to return sum

// of two number

int addTwoNumber(int A, int B)

// Return sum of A and B

return log(exp(A) * exp(B));

// Driver Code

int main()

// Given two number

int A = 4, B = 11;
// Function call

printf("sum = %d", addTwoNumber(A, B));

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
sum = 15
 Time complexity: O(log n)
 Auxiliary Space: O(1)
7. Using Recursion
Algorithm

// Base case: If A is greater than 0, then return B


if(A > 0)
return B;

// Update A to (A&B)<<1 and B to A ^ B and recursively call for the


updated value
else
recursive_function((A & B) << 1, A ^ B);
C++ Program to Add Two Numbers Using Recursion
 C++

// C++ program to add two number


// using Recursion

#include <iostream>

// Function to return sum

// of two number

int addTwoNumber(int A, int B)

// Base Case

if (!A)

return B;

// Recursive Call

else

return addTwoNumber((A & B) << 1, A ^ B);

// Driver Code

int main()
{

// Given two number

int A = 4, B = 11;

// Function call

printf("sum = %d", addTwoNumber(A, B));

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

1. Assign a to a temp variable: temp = a


2. Assign b to a: a = b
3. Assign temp to b: b = temp
C++ Program to Swap Two Numbers using a Temporary Variable.
 C++

// C++ program to swap two

// numbers using 3rd variable

#include <bits/stdc++.h>

using namespace std;

// Driver code

int main()

int a = 2, b = 3;

cout << "Before swapping a = " << a << " , b = " << b

<< endl;
// temporary variable

int temp;

// appying swapping algorithm

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

 Time Complexity: O(1) as only constant operations are done.


 Space Complexity: O(1) as no extra space has been used.
2. Swap Numbers Without Using a Temporary Variable
We can also swap numbers without using the temporary variable. Unlike the previous
method, we use some mathematical operations to swap the values.
Algorithm
1. Assign to b the sum of a and b i.e. b = a + b.
2. Assign to a difference of b and a i.e. a = b – a.
3. Assign to b the difference of b and a i.e. b = b – a.
C++ Program to Swap Two Numbers Without Using a Temporary Variable.
 C++

// C++ program to swap two

// numbers without using 3rd

// variable

#include <bits/stdc++.h>

using namespace std;

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

 Time Complexity: O(1), as only constant time operations are done.


 Space Complexity: O(1), as no extra space has been used.
3. Swap Two Numbers Using Inbuilt Function
C++ Standard Template Library (STL) provides an inbuilt swap() function to swap two
numbers.

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

// C++ program to swap two

// numbers using swap()

// function

#include <bits/stdc++.h>

using namespace std;

// Driver code

int main()

int a = 5, b = 10;

cout << "Before swapping a = " << a << " , b = " << b

<< endl;

// Built-in swap function

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

C++ Program to Find the Size of int, float,


double and char


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

// C++ program to find the size of int, char,

// float and double data types

#include <iostream>

using namespace std;

int main()

{
int integerType;

char charType;

float floatType;

double doubleType;

// Calculate and Print

// the size of integer type

cout << "Size of int is: " << sizeof(integerType)

<< "\n";

// Calculate and Print

// the size of doubleType

cout << "Size of char is: " << sizeof(charType) << "\n";

// Calculate and Print

// the size of charType

cout << "Size of float is: " << sizeof(floatType)

<< "\n";
// Calculate and Print

// the size of floatType

cout << "Size of double is: " << sizeof(doubleType)

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

 Time complexity: O(1)


 Auxiliary space: O(1)
Data Types with Their Size, Range, and Format Specifiers
Here is a list of all the data types with their size, range and format specifiers:
/tbody>
Memory Format
Data Type (bytes) Range Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

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

-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

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

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

unsigned long long 0 to


8 %llu
int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.17549e-38 to 3.40282e+38 %f


Memory Format
Data Type (bytes) Range Specifier

2.22507e-308 to
double 8 %lf
1.79769e+308

C++ Program To Multiply Two Floating-Point


Numbers


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

We can multiply two floating-point numbers in C++ by using Multiplication


Operator (*)
C++ Program To Multiply Two Floating-Point Numbers
The two floating-point numbers are multiplied using the function that uses the arithmetic
operator ( * ), and the product is stored in the variable product.
 C++

// C++ program to multiply two

// floating point numbers

#include <iostream>

using namespace std;

// Creating a user-defined function

// called mul_floatnumbers that

// multiplies the numbers passed to

// it as an input. It gives you the

// product of these numbers.

float mul_floatnumbers(float a, float b) { return a * b; }

// Driver code

int main()

float A = 1.2, B = 3.0, product;


// Calling mul_floatnumbers function

product = mul_floatnumbers(A, B);

// Printing the output

cout << product;

return 0;

Output
3.6

Complexity Analysis

 Time Complexity: O(1)


 Auxiliary Space: O(1)
C++ Program To Convert Fahrenheit To
Celsius


Given a Temperature n in Fahrenheit scale convert it into Celsius scale. Examples:


Input: 32
Output: 0
Input: -40
Output: -40
Formula for converting Fahrenheit scale to Celsius scale
T(°C) = (T(°F) - 32) × 5/9

 C++

// C++ program to convert Fahrenheit

// scale to Celsius scale

#include <bits/stdc++.h>

using namespace std;

// Function to convert Fahrenheit

// to Celsius

float Conversion(float n)

return (n - 32.0) * 5.0 / 9.0;

// Driver code

int main()

{
float n = 40;

cout << Conversion(n);

return 0;

Output:
4.44444
Time Complexity: O(1)
Auxiliary Space: O(1)
C++ Program To Find Simple Interest


What is ‘Simple Interest’?


Simple interest is a quick method of calculating the interest charge on a loan. Simple
interest is determined by multiplying the daily interest rate by the principal by the number
of days that elapse between payments.
Simple Interest formula:
Simple interest formula is given by:
Simple Interest = (P x T x R)/100
Where,
P is the principal amount
T is the time and
R is the rate
Examples :
Example 1:
Input: P = 10000
R = 5
T = 5
Output: 2500
We need to find simple interest on
Rs. 10,000 at the rate of 5% for 5
units of time.
Example 2:
Input: P = 3000
R = 7
T = 1
Output: 210
Recommended PracticeSimple InterestTry It!

The formula to calculate the simple interest is:


simple_interest = (P * T * R) / 100
where P is the principal amount, T is time & R is the rate of interest.
Below is the implementation of the above example:
 C++

// C++ program to find simple interest

// for given principal amount, time

// and rate of interest.

#include<iostream>

using namespace std;

// Driver code

int main()

// We can change values here for

// different inputs

float P = 1, R = 1, T = 1;
// Calculate simple interest

float SI = (P * T * R) / 100;

// Print the resultant value of SI

cout << "Simple Interest = " << SI;

return 0;

Output:
Simple Interest: 0.01
Time complexity: O(1).
Auxiliary space: O(1).
C++ Program To Find Compound Interest


What is ‘Compound interest’?


Compound interest is the addition of interest to the principal sum of a loan or deposit, or
in other words, interest on interest. It is the result of reinvesting interest, rather than
paying it out, so that interest in the next period is then earned on the principal sum plus
previously-accumulated interest. Compound interest is standard in finance and
economics.
Compound interest may be contrasted with simple interest, where interest is not added to
the principal, so there is no compounding.
Compound Interest formula:
Formula to calculate compound interest annually is given by:

Amount= P(1 + R/100)t


Compound Interest = Amount - P
Where,
P is principal amount
R is the rate and
T is the time span
Pseudo Code:
Input principal amount. Store it in some variable say principal.
Input time in some variable say time.
Input rate in some variable say rate.
Calculate Amount using formula,
Amount = principal * (1 + rate / 100) time.
Calculate Compound Interest using Formula.
Finally, print the resultant value of CI.
Example:
Input: Principal (amount): 1200
Time: 2
Rate: 5.4
Output: Compound Interest = 133.099243

 C++

// C++ program to find compound interest

// for given values.

#include <bits/stdc++.h>

using namespace std;

// Driver code

int main()
{

double principal = 10000, rate = 5, time = 2;

// Calculate compound interest

double A = principal * ((pow((1 + rate / 100), time)));

double CI = A - principal;

cout << "Compound interest is " << CI;

return 0;

// This Code is Contributed by Sahil Rai.

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

// C++ program to find area

// and perimeter of rectangle

#include<iostream>

using namespace std;

// Utility function

int areaRectangle(int a, int b)

int area = a * b;

return area;

int perimeterRectangle(int a, int b)


{

int perimeter = 2*(a + b);

return perimeter;

// Driver code

int main()

int a = 5;

int b = 6;

cout << "Area = " <<

areaRectangle(a, b) <<

endl;

cout << "Perimeter = " <<

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.

C++ Control Flow Programs


C++ Program To Check Whether Number is
Even Or Odd


A number is even if it is completely divisible by 2 without leaving a remainder. A


number is odd if it is not completely divisible by 2 and leaves the remainder 1. In this
article, we will learn to write a C++ program to check whether a number is even or odd.
Algorithm to Check Even or Odd Numbers
The idea is to use the Modulo operator to find the remainder after dividing by 2.
 If the remainder is 0, print “Even”.
 If the remainder is 1, print “Odd”.
For example, 2, 4, 6, 8, … are even numbers, and 5, 7, 9, 11, … are odd numbers.
Recommended Practice – Odd Even Problem – Try It!

C++ Program To Check Whether Number is Even Or Odd


 C++

// C++ program to check

// for even or odd

#include <iostream>

using namespace std;

// Returns true if n is

// even, else odd

bool isEven(int n) { return (n % 2 == 0); }

// Driver code

int main()

int n = 101;
if (isEven(n))

cout << "Even";

else

cout << "Odd";

return 0;

Output
Odd

C++ Program to Find Largest Among Three


Numbers


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++ Program to Check Whether a Character is a Vowel or


Consonant
In this method, we check whether the given character matches any of the 5 vowels using
if-else statement. If yes, we print “Vowel”, else we print “Consonant”.

 C++

// C++ program to check if a given

// character is vowel or consonant.

#include <iostream>

using namespace std;

// Function to check whether a


// character is vowel or not

void vowelOrConsonant(char x)

if (x == 'a' || x == 'e' || x == 'i' || x


== 'o'

|| x == 'u' || x == 'A' || x == 'E'


|| x == 'I'

|| x == 'O' || x == 'U')

cout << "Vowel" << endl;

else

cout << "Consonant" << endl;

// Driver code

int main()

vowelOrConsonant('c');

vowelOrConsonant('E');

return 0;

}
Output
Consonant
Vowel

Complexity Analysis

 Time Complexity: O(1)


 Auxiliary Space: O(1)
Check Vowel or Consonant using find() Function
In the below C++ program, the find() function is used to search for the character in the
string containing vowel letters. If the character is found, the isVowel function return 1,
else it returns 0.

 C++

// C++ program to check vowel or consonant


using find()

// function

#include <iostream>

#include <string>

using namespace std;

int isVowel(char ch)

// Make the list of vowels


string str = "aeiouAEIOU";

return (str.find(ch) != string::npos);

// Driver code

int main()

if (isVowel('a'))

cout << "a is vowel" << endl;

else

cout << "a is consonant" << endl;

return 0;

Output
a is vowel

C++ Program to Check 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.

Algorithm to Check Leap Year


The algorithm implements the conditions specified above to check for leap year.
if (year % 400 = 0)
return true (Leap year)
else if (year % 100 = 0)
return false (Not a leap year)
else if (year % 4 = 0)
return true (Leap year)
else
return false (Not a leap year)
endif
Leap Year Program in C++
 C++

// C++ program to check if a given

// year is a leap year or not

#include <iostream>

using namespace std;

// Function to check leap year

bool checkYear(int year)


{

if (year % 400 == 0) {

return true;

// not a leap year if divisible by 100

// but not divisible by 400

else if (year % 100 == 0) {

return false;

// leap year if not divisible by 100

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

int year = 2000;

checkYear(year) ? cout << "Leap Year"

: cout << "Not a Leap


Year";

return 0;

Output
Leap Year

C++ Program to Check 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.

Algorithm to Check Leap Year


The algorithm implements the conditions specified above to check for leap year.
if (year % 400 = 0)
return true (Leap year)
else if (year % 100 = 0)
return false (Not a leap year)
else if (year % 4 = 0)
return true (Leap year)
else
return false (Not a leap year)
endif
Leap Year Program in C++
 C++

// C++ program to check if a given

// year is a leap year or not

#include <iostream>

using namespace std;

// Function to check leap year


bool checkYear(int year)

if (year % 400 == 0) {

return true;

// not a leap year if divisible by 100

// but not divisible by 400

else if (year % 100 == 0) {

return false;

// leap year if not divisible by 100

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

int year = 2000;

checkYear(year) ? cout << "Leap Year"

: cout << "Not a Leap


Year";

return 0;

Output
Leap Year
C++ Program To Print Multiplication Table of a
Number


A multiplication table shows a list of multiples of a particular number, from 1 to 10. In


this article, we will learn to generate and display the multiplication table of a number in
C++ programming language.

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

// C++ program to print table

// of a number

#include <iostream>

using namespace std;

// Driver code

int main()

// Change here to change output

int n = 5;

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

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

// C++ program to print table

// over a range

#include <iostream>

using namespace std;


// Driver code

int main()

// Change here to change

// input number

int n = 8;

// Change here to change result

int range = 11;

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

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

C++ Program To Find Sum of First N Natural


Numbers


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

// C++ program to find sum of first

// n natural numbers.

#include <iostream>

using namespace std;

// Returns sum of first n natural

// numbers

int findSum(int n)

int sum = 0;

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

sum = sum + i;

return sum;

}
// Driver code

int main()

int n = 5;

cout << findSum(n);

return 0;

Output
15

C++ Program To Find Factorial Of A Number




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

// C++ program to find factorial

// of given number
#include <iostream>

using namespace std;

// Function to find factorial of

// given number

unsigned int factorial(unsigned int n)

if (n == 0)

return 1;

return n * factorial(n - 1);

// Driver code

int main()

int num = 5;

cout << "Factorial of " << num << " is


"

<< factorial(num) << endl;


return 0;

Output
Factorial of 5 is 120

Reverse a Number in C++




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

// the above approach

#include <bits/stdc++.h>

using namespace std;

// Iterative function to

// reverse digits of num

int reverseDigits(int num)

int rev_num = 0;

while (num > 0) {

rev_num = rev_num * 10 + num % 10;

num = num / 10;

return rev_num;

// Driver code
int main()

int num = 4562;

cout << "Reverse of num is " <<


reverseDigits(num);

getchar();

return 0;

Output
Reverse of num is 2654

GCD of Two Numbers in C++




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!

1. GCD Using Simple Method


The idea is to find the minimum of the two numbers and then find the common divisor
starting from the minimum number and decrementing it by 1 until a common divisor is
found.
Algorithm

 Initialize a variable result with the minimum of a and b.


 Run a loop till the result > 0.
 If both numbers are divisible by the variable result, break the loop.
 Else, decrement the result variable by 1.
 After the loop, the result variable holds the GCD of the two numbers.
 Return the result variable.

C++ Program To Find GCD of Two Numbers Using Simple Method

 C++

// C++ program to find GCD of two numbers

#include <bits/stdc++.h>

using namespace std;

// Function to return gcd of a and b

int gcd(int a, int b)

// Find Minimum of a and b

int result = min(a, b);

while (result > 0) {

if (a % result == 0 && b % result


== 0) {

break;

result--;

// Return gcd of a and b

return result;

// Driver code

int main()

int a = 98, b = 56;

cout << "GCD of " << a << " and " << b
<< " is "

<< gcd(a, b);

return 0;

}
// This code is contributed by Suruchi
Kumari

Output
GCD of 98 and 56 is 14

2. GCD Using Euclidean Algorithm


The Euclidean algorithm is an efficient method to find the GCD of two numbers. It works
on the principle that the GCD of two numbers remains the same if the greater number is
replaced by the difference between the two numbers.

Algorithm

 Define a function that takes two integers to find their GCD.


 If a is equal to 0, then the GCD of a and b is b.
 If b is equal to 0, then the GCD of a and b is a.
 If a and b are equal, the GCD is a or b.
 If a > b, call the gcd function recursively with parameters (a – b, b).
 Else, call the gcd function recursively with parameters (a, b-a).

C++ Program to Find GCD of Two Numbers Using Euclidean Algorithm

 C++

// C++ program to find GCD

// of two numbers

#include <iostream>

using namespace std;


// Recursive function to return

// gcd of a and b

int gcd(int a, int 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)

return gcd(a - b, b);

return gcd(a, b - a);


}

// Driver code

int main()

int a = 98, b = 56;

cout << "GCD of " << a << " and " << b
<< " is "

<< gcd(a, b);

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

 Time Complexity: O(min(a,b))


 Auxiliary Space: O(min(a,b))
3. GCD Using Inbuilt Function in C++
In C++ Standard Library, there is an inbuilt function __gcd() in <algorithm> header file
to find the gcd of two numbers.

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

// CPP program to find gcd of two numbers


using inbuilt

// __gcd() function

// #include<numeric> for C++17

#include <algorithm>

#include <iostream>

using namespace std;


int main()

cout << "gcd(10, 20) = " << __gcd(10,


20) << endl;

Output
gcd(10, 20) = 10

C++ Program To Find LCM of Two Numbers




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++ Program To Find LCM of Two Numbers using Simple Method

 C++

// C++ program to find the LCM of two

// numbers using the if statement and

// while loop

#include <iostream>

using namespace std;

// Driver code

int main()

int a = 15, b = 20, max_num, flag = 1;


// Use ternary operator to get the

// large number

max_num = (a > b) ? a : b;

while (flag) {

// if statement checks max_num is


completely

// divisible by n1 and n2.

if (max_num % a == 0 && max_num % b


== 0) {

cout << "LCM of " << a << " and


" << b << " is "

<< max_num;

break;

// update by 1 on each iteration

++max_num;

return 0;
}

Output
LCM of 15 and 20 is 60

Complexity Analysis

 Time complexity: O(a*b)


 Auxiliary space: O(1)
2. LCM of Two Numbers Using Built-In std::lcm() Function
C++ has an inbuilt function lcm() to find the lcm of the two numbers. It is defined in
<numeric> header file.

Syntax

lcm(num1, num2);
where num1 and num2 are the two numbers.
Note: This function is only available since C++17.

C++ Program to Find LCM Using std::lcm() Function

 C++

// CPP program to illustrate how to find


lcm of two numbers

// using std::lcm function

#include <iostream>

#include <numeric>
using namespace std;

int main()

cout << "LCM(10,20) = " << lcm(10, 20)


<< endl;

return 0;

Output
LCM(10,20) = 20

Complexity Analysis

 Time complexity: O(log(min(a, b)))


 Auxiliary space: O(1)
3. LCM of Two Numbers Using GCD
An efficient solution is based on the below formula for LCM of two numbers ‘a’ and ‘b’.
a x b = LCM(a, b) * GCD (a, b)
LCM(a, b) = (a x b) / GCD(a, b)
We have discussed the function to find the GCD of two numbers. Using GCD, we can
find LCM.

C++ Program to Find LCM Using GCD

 C++
// C++ program to find LCM

// of two numbers

#include <iostream>

using namespace std;

// Recursive function to return

// gcd of a and b

long long gcd(long long int a, long long int b)

if (b == 0)

return a;

return gcd(b, a % b);

// Function to return LCM of

// two numbers

long long lcm(int a, int b) { return (a /


gcd(a, b)) * b; }
// Driver code

int main()

int a = 15, b = 20;

cout << "LCM of " << a << " and " << b
<< " is "

<< lcm(a, b);

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

// A recursive C++ program to check


// whether a given number is

// palindrome or not

#include <iostream>

using namespace std;

// A function that returns true

// only if num contains one

// digit

int oneDigit(int num)

// Comparison operation is faster

// than division operation.

// So using following instead

// of "return num

return (num >= 0 && num < 10);

}
// A recursive function to find

// out whether num is palindrome

// or not. Initially, dupNum

// contains address of a

// copy of num.

bool isPalUtil(int num, int* dupNum)

// Base case (needed for recursion

// termination): This statement

// mainly compares the first

// digit with the last digit

if (oneDigit(num))

return (num == (*dupNum) % 10);

// This is the key line in this

// method. Note that all recursive

// calls have a separate copy of num,

// but they all share same copy of


// *dupNum. We divide num while

// moving up the recursion tree

if (!isPalUtil(num / 10, dupNum))

return false;

// The following statements are

// executed when we move up

// the recursion call tree

*dupNum /= 10;

// At this point, if num%10 contains

// i'th digit from beginning, then

// (*dupNum)%10 contains i'th digit

// from end

return (num % 10 == (*dupNum) % 10);

// The main function that uses


// recursive function isPalUtil()

// to find out whether num is

// palindrome or not

int isPal(int num)

// Check if num is negative,

// make it positive

if (num < 0)

num = -num;

// Create a separate copy of num,

// so that modifications made to

// address dupNum don't change

// the input number.

int* dupNum = new int(num);

return isPalUtil(num, dupNum);


}

// Driver code

int main()

int n = 12321;

isPal(n) ? cout << "Yes":

cout << "No" << endl;

n = 12;

isPal(n) ? cout << "Yes":

cout << "No" << endl;

n = 88;

isPal(n) ? cout << "Yes":

cout << "No" << endl;

n = 8999;
isPal(n) ? cout << "Yes":

cout << "No";

return 0;

// This code is contributed by


shivanisinghss2110

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

// A school method based C++ program

// to check if a number is prime

#include <bits/stdc++.h>

using namespace std;


bool isPrime(int n)

// Corner case

if (n <= 1)

return false;

// Check from 2 to n-1

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

if (n % i == 0)

return false;

return true;

// Driver code

int main()

isPrime(11) ? cout << " true\n" : cout


<< " false\n";
isPrime(15) ? cout << " true\n" : cout
<< " false\n";

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

1. Using For Loop

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

// C++ program to find the


// prime numbers between a

// given interval

#include <bits/stdc++.h>

using namespace std;

// Driver code

int main()

// Declare the variables

int a, b, i, j, flag;

// Ask user to enter lower value

// of interval

cout << "Enter lower bound of the


interval: ";

// Take input

cin >> a;
// Ask user to enter upper value

// of interval

cout << "Enter upper bound of the


interval: ";

// Take input

cin >> b;

// Print display message

cout << "Prime numbers between " << a


<< " and " << b

<< " are: ";

// Traverse each number in the interval

// with the help of for loop

for (i = a; i <= b; i++) {

// Skip 0 and 1 as they are

// neither prime nor composite


if (i == 1 || i == 0)

continue;

// flag variable to tell

// if i is prime or not

flag = 1;

for (j = 2; j <= i / 2; ++j) {

if (i % j == 0) {

flag = 0;

break;

// flag = 1 means i is prime

// and flag = 0 means i is not


prime

if (flag == 1)

cout << i << " ";


}

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

// C++ program to find the prime numbers

// between a given interval

#include <bits/stdc++.h>

using namespace std;


// Driver code

int main()

// Declare the variables

int a, b, i, j;

// Ask user to enter lower value of

// interval please not interval < 0

// cannot be prime numbers

cout << "Enter lower bound of the


interval: ";

// Take input

cin >> a;

// Ask user to enter upper value

// of interval

cout << "Enter upper bound of the


interval: ";
// Take input

cin >> b;

// Print display message

cout << "Prime numbers between " << a


<< " and " << b

<< " are: ";

// Explicitly handling the cases

// when a is less than 2 since 0

// and 1 are not prime numbers

if (a <= 2) {

a = 2;

if (b >= 2) {

cout << a << " ";

a++;

}
// Making sure that a is odd before

// beginning the loop

if (a % 2 == 0)

a++;

// NOTE : We traverse through

// odd numbers only

for (i = a; i <= b; i = i + 2) {

// flag variable to tell

// if i is prime or not

bool flag = 1;

// We traverse till square root of


j only.

// (Largest possible value of prime


factor)

for (j = 2; j * j <= i; ++j) {

if (i % j == 0) {
flag = 0;

break;

// flag = 1 means i is prime

// and flag = 0 means i is

// not prime

if (flag == 1) {

if (i == 1)

continue;

else

cout << i << " ";

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

3. Sieve of Eratosthenes Method

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

// C++ program to find the prime numbers

// between a given interval using Sieve of


Eratosthenes

#include <bits/stdc++.h>

using namespace std;

void SieveOfEratosthenes(int srt, int n)

// Create a boolean array "prime[srt to


n]" and

// initialize all entries it as true. A


value in

// prime[i] will finally be false if i


is Not a prime,

// else true.

bool prime[n + 2 - srt];

memset(prime, true, sizeof(prime));

prime[0] = false;

prime[1] = false;

for (int p = srt; p * p <= n; p++)

// If prime[p] is not changed, then


it is a prime

if (prime[p] == true)

// Update all multiples of p


greater than or

// equal to the square of it


numbers which are

// multiple of p and are less


than p^2 are

// already been marked.

for (int i = p * p; i <= n; i +=


p)

prime[i] = false;

// Print all prime numbers

for (int p = srt; p <= n; p++)

if (prime[p])

cout << p << " ";

// Driver Code

int main()

int srt = 1;

int end = 10;


SieveOfEratosthenes(srt, end);

return 0;

Output
2 3 5 7

C++ Program To Check And Print Neon


Number in a Given Range


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

// C++ program to check and print


// Neon Numbers upto 10000

#include <iostream>

using namespace std;

#include <math.h>

int checkNeon(int x)

// Storing the square of x

int sq = x * x;

// Calculating the sum of

// digits of sq

int sum_digits = 0;

while (sq != 0)

sum_digits = sum_digits + sq % 10;

sq = sq / 10;

}
return (sum_digits == x);

// Driver Code

int main(void)

// Printing Neon Numbers upto 10000

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

if (checkNeon(i))

cout << i << " ";

Output:
1 9

C++ Program To Check Armstrong Number




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!

Methods to Check Armstrong Number


There are certain methods to check if a number is mentioned below:

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

// C++ program to determine whether

// the number is Armstrong number

// or not

#include <bits/stdc++.h>

using namespace std;


// Function to calculate x

// raised to the power y

int power(int x, unsigned int y)

if (y == 0)

return 1;

if (y % 2 == 0)

return (power(x, y / 2) * power(x,


y / 2));

return (x * power(x, y / 2) * power(x,


y / 2));

// Function to calculate

// order of the number

int order(int x)

int n = 0;
while (x) {

n++;

x = x / 10;

return n;

// Function to check whether the

// given number is Armstrong number

// or not

bool isArmstrong(int x)

// Calling order function

int n = order(x);

int temp = x, sum = 0;

while (temp) {

int r = temp % 10;


sum += power(r, n);

temp = temp / 10;

// If satisfies Armstrong

// condition

return (sum == x);

// Driver code

int main()

int x = 153;

cout << boolalpha << isArmstrong(x) <<


endl;

x = 1253;

cout << boolalpha << isArmstrong(x) <<


endl;
return 0;

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

The above approach can also be implemented in a shorter way:

 C++

// C++ program to implement

// the above approach

#include <iostream>

using namespace std;

// Driver code

int main()
{

int n = 153;

int temp = n;

int p = 0;

// Function to calculate

// the sum of individual digits

while (n > 0) {

int rem = n % 10;

p = (p) + (rem * rem * rem);

n = n / 10;

// Condition to check whether

// the value of P equals

// to user input or not.

if (temp == p) {

cout << ("Yes. It is Armstrong


No.");
}

else {

cout << ("No. It is not an


Armstrong No.");

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

// C++ Program to find Nth

// Armstrong Number
#include <bits/stdc++.h>

#include <math.h>

using namespace std;

// Function to find Nth

// Armstrong Number

int NthArmstrong(int n)

int count = 0;

// Upper limit from integer

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

int num = i, rem, digit = 0, sum =


0;

// Copy the value for num in num

num = i;

// Find total digits in num


digit = (int)log10(num) + 1;

// Calculate sum of power of digits

while (num > 0) {

rem = num % 10;

sum = sum + pow(rem, digit);

num = num / 10;

// Check for Armstrong number

if (i == sum)

count++;

if (count == n)

return i;

// Driver code

int main()
{

int n = 12;

cout << NthArmstrong(n);

return 0;

Output:
371

C++ Program to Print Armstrong Numbers


Between 1 to 1000


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.

1. Using Brute-force Approach


The idea is to first count the number of digits (or find order). Let the number of digits
be order_n. For every digit curr in input number num, compute currorder_n. If the sum of all
such values is equal to num, then return true, else false.
Below is the C++ program to find Armstrong numbers between 1 to 1000 using a brute
force approach:

 C++

// C++ program to find Armstrong numbers

// between 1 to 1000 using a brute force

// approach

#include <bits/stdc++.h>

using namespace std;

// Function to return the order of

// a number.

int order(int num)

int count = 0;
while (num > 0)

num /= 10;

count++;

return count;

// Function to check whether the

// given number is Armstrong number

// or not

bool isArmstrong(int num)

int order_n = order(num);

int num_temp = num, sum = 0;

while (num_temp > 0)

{
int curr = num_temp % 10;

sum += pow(curr, order_n);

num_temp /= 10;

if (sum == num)

return true;

else

return false;

// Driver code

int main()

cout << "Armstrong numbers between 1 to


1000 : ";

// Loop which will run from 1 to 1000

for (int num = 1; num <= 1000; ++num)

if (isArmstrong(num))

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

// C++ program to find Armstrong numbers

// between 1 to 1000 using an optimized

// solution

#include <bits/stdc++.h>

using namespace std;

// Driver code

int main()

int ord1, ord2, ord3, total_sum;

cout << "All the Armstrong numbers


between 1 to 1000 : ";

// Loop which will run from 1 to 1000

for (int num = 1; num <= 1000; ++num)

// All the single-digit numbers are


// armstrong number.

if (num <= 9)

cout << num << " ";

else

ord1 = num % 10;

ord2 = (num % 100 - ord1) / 10;

ord3 = (num % 1000 - ord2) /


100;

total_sum = ((ord1 * ord1 *


ord1) +

(ord2 * ord2 *
ord2) +

(ord3 * ord3 *
ord3));

if (total_sum == num)

cout << num << " ";


}

return 0;

All the Armstrong numbers between 1 to 1000 : 1 2 3 4 5 6 7 8 9 153


370 371 407

C++ Program For Fibonacci Numbers




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

Rohan’s Love for Matrix


Try It!
Write a function int fib(int n) that returns Fn. For example, if n = 0, then fib() should
return 0. If n = 1, then it should return 1. For n > 1, it should return Fn-1 + Fn-2
For n = 9
Output:34
The following are different methods to get the nth Fibonacci number.
Method 1 (Use recursion)
A simple method that is a direct recursive implementation mathematical recurrence
relation is given above.
 C++

// Fibonacci Series using Recursion

#include <bits/stdc++.h>

using namespace std;

int fib(int n)

if (n <= 1)

return n;

return fib(n - 1) + fib(n - 2);

int main()
{

int n = 9;

cout << fib(n);

getchar();

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program for Fibonacci Series

// using Dynamic Programming

#include<bits/stdc++.h>

using namespace std;

class GFG{

public:

int fib(int n)

// Declare an array to store


// Fibonacci numbers.

// 1 extra to handle

// case, n = 0

int f[n + 2];

int i;

// 0th and 1st number of the

// series are 0 and 1

f[0] = 0;

f[1] = 1;

for(i = 2; i <= n; i++)

//Add the previous 2 numbers

// in the series and store it

f[i] = f[i - 1] + f[i - 2];

}
return f[n];

};

// Driver code

int main ()

GFG g;

int n = 9;

cout << g.fib(n);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// Fibonacci Series using Space Optimized


Method

#include<bits/stdc++.h>

using namespace std;

int fib(int n)

int a = 0, b = 1, c, i;

if( n == 0)

return a;

for(i = 2; i <= n; i++)

c = a + b;

a = b;

b = c;

return b;
}

// Driver code

int main()

int n = 9;

cout << fib(n);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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>

using namespace std;

// Helper function that multiplies 2

// matrices F and M of size 2*2, and

// puts the multiplication result

// back to F[][]

void multiply(int F[2][2], int M[2][2]);

// Helper function that calculates F[][]

// raise to the power n and puts the

// result in F[][]

// Note that this function is designed

// only for fib() and won't work as

// general power function

void power(int F[2][2], int n);


int fib(int n)

int F[2][2] = { { 1, 1 }, { 1, 0 } };

if (n == 0)

return 0;

power(F, n - 1);

return F[0][0];

void multiply(int F[2][2], int M[2][2])

int x = F[0][0] * M[0][0] +

F[0][1] * M[1][0];

int y = F[0][0] * M[0][1] +

F[0][1] * M[1][1];
int z = F[1][0] * M[0][0] +

F[1][1] * M[1][0];

int w = F[1][0] * M[0][1] +

F[1][1] * M[1][1];

F[0][0] = x;

F[0][1] = y;

F[1][0] = z;

F[1][1] = w;

void power(int F[2][2], int n)

int i;

int M[2][2] = { { 1, 1 }, { 1, 0 } };

// n - 1 times multiply the

// matrix to {{1,0},{0,1}}
for(i = 2; i <= n; i++)

multiply(F, M);

// Driver code

int main()

int n = 9;

cout << " " << fib(n);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
34
Time Complexity: O(n)
Extra Space: O(1)

Method 5: (Optimized Method 4)


Method 4 can be optimized to work in O(Logn) time complexity. We can do recursive
multiplication to get power(M, n) in the previous method (Similar to the optimization
done in this post)
 C++

// Fibonacci Series using Optimized Method

#include <bits/stdc++.h>

using namespace std;

void multiply(int F[2][2], int M[2][2]);

void power(int F[2][2], int n);

// Function that returns nth Fibonacci


number

int fib(int n)

int F[2][2] = {{1, 1}, {1, 0}};

if (n == 0)

return 0;

power(F, n - 1);
return F[0][0];

// Optimized version of power() in method 4

void power(int F[2][2], int n)

if(n == 0 || n == 1)

return;

int M[2][2] = {{1, 1}, {1, 0}};

power(F, n / 2);

multiply(F, F);

if (n % 2 != 0)

multiply(F, M);

void multiply(int F[2][2], int M[2][2])


{

int x = F[0][0] * M[0][0] + F[0][1] *


M[1][0];

int y = F[0][0] * M[0][1] + F[0][1] *


M[1][1];

int z = F[1][0] * M[0][0] + F[1][1] *


M[1][0];

int w = F[1][0] * M[0][1] + F[1][1] *


M[1][1];

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;

Learn Data Structures & Algorithms with GeeksforGeeks

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)

If n is odd then k = (n + 1)/2


F(n) = F(k)*F(k) + F(k-1)*F(k-1)
How does this formula work?
The formula can be derived from the above matrix equation.

Taking determinant on both sides, we get

(-1)n = Fn+1Fn-1 - Fn2


Moreover, since AnAm = An+m for any square matrix A,
the following identities can be derived (they are obtained
from two different coefficients of the matrix product)

FmFn + Fm-1Fn-1 = Fm+n-1 ---------------------------(1)

By putting n = n+1 in equation(1),


FmFn+1 + Fm-1Fn = Fm+n --------------------------(2)

Putting m = n in equation(1).
F2n-1 = Fn2 + Fn-12
Putting m = n in equation(2)

F2n = (Fn-1 + Fn+1)Fn = (2Fn-1 + Fn)Fn (Source: Wiki) --------


( By putting Fn+1 = Fn + Fn-1 )
To get the formula to be proved, we simply need to do the following
If n is even, we can put k = n/2
If n is odd, we can put k = (n+1)/2
Below is the implementation of the above idea.

 C++

// C++ Program to find n'th fibonacci


Number in

// with O(Log n) arithmetic operations

#include <bits/stdc++.h>

using namespace std;

const int MAX = 1000;

// Create an array for memoization


int f[MAX] = {0};

// Returns n'th fibonacci number using


table f[]

int fib(int n)

// Base cases

if (n == 0)

return 0;

if (n == 1 || n == 2)

return (f[n] = 1);

// If fib(n) is already computed

if (f[n])

return f[n];

int k = (n & 1)? (n+1)/2 : n/2;

// Applying above formula [Note value


n&1 is 1

// if n is odd, else 0.

f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-


1)*fib(k-1))

: (2*fib(k-1) + fib(k))*fib(k);

return f[n];

// Driver program to test above function

int main()

int n = 9;

printf("%d ", fib(n));

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ Program to find n'th fibonacci


Number

#include<iostream>

#include<cmath>

int fib(int n) {

double phi = (1 + sqrt(5)) / 2;

return round(pow(phi, n) / sqrt(5));

// Driver Code

int main ()

{
int n = 9;

std::cout << fib(n) << std::endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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>

using namespace std;

int dp[10];

int fib(int n)

if (n <= 1)
return n;

// temporary variables to store

// values of fib(n-1) & fib(n-2)

int first, second;

if (dp[n - 1] != -1)

first = dp[n - 1];

else

first = fib(n - 1);

if (dp[n - 2] != -1)

second = dp[n - 2];

else

second = fib(n - 2);

// memoization

return dp[n] = first + second;


}

// Driver Code

int main()

int n = 9;

memset(dp, -1, sizeof(dp));

cout << fib(n);

getchar();

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ Program to find sum of

// even-indiced Fibonacci numbers

#include <bits/stdc++.h>

using namespace std;


// Computes value of first

// fibonacci numbers and

// stores the even-indexed sum

int calculateEvenSum(int n)

if (n <= 0)

return 0;

int fibo[2 * n + 1];

fibo[0] = 0, fibo[1] = 1;

// Initialize result

int sum = 0;

// Add remaining terms

for (int i = 2; i <= 2 * n; i++)

fibo[i] = fibo[i - 1] + fibo[i -


2];
// For even indices

if (i % 2 == 0)

sum += fibo[i];

// Return the alternating sum

return sum;

// Driver code

int main()

// Get n

int n = 8;

// Find the even-indiced sum


cout << "Even indexed Fibonacci Sum
upto " <<

n << " terms: " <<


calculateEvenSum(n) <<

endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// Fibonacci Sum in O(Log n) time.

#include <bits/stdc++.h>

using namespace std;

const int MAX = 1000;

// Create an array for memoization

int f[MAX] = { 0 };

// Returns n'th Fibonacci number

// using table f[]

int fib(int n)

// Base cases

if (n == 0)

return 0;

if (n == 1 || n == 2)
return (f[n] = 1);

// If fib(n) is already computed

if (f[n])

return f[n];

int k = ((n & 1) ? (n + 1) / 2 :

n / 2);

// Applying above formula [Note value

// n&1 is 1 if n is odd, else 0].

f[n] = (n & 1) ? (fib(k) * fib(k) +

fib(k - 1) * fib(k -
1)) :

(2 * fib(k - 1) +
fib(k)) *

fib(k);

return f[n];
}

// Computes value of even-indexed

// Fibonacci Sum

int calculateEvenSum(int n)

return (fib(2 * n + 1) - 1);

// Driver code

int main()

// Get n

int n = 8;

// Find the alternating sum

cout << "Even indexed Fibonacci Sum


upto " <<

n << " terms: " <<


calculateEvenSum(n) <<

endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
Even indexed Fibonacci Sum upto 8 terms: 1596

Power Function in C/C++




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

double x = 6.1, y = 4.8;

// Storing the answer in result.

double result = pow(x, y);

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.

Example 1: C/C++ Program to demonstrate the behavior of the pow()


function with integers.

 C++
 C

// C++ program to illustrate

// working with integers in

// power function

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

int main()

int a, b;

// Using typecasting for

// integer result

a = (int)(pow(5, 2) + 0.5);

b = round(pow(5,2));

cout << a << endl << b ;

return 0;

Output
25
25

C++ Program To Find All Factors of A Natural


Number



Given a natural number n, print all distinct divisors of it.

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

Count Numbers In Range


Try It!

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

// C++ implementation of Naive

// method to print all divisors

#include <iostream>

using namespace std;

// Function to print the divisors

void printDivisors(int n)

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

if (n % i == 0)

cout <<" " << i;

// Driver code

int main()
{

cout <<"The divisors of 100 are: ";

printDivisors(100);

return 0;

// This code is contributed by


shivanisinghss2110

Learn Data Structures & Algorithms with GeeksforGeeks

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

// A Better (than Naive) Solution

// to find all divisors


#include <iostream>

#include <math.h>

using namespace std;

// Function to print the divisors

void printDivisors(int n)

// Note that this loop runs

// till square root

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

if (n % i == 0)

// If divisors are equal,

// print only one

if (n / i == i)

cout <<" "<< i;


// Otherwise print both

else

cout << " "<< i << " " << n


/ i;

// Driver code

int main()

cout <<"The divisors of 100 are: ";

printDivisors(100);

return 0;

// This code is contributed by


shivanisinghss2110

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
The divisors of 100 are:
1 100 2 50 4 25 5 20 10

C++ Program to Make a Simple Calculator




A simple calculator is a device used to perform basic arithmetic operations such as


addition, subtraction, multiplication, and division. It makes arithmetic calculations easier
and faster. In this article, we will learn how to code a simple calculator using C++.
Algorithm to Make a Simple Calculator
 Initialize two float variables num1 and num2 to take two operands as input.
 Initialize a char variable op to take the operator as input.
 Start the switch statement with op as the expression of the switch statement.
 Now, create cases for different arithmetic operations.
 ‘+’ for addition
 ‘-‘ for subtraction
 ‘*’ for multiplication
 ‘/’ for division
 Default case for the case when the entered operator is not one of the above
operators.
 The operation will be performed based on the operator entered as the input.
C++ Program to Implement a Simple Calculator
Below is the C++ program to make a simple calculator using switch and break
statements:

 C++

// C++ program to create calculator using

// switch statement

#include <iostream>

using namespace std;

// Driver code

int main()

char op;

float num1, num2;


// It allows user to enter operator

// i.e. +, -, *, /

cin >> op;

// It allow user to enter the operands

cin >> num1 >> num2;

// Switch statement begins

switch (op) {

// If user enter +

case '+':

cout << num1 + num2;

break;

// If user enter -

case '-':

cout << num1 - num2;


break;

// If user enter *

case '*':

cout << num1 * num2;

break;

// If user enter /

case '/':

cout << num1 / num2;

break;

// If the operator is other than +, -,


* or /,

// error message will display

default:

cout << "Error! operator is not


correct";

}
// switch statement ends

return 0;

Input
+
2
2
Output
4

Complexity Analysis

Time Complexity: O(1)


Auxiliary Space: O(1)
C++ Pattern Printing Programs
C++ Program To Print Right Half Pyramid
Pattern


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

1. Using for loop


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

// C++ Program To Print Right Half

// Pyramid Pattern using for loop

#include <iostream>

using namespace std;

int main()

int rows = 5;

// first for loop is used to identify


number of rows

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

// second for loop is used to


identify number of

// columns and here the values will


be changed

// according to the first for loop

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

// printing the required


pattern

cout << "* ";

cout << "\n";

return 0;

Output
*
* *
* * *
* * * *
* * * * *
Time complexity: O(n2)
Here n is number of rows.
Space complexity: O(1)
As constant extra space is used.

2. Using while loop


The while loops check the condition until the condition is false. If condition is true then
enters in to loop and execute the statements.

 C++

// C++ Program To Print Right Half

// Pyramid Pattern using while loop

#include <iostream>

using namespace std;

int main()

int i = 0, j = 0;

int rows = 5;

// while loop check the condition until


the given

// condition is false if it is true


then enteres in to
// the loop

while (i < rows) {

// this loop will print the pattern

while (j <= i) {

cout << "* ";

j++;

j = 0;

i++;

cout << "\n";

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

// C++ program to print 180 degree rotation


of simple

// pyramid pattern using for loop

#include <iostream>

using namespace std;


int main()

int rows = 5;

// first for loop is used to identify


number of rows

for (int i = rows; i > 0; i--) {

// second for loop is used to


identify number of

// columns and here the values will


be changed

// according to the first for loop

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

// if j is greater than i then


it will print

// the output otherwise print


the space
if (j >= i) {

cout << "*";

else {

cout << " ";

cout << "\n";

return 0;

Output
*
**
***
****
*****
Time complexity: O(n2)
Here n is number of rows.
Auxiliary Space: O(1)
As constant extra space is used.

2. Using while loop


Input:
rows = 5
Output:
*
**
***
****
*****
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++

// C++ program to print 180 degree rotation


of simple

// pyramid pattern using while loop

#include <iostream>

using namespace std;

int main()

int i = 0, j = 0, sp = 0;

int rows = 5;

// while loop check the condition until


the given

// condition is false if it is true


then enteres in to

// the loop

while (i < rows) {

// second while loop is used for


printing spaces

while (sp < (rows - i - 1)) {

cout << " ";

sp++;

// assigning sp value as 0 because


we need to run sp

// from starting

sp = 0;

// this loop will print the pattern


while (j <= i) {

cout << "* ";

j++;

j = 0;

i++;

cout << "\n";

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

// C++ program to print number patterns


using for loop

#include <iostream>

using namespace std;

int main()

int rows, columns, number = 1, n = 5;

// first for loop is used to identify


number of rows

for (rows = 0; rows <= n; rows++) {

// second for loop is used to


identify number of

// columns and here the values will


be changed
// according to the first for loop

for (columns = 0; columns < rows;


columns++) {

// printing number pattern


based on the number

// of columns

cout << number << " ";

// incrementing number at each


column to print

// the next number

number++;

// print the next line for each row

cout << "\n";

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)

Using while loop:

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

// C++ program to print number

// patterns using while loop

#include <iostream>

using namespace std;

int main()

int rows = 1, columns = 0, n = 5;


// 1 value is assigned to the number

// helpful to print the number pattern

int number = 1;

// while loops check the condition and


repeat

// the loop until the condition is


false

while (rows <= n) {

while (columns <= rows - 1) {

// printing number to get


required pattern

cout << number << " ";

// incrementing columns value

columns++;

// incrementing number value to

// print the next number


number++;

columns = 0;

// incrementing rows value

rows++;

cout << endl;

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

// C++ program to print number

// patterns using for loop

#include <iostream>

using namespace std;

int main()

int rows, columns, n = 5;

// first for loop is used to

// identify number of rows

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

// second for loop is used to


identify number of

// columns and here the values will


be changed

// according to the first for loop

for (columns = 1; columns <= rows;


columns++) {

// printing number pattern


based on the number

// of rows

cout << rows << " ";

// print the next line for each row

cout << "\n";

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)

Using while loop:

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

// C++ program to print number

// patterns using while loop

#include <iostream>

using namespace std;

int main()

int rows = 1, columns = 0, n = 5;

// while loops check the condition and


repeat

// the loop until the condition is


false

while (rows <= n) {


while (columns <= rows - 1) {

// printing number to get


required pattern

cout << rows << " ";

// incrementing columns value

columns++;

columns = 0;

// incrementing rows value

rows++;

cout << endl;

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

// C++ program to print number

// patterns using for loop

#include <iostream>

using namespace std;

int main()

{
int rows, columns, n = 5;

// second for loop is used to identify


number of rows

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

// second for loop is used to


identify number of

// columns and here the values will


be changed

// according to the first for loop

for (columns = 1; columns <= rows;


columns++) {

// print the number to be print


based on the

// number of columns

cout << columns << " ";

// print the next line

cout << "\n";


}

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)

Using while loop:

The while loops check the condition until the condition is false. If condition is true then
enter into loop and execute the statements.

 C++

// C++ program to print number

// patterns using while loop

#include <iostream>

using namespace std;


int main()

int rows = 1, columns = 1, n = 6;

int number = 1;

// while loops check the condition and


repeat

// the loop until the condition is


false

while (rows <= n) {

while (columns <= rows - 1) {

// printing number to get


required pattern

cout << columns << " ";

// incrementing columns value

columns++;

}
columns = 1;

// incrementing rows value

rows++;

cout << endl;

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

// C++ program to demonstrate

// inverted half triangle using *

using namespace std;

#include <bits/stdc++.h>

#include <iostream>

int main()

int n = 4;

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

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

cout << "* ";


}

cout << endl;

return 0;

Output
* * * *
* * *
* *
*
Time complexity: O(n2)
Here n is number of rows.
Space complexity: O(1)
As constant extra space is used.

2. Program to print an inverted half pyramid using numbers


Input
n=4
Output:
1 2 3 4
1 2 3
1 2
1
By looking at the given example we can try to run the outer for loop from n to 1 and for
each row traversal, we should print the elements from 1 to the row number. This means
instead of printing * we need to print that specific column number.
Example:
 C++

// C++ program to demonstrate

// inverted half triangle using Digits

using namespace std;

#include <bits/stdc++.h>

#include <iostream>

int main()

int n=4; // took a default value

for (int i = n; i >= 1; --i) { // loop


for iterating

for (int j = 1; j <= i; ++j) { //


loop for printing

cout << j << " ";

cout << endl;

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.

3. Program to print inverted full pyramid using ” * “


Input:
n = 4
Output:
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Example:
 C++

// C++ program to demonstrate

// inverted pyramid using *

using namespace std;

#include <bits/stdc++.h>

#include <iostream>

int main()

{
int n=5;

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

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

cout << " ";

for (int j = i; j <= 2 * i - 1; ++j)


{

cout << "* ";

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

cout << "* ";

cout << endl;

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>

using namespace std;

// Driver code

int main()

int n = 5;

// ith row has i elements

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

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

cout << "* ";

cout << endl;

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

// C++ program to print inverted

// right triangle

#include <iostream>
using namespace std;

// Driver code

int main()

int n = 5;

// ith row has n-i+1 elements

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

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

cout << "* ";

cout << endl;

return 0;

Output
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Another Approach:
 C++

// Another C++ Approach for printing

// Inverted Right Triangle

#include <bits/stdc++.h>

using namespace std;

// similar to right triangle's code

int main()

int n = 5;

// start printing from the last row,


i.e., nth row

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

for (int j = i; j >= 1; j--)

cout << "* ";

cout << endl;

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

// C++ program to print


// equilateral triangle

#include <iostream>

using namespace std;

// Driver code

int main()

int n = 5;

// ith row has n-i leading spaces

// and i elements

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

// n-i leading spaces

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

cout << " ";

// i elements
for (int j = 1; j <= i; j++)

cout << "* ";

cout << endl;

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

// C++ program to print an

// inverted equilateral triangle

#include <iostream>

using namespace std;

// Driver code

int main()

int n = 5;

// ith row has n-i+1 elements

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

// leading spaces

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


cout << " ";

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

cout << "* ";

cout << endl;

return 0;

Output
* * * * *
* * * *
* * *
* *
*
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Another Approach:
 C++

#include <bits/stdc++.h>

using namespace std;

// similar to the equilateral triangle code

int main()
{

int n = 5;

// start printing from the last row,


i.e., nth row

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

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

cout << " ";

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

cout << "* ";

cout << endl;

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

// C++ program to print a

// inverted mirrored right triangle

#include <iostream>

using namespace std;

// Driver code

int main()

int n = 5;
// ith row has n-i+1 elements

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

// leading spaces

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

cout << " ";

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

cout << "* ";

cout << endl;

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

// C++ program to print number pattern

// without re assigning using for loop

#include <iostream>

using namespace std;


int main()

int rows, columns, number = 1, n = 5;

// first for loop is used to identify


number of rows

for (rows = 0; rows <= n; rows++) {

// second for loop is used to


identify number of

// columns and here the values will


be changed

// according to the first for loop

for (columns = 0; columns < rows;


columns++) {

// printing number pattern


based on the number

// of columns

cout << number << " ";


// incrementing number at each
column to print

// the next number

number++;

// print the next line for each row

cout << "\n";

return 0;

Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

2. Using while loop


Input:
n = 5
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
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++

// C++ program to print number without

// reassigning patterns using while loop

#include <iostream>

using namespace std;

int main()

int rows = 1, columns = 0, n = 5;

// 1 value is assigned to the number

// helpful to print the number pattern

int number = 1;

// while loops check the condition and


repeat

// the loop until the condition is


false

while (rows <= n) {

while (columns <= rows - 1) {

// printing number to get


required pattern

cout << number << " ";

// incrementing columns value

columns++;

// incrementing number value to


print the next

// number

number++;

columns = 0;
// incrementing rows value

rows++;

cout << endl;

return 0;

Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

C++ Program To Print Character Pattern




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.

1. Using for loop


Input:
rows = 5
Output:
A
B B
C C C
D D D D
E E E E E
Approach 1:
Assign any character 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. Then print the character based on the number of columns.

 C++

// C++ program to print character

// pattern using character

#include <iostream>

using namespace std;

int main()

int i, j;

// input entering number of rows

int rows = 5;
// taking first character of alphabet

// which is useful to print pattern

char character = 'A';

// first for loop is used to identify


number rows

for (i = 0; i < rows; i++) {

// second for loop is used to


identify number

// of columns based on the rows

for (j = 0; j <= i; j++) {

// printing character to get


the required

// pattern

cout << character << " ";

cout << "\n";


// incrementing character value so
that it

// will print the next character

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

// C++ program to print character pattern


by

// converting number in to character


#include <iostream>

using namespace std;

int main()

int i, j;

// input entering number of rows

int rows = 5;

// given a number

int number = 65;

// first for loop is used to identify


number rows

for (i = 0; i < rows; i++) {

// second for loop is used to


identify number
// of columns based on the rows

for (j = 0; j <= i; j++) {

// converting number in to
character

char character = char(number);

// printing character to get


the required

// pattern

cout << character << " ";

cout << "\n";

// incrementing number value so


that it

// will print the next character

number++;

return 0;
}

Output
A
B B
C C C
D D D D
E E E E E

2. Using while loops


Input:
rows = 5
Output:
A
B B
C C C
D D D D
E E E E E
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++

// C++ program to print character pattern


by

// converting number in to character

#include <iostream>

using namespace std;


int main()

int i = 1, j = 0;

// input entering number of rows

int rows = 5;

// given a character

char character = 'A';

// while loops checks the conditions


until the

// condition is false if condition is


true then enters

// in to the loop and executes the


statements

while (i <= rows) {

while (j <= i - 1) {
// printing character to get
the required

// pattern

cout << character << " ";

j++;

cout << "\n";

// incrementing character value so


that it

// will print the next character

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

// C++ program to print character pattern


by

// converting number in to character

#include <iostream>

using namespace std;

int main()

int i = 1, j = 0;

// input entering number of rows

int rows = 5;
// given a number

int number = 65;

// while loops checks the conditions


until the

// condition is false if condition is


true then enters

// in to the loop and executes the


statements

while (i <= rows) {

while (j <= i - 1) {

// converting number in to
character

char character = char(number);

// printing character to get


the required

// pattern

cout << character << " ";

j++;
}

cout << "\n";

// incrementing number value so


that it

// will print the next chC++


Program To Print
Continuous Character
Pattern


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

1. Using for loop


Approach 1:
Assign any character 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.
Then print the character based on the number of
columns and increment the character value at
each column to print a continuous character
pattern.

 C++

// C++ program to print continuous


character

// pattern using character

#include <iostream>

using namespace std;

int main()

int i, j;

// input entering number of rows

int rows = 5;
// taking first character of alphabet

// which is useful to print pattern

char character = 'A';

// first for loop is used to identify


number rows

for (i = 0; i < rows; i++) {

// second for loop is used to


identify number

// of columns based on the rows

for (j = 0; j <= i; j++) {

// printing character to get


the required

// pattern

cout << character << " ";

// incrementing character value


so that it
// will print the next
character

character++;

cout << "\n";

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

// C++ program to print continuous


character pattern by

// converting number in to character

#include <iostream>

using namespace std;

int main()

int i, j;

// input entering number of rows

int rows = 5;

// given a number

int number = 65;

// first for loop is used to identify


number rows
for (i = 0; i < rows; i++) {

// second for loop is used to


identify number

// of columns based on the rows

for (j = 0; j <= i; j++) {

// converting number in to
character

char character = char(number);

// printing character to get


the required

// pattern

cout << character << " ";

// incrementing number value so


that it

// will print the next


character
number++;

cout << "\n";

return 0;

Output
A
B C
D E F
G H I J
K L M N O

Using while loops:


Input:
rows=5
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++

// C++ program to print the continuous

// character pattern using while loop

#include <iostream>

using namespace std;

int main()

int i = 1, j = 0;

// input entering number of rows

int rows = 5;

// given a character

char character = 'A';


// while loops checks the conditions
until the

// condition is false if condition is


true then enters

// in to the loop and executes the


statements

while (i <= rows) {

while (j <= i - 1) {

// printing character to get


the required

// pattern

cout << character << " ";

j++;

// incrementing character value


so that it

// will print the next


character

character++;

cout << "\n";

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

// character pattern by converting

// number in to character

#include <iostream>

using namespace std;

int main()

int i = 1, j = 0;

// input entering number of rows

int rows = 5;

// given a number

int number = 65;

// while loops checks the conditions


until the

// condition is false if condition is


true then enters

// in to the loop and executes the


statements

while (i <= rows) {

while (j <= i - 1) {

// converting number in to
character

char character = char(number);

// printing character to get


the required

// pattern

cout << character << " ";

j++;

// incrementing number value so


that it

// will print the next


character

number++;

cout << "\n";

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

C++ Program To Print Continuous Character


Pattern


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

1. Using for loop


Approach 1:
Assign any character 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. Then print the character based on the number of columns and increment the
character value at each column to print a continuous character pattern.

 C++

// C++ program to print continuous


character

// pattern using character

#include <iostream>

using namespace std;

int main()

int i, j;

// input entering number of rows

int rows = 5;
// taking first character of alphabet

// which is useful to print pattern

char character = 'A';

// first for loop is used to identify


number rows

for (i = 0; i < rows; i++) {

// second for loop is used to


identify number

// of columns based on the rows

for (j = 0; j <= i; j++) {

// printing character to get


the required

// pattern

cout << character << " ";

// incrementing character value


so that it

// will print the next


character

character++;

cout << "\n";

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

// C++ program to print continuous


character pattern by

// converting number in to character

#include <iostream>

using namespace std;

int main()

int i, j;

// input entering number of rows

int rows = 5;

// given a number

int number = 65;

// first for loop is used to identify


number rows

for (i = 0; i < rows; i++) {


// second for loop is used to
identify number

// of columns based on the rows

for (j = 0; j <= i; j++) {

// converting number in to
character

char character = char(number);

// printing character to get


the required

// pattern

cout << character << " ";

// incrementing number value so


that it

// will print the next


character

number++;

}
cout << "\n";

return 0;

Output
A
B C
D E F
G H I J
K L M N O

Using while loops:


Input:
rows=5
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++

// C++ program to print the continuous


// character pattern using while loop

#include <iostream>

using namespace std;

int main()

int i = 1, j = 0;

// input entering number of rows

int rows = 5;

// given a character

char character = 'A';

// while loops checks the conditions


until the

// condition is false if condition is


true then enters

// in to the loop and executes the


statements

while (i <= rows) {

while (j <= i - 1) {

// printing character to get


the required

// pattern

cout << character << " ";

j++;

// incrementing character value


so that it

// will print the next


character

character++;
}

cout << "\n";

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

// character pattern by converting

// number in to character
#include <iostream>

using namespace std;

int main()

int i = 1, j = 0;

// input entering number of rows

int rows = 5;

// given a number

int number = 65;

// while loops checks the conditions


until the

// condition is false if condition is


true then enters

// in to the loop and executes the


statements
while (i <= rows) {

while (j <= i - 1) {

// converting number in to
character

char character = char(number);

// printing character to get


the required

// pattern

cout << character << " ";

j++;

// incrementing number value so


that it

// will print the next


character

number++;

}
cout << "\n";

j = 0;

i++;

return 0;

Output
A
B C
D E F
G H I J
K L M N O

C++ Program To Print The Diamond Shape




Given a number n, write a program to print a diamond shape with 2n-1 rows.
Examples :
Input: 5
Output:
 C++

// C++ program to print diamond shape

// with 2n-1 rows

#include <bits/stdc++.h>

using namespace std;

// Prints diamond pattern with 2n-1 rows

void printDiamond(int n)

{
int space = n - 1;

// run loop (parent loop)

// till number of rows

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

// loop for initially space,

// before star printing

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

cout << " ";

// Print i+1 stars

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

cout << "* ";

cout << endl;

space--;

}
// Repeat again in reverse order

space = 0;

// run loop (parent loop)

// till number of rows

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

// loop for initially space,

// before star printing

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

cout << " ";

// Print i stars

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

cout << " *";

cout << endl;


space++;

// Driver code

int main()

printDiamond(5);

return 0;

// This is code is contributed

// by rathbhupendra

Output
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

C++ Program To Print Inverted Hollow Star


Pyramid Pattern


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

// C++ program to Print a Inverted

// hollow Star Pyramid

#include <bits/stdc++.h>

using namespace std;

void print_patt(int R)

// To iterate through the rows

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

// To print the beginning spaces

for(int sp = 1;

sp <= i - 1 ; sp++)

cout << " ";

}
// Iterating from ith column to

// last column (R*2 - (2*i - 1))

int last_col = (R * 2 - (2 * i - 1));

// To iterate through column

for(int j = 1; j <= last_col; j++)

// To Print all star for first

// row (i==1) ith column (j==1)

// and for last column

// (R*2 - (2*i - 1))

if(i == 1)

cout << "*";

else if(j == 1)

cout << "*";

else if(j == last_col)

cout << "*";

else
cout << " ";

// After printing a row proceed

// to the next row

cout << "\n";

// Driver code

int main()

// Number of rows

int R = 5;

print_patt(R);

return 0;

Output
*********
* *
* *
* *
*

C++ Program To Print Hollow Star Pyramid


Diamond Shape Pattern


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

1. Using for loop


 C++

// C++ program to print hollow diamond


pattern
#include <iostream>

using namespace std;

int main()

int n = 5, rows, columns;

// for loop is used to identify the


number of rows and

// it is used to print upper triangle

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

// used for printing the spaces

for (columns = n; columns > rows;


columns--) {

cout << " ";

// print star

cout << "*";

// again print the spaces

for (columns = 1; columns < (rows -


1) * 2;

columns++) {

cout << " ";

if (rows == 1) {

cout << "\n";

else {

cout << "*\n";

// for loop is used to identify the


number of rows and

// it is used to print lower triangle

for (rows = n - 1; rows >= 1; rows--) {

// used for printing the spaces

for (columns = n; columns > rows;


columns--) {

cout << " ";

}
// print star

cout << "*";

for (columns = 1; columns < (rows -


1) * 2;

columns++) {

cout << " ";

if (rows == 1) {

cout << "\n";

else {

cout << "*\n";

return 0;

Output
*
* *
* *
* *
* *
* *
* *
* *
*
Time complexity: O(n2) for given input n
Auxiliary Space: O(1)
2. Using while loop:
 C++

// C++ program to print hollow diamond


pattern

#include <iostream>

using namespace std;

int main()

int n = 5, rows = 1, columns;

// while loop is used to identify the


number of rows and

// it is used to print upper triangle

while (rows <= n) {


columns = n;

// used for printing the spaces

while (columns > rows) {

cout << " ";

columns--;

// print star

cout << "*";

columns = 1;

while (columns < (rows - 1) * 2) {

cout << " ";

columns++;

if (rows == 1) {

cout << "\n";

else {
cout << "*\n";

rows++;

// while loop is used to identify the


number of rows and

// it is used to print lower triangle

rows = n - 1;

while (rows >= 1) {

columns = n;

// used for printing the spaces

while (columns > rows) {

cout << " ";

columns--;

// print star

cout << "*";

columns = 1;

while (columns < (rows - 1) * 2) {


cout << " ";

columns++;

if (rows == 1) {

cout << "\n";

else {

cout << "*\n";

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!

Method 1 ( O(n^3) time complexity )


Number of entries in every line is equal to line number. For example, the first line has
“1”, the second line has “1 1”, the third line has “1 2 1”,.. and so on. Every entry in a line
is value of a Binomial Coefficient. The value of ith entry in line number line is C(line, i).
The value can be calculated using following formula.
C(line, i) = line! / ( (line-i)! * i! )
A simple method is to run two loops and calculate the value of Binomial Coefficient in
inner loop.

 C++
// C++ code for Pascal's Triangle

#include <iostream>

using namespace std;

// See https://www.geeksforgeeks.org/space-
and-time-efficient-binomial-coefficient/

// for details of this function

int binomialCoeff(int n, int k);

// Function to print first

// n lines of Pascal's

// Triangle

void printPascal(int n)

// Iterate through every line and

// print entries in it

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

// Every line has number of


// integers equal to line

// number

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

cout <<" "<<


binomialCoeff(line, i);

cout <<"\n";

// See https://www.geeksforgeeks.org/space-
and-time-efficient-binomial-coefficient/

// for details of this function

int binomialCoeff(int n, int k)

int res = 1;

if (k > n - k)

k = n - k;

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

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

// C++ program for Pascal’s Triangle

// A O(n^2) time and O(n^2) extra space

// method for Pascal's Triangle

#include <bits/stdc++.h>

using namespace std;


void printPascal(int n)

// An auxiliary array to store

// generated pascal triangle values

int arr[n][n];

// Iterate through every line and

// print integer(s) in it

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

// Every line has number of


integers

// equal to line number

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

// First and last values in every


row are 1

if (line == i || i == 0)
arr[line][i] = 1;

// Other values are sum of values


just

// above and left of above

else

arr[line][i] = arr[line - 1][i


- 1] +

arr[line - 1]
[i];

cout << arr[line][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
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(line, i) = line! / ( (line-i)! * i! )


C(line, i-1) = line! / ( (line - i + 1)! * (i-1)! )
We can derive following expression from above two expressions.
C(line, i) = C(line, i-1) * (line - i + 1) / i

So C(line, i) can be calculated from C(line, i-1) in O(1) time

 C++

// C++ program for Pascal’s Triangle


// A O(n^2) time and O(1) extra space

// function for Pascal's Triangle

#include <bits/stdc++.h>

using namespace std;

void printPascal(int n)

for (int line = 1; line <= n; line++)

int C = 1; // used to represent C(line,


i)

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

// The first value in a line is


always 1

cout<< C<<" ";

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++ Program To Print Floyd’s Triangle





Floyd’s triangle is a triangular array of natural numbers and it is named after Robert
Floyd, a renowned computer scientist popularly known for the design of the Floyd–
Warshall algorithm. Here, we will see how to print Floyd’s pattern triangle pyramid using
the C++ program. Below are the examples:
Input: row = 5
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Input: row = 4
Output:
1
2 3
4 5 6
7 8 9 10
Algorithm:
 At first, take the number of rows as input.
 The next step is to implement the nested loop to print this pattern.
 A variable name count maintains the value of natural numbers to be printed.
There are 3 ways to print Floyd’s pattern triangle pyramid:
1. Using for loop.
2. Using While loop.
3. Using Recursion.
Let’s start discussing each of these methods in detail.

1. Using for loop


Below is the C++ program to print Floyd’s pattern triangle using for loop:

 C++

// C++ program to print

// Floyd's pattern triangle

// using for loop

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

void print_patt(int row)

// Initializing count to 1.

int count = 1;

// The outer loop maintains

// the number of rows.

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

// The inner loop maintains the

// number of column.

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

// To print the numbers

cout << count << " ";


// To keep increasing the count

// of numbers

count += 1;

// To proceed to next line.

cout << "\n";

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

// C++ program to print

// Floyd's pattern triangle

// using while loop

#include <bits/stdc++.h>

using namespace std;

void print_patt(int row)

// Initializing count to 1.

int count = 1;

// Loop control variables.

int i = 1, j;
// The outer loop maintains

// the number of rows.

while (i <= row)

// Reverting the value of j to 1

// after each iteration.

j = 1;

// The inner loop maintains the

// number of column.

while (j <= i)

// To print the numbers

cout << count << " ";

// To keep increasing the

// count of numbers
count += 1;

// Increasing the count

// of inner loop.

j += 1;

// Increasing the count of outer


loop.

i += 1;

// To proceed to next line.

cout << "\n";

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

// C++ program to print

// Floyd's pattern triangle

// using recursion

#include <bits/stdc++.h>

using namespace std;


void print_patt(int row, int curr_row,

int count)

// If row is less than 0, it

// returns return.

if (row <= 0)

return;

// The loop maintains the number

// of rows.

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

// To print the numbers

cout << count << " ";

// To keep increasing the count

// of numbers

count += 1;
}

// To proceed to next line.

cout << "\n";

// To increasing the current row

curr_row += 1;

// Calling the function recursively.

print_patt(row - 1,

curr_row, count);

// Driver Code

int main()

int curr_row = 1;

int count = 1;
int row = 5;

print_patt(row, curr_row, count);

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

// C++ program to print reverse

// of Floyd's triangle

#include <bits/stdc++.h>

using namespace std;

void printReverseFloyd(int n)

int curr_val = n * (n + 1) / 2;

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

for (int j = i; j >= 1; j--)

cout << setprecision(2);

cout << curr_val-- << " ";

}
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

C++ Function Programs


C/C++ Program to find Prime Numbers
between given range
Last Updated : 17 May, 2023



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

// C program to find the prime numbers

// between a given interval

#include <stdio.h>

// Function for print prime


// number in given range

void primeInRange(int L, int R)

int i, j, flag;

// Traverse each number in the

// interval with the help of for loop

for (i = L; i <= R; i++) {

// Skip 0 and 1 as they are

// neither prime nor composite

if (i == 1 || i == 0)

continue;

// flag variable to tell

// if i is prime or not

flag = 1;
// Iterate to check if i is prime

// or not

for (j = 2; j <= i / 2; ++j) {

if (i % j == 0) {

flag = 0;

break;

// flag = 1 means i is prime

// and flag = 0 means i is not prime

if (flag == 1)

printf("%d ", i);

// Driver Code

int main()
{

// Given Range

int L = 1;

int R = 10;

// Function Call

primeInRange(L, R);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
2 3 5 7

C++ Program To Check If a Prime Number Can


Be Expressed as Sum of Two Prime Numbers
Last Updated : 17 Jan, 2023



Given a prime number . The task is to check if it is possible to express as


sum of two separate prime numbers.
Note: The range of N is less than 108.
Examples:
Input: N = 13
Output: Yes
Explanation: The number 13 can be written as 11 + 2,
here 11 and 2 are both prime.

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

// C++ program to check if a prime number

// can be expressed as sum of

// two Prime Numbers

#include <bits/stdc++.h>

using namespace std;

// Function to check whether

// a number is prime or not

bool isPrime(int n)
{

if (n <= 1)

return false;

for (int i = 2; i <= sqrt(n); i++)

if (n % i == 0)

return false;

return true;

// Function to check if a prime number

// can be expressed as sum of

// two Prime Numbers

bool isPossible(int N)

{
// if the number is prime,

// and number-2 is also prime

if (isPrime(N) && isPrime(N - 2))

return true;

else

return false;

// Driver code

int main()

int n = 13;

if (isPossible(n))

cout << "Yes";

else

cout << "No";


return 0;

Output:
Yes

C++ Program For Sum of Natural Numbers


Using Recursion
Last Updated : 23 Jun, 2023



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

The Sum of Natural Numbers Using Recursion

Below is a C++ program to find the sum of natural numbers up to n using recursion:

 C++

// C++ program to find the sum


// of natural numbers up to n

// using recursion

#include <iostream>

using namespace std;

// Returns sum of first

// n natural numbers

int recurSum(int n)

if (n <= 1)

return n;

return n + recurSum(n - 1);

// Driver code

int main()

{
int n = 5;

cout << recurSum(n);

return 0;

Output
15

C++ Program to Find Factorial of a Large


Number Using Recursion
Last Updated : 17 Jan, 2023



Given a large number N, task is to find the factorial of N using recursion.


Factorial of a non-negative integer is the multiplication of all integers smaller than or
equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
Examples:
Input : N = 100
Output : 933262154439441526816992388562667004-
907159682643816214685929638952175999-
932299156089414639761565182862536979-
208272237582511852109168640000000000-00000000000000
Input : N = 50
Output : 3041409320171337804361260816606476884-
4377641568960512000000000000

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

// C++ program for the above approach

#include <bits/stdc++.h>

using namespace std;

// MUltiply the number x with the number

// represented by res array

vector<int> multiply(long int n, vector<int> digits)

// Initialize carry

long int carry = 0;

// One by one multiply n with

// individual digits of res[]


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

long int result

= digits[i] * n + carry;

// Store last digit of 'prod' in res[]

digits[i] = result % 10;

// Put rest in carry

carry = result / 10;

// Put carry in res and increase result size

while (carry) {

digits.push_back(carry % 10);

carry = carry / 10;

return digits;
}

// Function to recursively calculate the

// factorial of a large number

vector<int> factorialRecursiveAlgorithm(

long int n)

if (n <= 2) {

return multiply(n, { 1 });

return multiply(

n, factorialRecursiveAlgorithm(n - 1));

// Driver Code

int main()

{
long int n = 50;

vector<int> result

= factorialRecursiveAlgorithm(n);

for (long int i = result.size() - 1; i >= 0; i--) {

cout << result[i];

cout << "\n";

return 0;

Output
30414093201713378043612608166064768844377641568960512000000000000

C++ Program To Print Reverse of a String


Using Recursion
Last Updated : 17 Jan, 2023


Write a recursive function to print the reverse of a given string.


Code:
 C++
Output:

skeeG rof skeeG


Explanation: Recursive function (reverse) takes string pointer (str) as input and calls
itself with next location to passed pointer (str+1). Recursion continues this way when
the pointer reaches ‘\0’, all functions accumulated in stack print char at passed
location (str) and return one by one.
Time Complexity: O(n^2) as substr() method has a time complexity of O(k) where k
is the size of the returned string. So for every recursive call, we are reducing the size
of the string by one, which leads to a series like (k-1)+(k-2)+…+1 = k*(k-1)/2 =
O(k^2) = O(n^2)
See Reverse a string for other methods to reverse string.
Auxiliary Space: O(n)
Efficient Approach:
We can store each character in recursive stack and then can print while coming back
as shown in the below code:

 C++

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

#include <bits/stdc++.h>

using namespace std;

/* Function to print reverse of the passed string */

void reverse(char *str, int index, int n)


{

if(index == n) // return if we reached at last index or at the end of the string

return;

char temp = str[index]; // storing each character starting from index 0 in


function call stack;

reverse(str, index+1, n); // calling recursive function by increasing index


everytime

cout << temp; // printing each stored character while recurring back

/* Driver program to test above function */

int main()

char a[] = "Geeks for Geeks";

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

reverse(a, 0, n);

return 0;

}
Output:
skeeG rof skeeG

C++ Program To Calculate the Power of a


Number
Last Updated : 13 Oct, 2023



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

// C++ program for the above approach

#include <bits/stdc++.h>

using namespace std;

// Naive iterative solution to calculate pow(x, n)

long power(int x, unsigned n)

// Initialize result to 1

long long pow = 1;

// Multiply x for n times

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


pow = pow * x;

return pow;

// Driver code

int main(void)

int x = 2;

unsigned n = 3;

// Function call

int result = power(x, n);

cout << result << endl;

return 0;
}

Output
8

Variadic function templates in C++


Last Updated : 25 Nov, 2021



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

// C++ program to demonstrate working of

// Variadic function Template

#include <iostream>
using namespace std;

// To handle base case of below recursive

// Variadic function Template

void print()

cout << "I am empty function and "

"I am called at last.\n";

// Variadic function Template that takes

// variable number of arguments and prints

// all of them.

template <typename T, typename... Types>

void print(T var1, Types... var2)

cout << var1 << endl;


print(var2...);

// Driver code

int main()

print(1, 2, 3.14,

"Pass me any "

"number of arguments",

"I will print\n");

return 0;

Output
1
2
3.14
Pass me any number of arguments
I will print

I am empty function and I am called at last.


Remember that templates are replaced by actual functions by the compiler.
Explanation: The variadic templates work as follows :
The statement, print(1, 2, 3.14, “Pass me any number of arguments”, “I will print\
n”); is evaluated in the following manner:
Firstly, the compiler resolves the statement into
cout<< 1 <<endl ;
print(2, 3.14, "Pass me any number of arguments",
"I will print\n");
Now, the compiler finds a print() function which can take those arguments and in
result executes the variadic print() function again in a similar manner:
cout<< 2 <<endl ;
print(3.14, "Pass me any number of arguments",
"I will print\n");
Again, it is resolved into the following forms :
cout<< 3.14 <<endl ;
print("Pass me any number of arguments",
"I will print\n");
cout<< "Pass me any number of arguments" <<endl ;
print("I will print\n");
cout<< "I will print\n" <<endl ;
print();

C++ Array Programs


C++ Program to check if two Arrays are Equal
or not
Last Updated : 05 Jul, 2022



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

Naive Approach: The basic way to solve the problem is as follows:


Apply sorting on both the arrays and then match each element of one array with the
element at same index of the other array.
Follow the steps mentioned below to implement the idea.
 Check if the length of both the arrays are equal or not
 Then sort both the arrays, so that we can compare every equal element.
 Linearly iterate over both the arrays and check if the elements are equal or not,
 If equal then print Equal and if not then print Not equal.
Below is the implementation of the above approach:

 C++

// C++ program to implement the approach

#include <bits/stdc++.h>

using namespace std;

// Function to check if both arrays are equal

bool checkArrays(int arr1[], int arr2[],

int n, int m)
{

// If lengths of array are not equal

// means array are not equal

if (n != m)

return false;

// Sort both arrays

sort(arr1, arr1 + n);

sort(arr2, arr2 + m);

// Linearly compare elements

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

if (arr1[i] != arr2[i])

return false;

// If elements are same

return true;

}
// Driver Code

int main()

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

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

int N = sizeof(arr1) / sizeof(int);

int M = sizeof(arr2) / sizeof(int);

// Function call

if (checkArrays(arr1, arr2, N, M))

cout << "Equal";

else

cout << "Not Equal";

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

// C++ program to implement the approach

#include <bits/stdc++.h>

using namespace std;

// Function to check if both arrays are equal

bool checkArrays(int arr1[], int arr2[],

int n, int m)

// If lengths of arrays are not equal

if (n != m)
return false;

// Store arr1[] elements and

// their frequencies in hash map

unordered_map<int, int> mp;

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

mp[arr1[i]]++;

// Traverse arr2[] elements and

// check if all elements of arr2[] are

// present same number of times or not.

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

// If there is an element in arr2[],

// but not in arr1[]

if (mp.find(arr2[i]) == mp.end())

return false;
// If an element of arr2[] appears

// more times than it appears in arr1[]

if (mp[arr2[i]] == 0)

return false;

// Decrease the count of arr2 elements

// in the unordered map

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

int M = sizeof(arr2) / sizeof(int);

// Function call

if (checkArrays(arr1, arr2, N, M))

cout << "Equal";

else

cout << "Not Equal";

return 0;

Output
Equal

C++ Program to Find the Minimum and


Maximum Element of an Array
Last Updated : 17 Jan, 2023



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>

using namespace std;

int getMin(int arr[], int n)

return *min_element(arr, arr + n);

int getMax(int arr[], int n)

return *max_element(arr, arr + n);

int main()

int arr[] = { 12, 1234, 45, 67, 1 };


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

cout << "Minimum element of array: " << getMin(arr, n) << " ";

cout << "Maximum element of array: " << getMax(arr, n);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to find minimum (or maximum) element


// in an array.

#include <bits/stdc++.h>

using namespace std;

int getMin(int arr[], int n)

return *min_element(arr, arr + n);

int getMax(int arr[], int n)

return *max_element(arr, arr + n);

int main()

int arr[] = { 12, 1234, 45, 67, 1 };

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


cout << "Minimum element of array: " << getMin(arr, n) << " ";

cout << "Maximum element of array: " << getMax(arr, n);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
Minimum element of array: 1
Maximum element of array: 1234

C++ Program For Average of an Array


(Iterative and Recursive)


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;

// Function that return average


// of an array.
double average(int a[], int n)
{
// Find sum of array element
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];

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

cout << average(arr, n) << endl;


return 0;
}

Output
6

C++ Program to Merge Two Sorted Arrays




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

// C++ program to merge two sorted arrays

//using maps

#include<bits/stdc++.h>

using namespace std;

// Function to merge arrays

void mergeArrays(int a[], int b[], int n, int m)

// Declaring a map.

// using map as a inbuilt tool

// to store elements in sorted order.


map<int, int> mp;

// Inserting values to a map.

for(int i = 0; i < n; i++)mp[a[i]]++;

for(int i = 0;i < m;i++)mp[b[i]]++;

// Printing keys of the map.

for(auto j: mp)

for(int i=0; i<j.second;i++)cout<<j.first<<" ";

// Driver Code

int main()
{

int a[] = {1, 3, 5, 7}, b[] = {2, 4, 6, 8};

int size = sizeof(a)/sizeof(int);

int size1 = sizeof(b)/sizeof(int);

// Function call

mergeArrays(a, b, size, size1);

return 0;

//This code is contributed by yashbeersingh42

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to merge two sorted arrays

//using maps

#include<bits/stdc++.h>

using namespace std;

// Function to merge arrays

void mergeArrays(int a[], int b[], int n, int m)

{
// Declaring a map.

// using map as a inbuilt tool

// to store elements in sorted order.

map<int, int> mp;

// Inserting values to a map.

for(int i = 0; i < n; i++)mp[a[i]]++;

for(int i = 0;i < m;i++)mp[b[i]]++;

// Printing keys of the map.

for(auto j: mp)

for(int i=0; i<j.second;i++)cout<<j.first<<" ";

}
// Driver Code

int main()

int a[] = {1, 3, 5, 7}, b[] = {2, 4, 6, 8};

int size = sizeof(a)/sizeof(int);

int size1 = sizeof(b)/sizeof(int);

// Function call

mergeArrays(a, b, size, size1);

return 0;

//This code is contributed by yashbeersingh42

Learn Data Structures & Algorithms with GeeksforGeeks

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.

1. Using for loop


The general method to print a 2D array using for loop requires two for loops to
traverse all the rows and columns of the given 2D matrix and print the elements.
 The outer loop will loop from index 0 to row_length-1.
 It traverses the 2D array row-wise, therefore the first row is printed then it goes to
print the second row.
An Example array

Below is the C++ program to print a 2D array using for loop:

 C++

// C++ program to print

// 2D array using for loop

#include <iostream>

using namespace std;

// Driver code

int main()

const int i = 3, j = 3;

// Declaring array

int arr[i][j] = {{1, 2, 3},


{4, 5, 6},

{7, 8, 9}};

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

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

cout << arr[a][b] << " ";

cout << endl;

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

// array using range-based for loop

#include <iostream>

using namespace std;

// Driver code

int main()

const int i = 3, j = 3;

int matrix[i][j] = {{1, 2, 3},

{4, 5, 6},

{7, 8, 9}};

for (auto &row : matrix)

for (auto &column : row)

cout << column << " ";

}
cout << endl;

Output
1 2 3
4 5 6
7 8 9

How to find common elements between two


Arrays using STL in C++?
Last Updated : 26 Apr, 2019



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

// between two Arrays using STL

#include <bits/stdc++.h>

using namespace std;

int main()

// Get the array

int arr1[] = { 1, 45, 54, 71, 76, 12 };

int arr2[] = { 1, 7, 5, 4, 6, 12 };

// Compute the sizes

int n1 = sizeof(arr1) / sizeof(arr1[0]);

int n2 = sizeof(arr2) / sizeof(arr2[0]);

// Sort the arrays


sort(arr1, arr1 + n1);

sort(arr2, arr2 + n2);

// Print the array

cout << "First Array: ";

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

cout << arr1[i] << " ";

cout << endl;

cout << "Second Array: ";

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

cout << arr2[i] << " ";

cout << endl;

// Initialise a vector

// to store the common values

// and an iterator

// to traverse this vector


vector<int> v(n1 + n2);

vector<int>::iterator it, st;

it = set_intersection(arr1, arr1 + n1,

arr2, arr2 + n2,

v.begin());

cout << "\nCommon elements:\n";

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

cout << *st << ", ";

cout << '\n';

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

Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}


Output: arr[] = {1, 2, 3, 4, 5}
new size = 5
Recommended PracticeRemove duplicate elements from sorted ArrayTry It!

Method 1: (Using extra space)


1. Create an auxiliary array temp[] to store unique elements.
2. Traverse input array and one by one copy unique elements of arr[] to temp[]. Also
keep track of count of unique elements. Let this count be j.
3. Copy j elements from temp[] to arr[] and return j
 C++

// Simple C++ program to remove duplicates

#include <iostream>

using namespace std;

// Function to remove duplicate

// elements This function returns


// new size of modified array.

int removeDuplicates(int arr[], int n)

// Return, if array is empty or

// contains a single element

if (n == 0 || n == 1)

return n;

int temp[n];

// Start traversing elements

int j = 0;

// If current element is not equal

// to next element then store that

// current element

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

if (arr[i] != arr[i + 1])


temp[j++] = arr[i];

// Store the last element as whether

// it is unique or repeated, it hasn't

// stored previously

temp[j++] = arr[n - 1];

// Modify original array

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

arr[i] = temp[i];

return j;

// Driver code

int main()

int arr[] = {1, 2, 2, 3, 4,


4, 4, 5, 5};

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

// RemoveDuplicates() returns

// new size of array.

n = removeDuplicates(arr, n);

// Print updated array

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

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

return 0;

// This code is contributed by Aditya Kumar (adityakumar129)

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to remove

// duplicates in-place

#include<iostream>

using namespace std;

// Function to remove duplicate

// elements. This function returns

// new size of modified array.

int removeDuplicates(int arr[], int n)

if (n==0 || n==1)

return n;

// To store index of next

// unique element

int j = 0;
// Doing same as done in Method 1

// Just maintaining another updated

// index i.e. j

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

if (arr[i] != arr[i + 1])

arr[j++] = arr[i];

arr[j++] = arr[n - 1];

return j;

// Driver code

int main()

int arr[] = {1, 2, 2, 3, 4,

4, 4, 5, 5};
int n = sizeof(arr) / sizeof(arr[0]);

// removeDuplicates() returns new

// size of array.

n = removeDuplicates(arr, n);

// Print updated array

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

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

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
1 2 3 4 5

C++ Program to Remove All Occurrences of


an Element in an Array
Last Updated : 08 Jul, 2022




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

// C++ program to remove all the

// occurrences

#include <iostream>

using namespace std;

void remove_all_occurrence(int arr[],

int target,

int n)

{
int cnt = 0;

// Counting all occurrence of

// target element

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

if(arr[i] == target)

cnt++;

// Creating new array of

// size = original size -

// no. of target element

int new_arr[n - cnt];

int ind = 0;

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

if(arr[i] != target)
{

new_arr[ind] = arr[i];

ind++;

// Printing the new array

int m = (sizeof(new_arr) /

sizeof(new_arr[0]));

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

cout << new_arr[i] << " ";

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

remove_all_occurrence(arr, target, n);

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

// C++ program to remove all occurrences


// of an element from an array using

// optimized approach

#include <iostream>

using namespace std;

void remove_all_occurrence(int arr[],

int target,

int n)

int cnt = 0;

// Shifting non target elements

// to the left side

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

if(arr[i] != target)

{
arr[i - cnt] = arr[i];

else

cnt++;

// Printing the array

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

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

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

remove_all_occurrence(arr, target, n);

return 0;

Output
1 4 6 8 9 10 7

C++ Program to Left Rotate an Array by d


Elements.
Last Updated : 17 Apr, 2023



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>

using namespace std;


// Function to rotate array

void Rotate(int arr[], int d, int n)

// Storing rotated version of array

int temp[n];

// Keeping track of the current index

// of temp[]

int k = 0;

// Storing the n - d elements of

// array arr[] to the front of temp[]

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

temp[k] = arr[i];

k++;

}
// Storing the first d elements of array arr[]

// into temp

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

temp[k] = arr[i];

k++;

// Copying the elements of temp[] in arr[]

// to get the final rotated array

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

arr[i] = temp[i];

// Function to print elements of array

void PrintTheArray(int arr[], int n)

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


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

// Driver code

int main()

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

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

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

// C++ program to rotate an array by

// d elements

#include <bits/stdc++.h>

using namespace std;

/*Function to left rotate arr[] of size n by d*/


void Rotate(int arr[], int d, int n)

int p = 1;

while (p <= d) {

int last = arr[0];

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

arr[i] = arr[i + 1];

arr[n - 1] = last;

p++;

// Function to print an array

void printArray(int arr[], int size)

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

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


}

// Driver code

int main()

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

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

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:

Let arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14} and d = 10


First step:
=> First set is {0, 5, 10}.
=> Rotate this set by d position in cyclic order
=> arr[0] = arr[0+10]
=> arr[10] = arr[(10+10)%15]
=> arr[5] = arr[0]
=> This set becomes {10,0,5}
=> Array arr[] = {10, 1, 2, 3, 4, 0, 6, 7, 8, 9, 5, 11, 12, 13, 14}
Second step:
=> Second set is {1, 6, 11}.
=> Rotate this set by d position in cyclic order.
=> This set becomes {11, 1, 6}
=> Array arr[] = {10, 11, 2, 3, 4, 0, 1, 7, 8, 9, 5, 6, 12, 13, 14}
Third step:
=> Second set is {2, 7, 12}.
=> Rotate this set by d position in cyclic order.
=> This set becomes {12, 2, 7}
=> Array arr[] = {10, 11, 12, 3, 4, 0, 1, 2, 8, 9, 5, 6, 7, 13, 14}
Fourth step:
=> Second set is {3, 8, 13}.
=> Rotate this set by d position in cyclic order.
=> This set becomes {13, 3, 8}
=> Array arr[] = {10, 11, 12, 13, 4, 0, 1, 2, 3, 9, 5, 6, 7, 8, 14}
Fifth step:
=> Second set is {4, 9, 14}.
=> Rotate this set by d position in cyclic order.
=> This set becomes {14, 4, 9}
=> Array arr[] = {10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Follow the steps below to solve the given problem.
 Perform d%n in order to keep the value of d within the range of the array
where d is the number of times the array is rotated and N is the size of the array.
 Calculate the GCD(N, d) to divide the array into sets.
 Run a for loop from 0 to the value obtained from GCD.
 Store the value of arr[i] in a temporary variable (the value of i denotes
the set number).
 Run a while loop to update the values according to the set.
 After exiting the while loop assign the value of arr[j] as the value of the
temporary variable (the value of j denotes the last element of the ith set).
Below is the implementation of the above approach :

 C++

// C++ program to rotate an array by

// d elements

#include <bits/stdc++.h>

using namespace std;

/*Function to get gcd of a and b*/


int gcd(int a, int b)

if (b == 0)

return a;

else

return gcd(b, a % b);

/*Function to left rotate arr[] of size n by d*/

void leftRotate(int arr[], int d, int n)

/* To handle if d >= n */

d = d % n;

int g_c_d = gcd(d, n);

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

/* move i-th values of blocks */

int temp = arr[i];


int j = i;

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;

// Function to print an array


void printArray(int arr[], int size)

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

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

/* Driver program to test above functions */

int main()

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

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

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

using namespace std;

int main() {

deque<int> dq {1, 2, 3, 4, 5, 6, 7};

int d = 2;

// Rotate the deque left by d elements

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

int temp = dq.front();

dq.pop_front();
dq.push_back(temp);

// Print the rotated deque

for(auto it=dq.begin(); it!=dq.end(); it++) {

cout << *it << " ";

return 0;

Output
deque([3, 4, 5, 6, 7, 1, 2])

C++ Program to Copy the Contents of One


Array Into Another in the Reverse Order
Last Updated : 17 Jan, 2023



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

// C program to copy the contents

// of one array into another

// in the reverse order

#include <stdio.h>

// Function to print the array

void printArray(int arr[], int len)

int i;

for (i = 0; i < len; i++) {

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

// Driver code
int main()

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

int len = sizeof(original_arr)/sizeof(original_arr[0]);

int copied_arr[len], i, j;

// Copy the elements of the array

// in the copied_arr in Reverse Order

for (i = 0; i < len; i++) {

copied_arr[i] = original_arr[len - i - 1];

// Print the original_arr

printf("

Original array: ");

printArray(original_arr, len);
// Print the copied array

printf("

Resultant array: ");

printArray(copied_arr, len);

return 0;

Output:
Original array: 1 2 3 4 5
Resultant array: 5 4 3 2 1

C++ Matrix Programs


C++ Program For Addition of Two Matrices
Last Updated : 27 Jun, 2023



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

Below is the idea to solve the problem.


1. Iterate over every cell of the matrix (i, j).
2. Add the corresponding values of the two matrices.
3. Store in a single matrix i.e. the resultant matrix.

Algorithm

1. Initialize a resultant matrix res[N][M].


2. Run a for loop for counter i as each row and in each iteration:
1. Run a for loop for counter j as each column and in each iteration:
1. Add values of the two matrices for index i, j, and store in res[i][j].
3. Return res.
Below is the Implementation of the above approach:
 C++

// C++ program for addition

// of two matrices
#include <bits/stdc++.h>

using namespace std;

#define N 4

// This function adds A[][] and B[][],

// and stores the result in C[][]

void add(int A[][N], int B[][N], int C[][N])

int i, j;

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

for (j = 0; j < N; j++)

C[i][j] = A[i][j] + B[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 } };

// To store the result

int C[N][N];

int i, j;

add(A, B, C);

cout << "Result matrix is " << endl;

for (i = 0; i < N; i++) {

for (j = 0; j < N; j++)

cout << C[i][j] << " ";


cout << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Result matrix is
2 2 2 2
4 4 4 4
6 6 6 6
8 8 8 8

C++ Program To Check if Two Matrices are


Identical
Last Updated : 17 Jan, 2023



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

// given matrices are identical

#include <bits/stdc++.h>

#define N 4

using namespace std;

// This function returns 1 if A[][]

// and B[][] are identical otherwise

// returns 0

int areSame(int A[][N], int B[][N])

int i, j;

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

for (j = 0; j < N; j++)

if (A[i][j] != B[i][j])

return 0;

return 1;

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

if (areSame(A, B))

cout << "Matrices are identical";

else

cout << "Matrices are not identical";

return 0;
}

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
Matrices are identical

C++ Program to Efficiently Compute Sums of


Diagonals of a Matrix
Last Updated : 17 Jan, 2023



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.

A00 A01 A02 A03


A10 A11 A12 A13
A20 A21 A22 A23
A30 A31 A32 A33
The primary diagonal is formed by the elements A00, A11, A22, A33.

1. Condition for Principal Diagonal: The row-column condition is row = column.


The secondary diagonal is formed by the elements A03, A12, A21, A30.
2. Condition for Secondary Diagonal: The row-column condition is row =
numberOfRows – column -1.
Examples :
Input:
4
1 2 3 4
4 3 2 1
7 8 9 6
6 5 4 3
Output:
Principal Diagonal: 16
Secondary Diagonal: 20

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

// A simple C++ program to find sum

// of diagonals

#include <bits/stdc++.h>

using namespace std;

const int MAX = 100;

void printDiagonalSums(int mat[][MAX], int n)

int principal = 0, secondary = 0;

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


{

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

// Condition for principal diagonal

if (i == j)

principal += mat[i][j];

// Condition for secondary diagonal

if ((i + j) == (n - 1))

secondary += mat[i][j];

cout << "Principal Diagonal:" <<

principal << endl;

cout << "Secondary Diagonal:" <<

secondary << endl;

}
// Driver code

int main()

int a[][MAX] = {{1, 2, 3, 4},

{5, 6, 7, 8},

{1, 2, 3, 4},

{5, 6, 7, 8}};

printDiagonalSums(a, 4);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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.

Method 2 (Efficient Approach) :


In this method we use one loop i.e. a loop for calculating sum of both the principal
and secondary diagonals:

 C++
// An efficient C++ program to

// find sum of diagonals

#include <bits/stdc++.h>

using namespace std;

const int MAX = 100;

void printDiagonalSums(int mat[][MAX],

int n)

int principal = 0, secondary = 0;

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

principal += mat[i][i];

secondary += mat[i][n - i - 1];

cout << "Principal Diagonal:" <<


principal << endl;

cout << "Secondary Diagonal:" <<

secondary << endl;

// Driver code

int main()

int a[][MAX] = {{1, 2, 3, 4},

{5, 6, 7, 8},

{1, 2, 3, 4},

{5, 6, 7, 8}};

printDiagonalSums(a, 4);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output :
Principal Diagonal:18
Secondary Diagonal:18
C++ Program For Boundary Elements of a
Matrix
Last Updated : 17 Jan, 2023



Printing Boundary Elements of a Matrix.


Given a matrix of size n x m. Print the boundary elements of the matrix. Boundary
elements are those elements which are 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:
1 2 3 4
5 8
1 4
5 6 7 8
Explanation:The boundary elements of the
matrix is printed.

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

// C++ program to print boundary element

// of matrix.

#include <iostream>

using namespace std;

const int MAX = 100;

void printBoundary(int a[][MAX], int m, int n)

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

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

if (i == 0 || j == 0 ||
i == n - 1 || j == n - 1)

cout << a[i][j] << " ";

else

cout << " "

<< " ";

cout << endl;

// Driver code

int main()

int a[4][MAX] = {{1, 2, 3, 4},

{5, 6, 7, 8},

{1, 2, 3, 4},

{5, 6, 7, 8}};

printBoundary(a, 4, 4);
return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to find sum of boundary elements

// of matrix.

#include <iostream>

using namespace std;

const int MAX = 100;

int getBoundarySum(int a[][MAX],

int m, int n)

{
long long int sum = 0;

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

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

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

int a[][MAX] = {{1, 2, 3, 4},

{5, 6, 7, 8},

{1, 2, 3, 4},

{5, 6, 7, 8}};

long long int sum = getBoundarySum(a, 4, 4);

cout << "Sum of boundary elements is " <<

sum;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
Sum of boundary elements is 54

C++ Program To Find Transpose of a Matrix


Last Updated : 21 Jun, 2023



Transpose of a matrix is obtained by changing rows to columns and columns to rows.


In other words, the transpose of A[][] is obtained by changing A[i][j] to A[j][i].
Example:

Recommended: Please solve it on “PRACTICE ” first, before moving on to the


solution.

1. For Square Matrix

The below program finds the transpose of A[][] and stores the result in B[][], we can
change N for a different dimension.

 C++

// C++ Program to find the transpose

// of a matrix

#include <bits/stdc++.h>

using namespace std;

#define N 4

// This function stores transpose


// of A[][] in B[][]

void transpose(int A[][N],

int B[][N])

int i, j;

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

for (j = 0; j < N; j++)

B[i][j] = A[j][i];

// 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], i, j;

transpose(A, B);

cout << "Result matrix is \n";

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

for (j = 0; j < N; j++)

cout << " " << B[i][j];

cout <<"\n";

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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.

2. For Rectangular Matrix

The below program finds the transpose of A[][] and stores the result in B[][].

 C++

// C++ program to find transpose

// of a matrix

#include <bits/stdc++.h>

using namespace std;

#define M 3

#define N 4

// This function stores transpose

// of A[][] in B[][]

void transpose(int A[][N], int B[][M])

int i, j;

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

for(j = 0; j < M; j++)


B[i][j] = A[j][i];

// Driver code

int main()

int A[M][N] = {{1, 1, 1, 1},

{2, 2, 2, 2},

{3, 3, 3, 3}};

// Note dimensions of B[][]

int B[N][M], i, j;

transpose(A, B);

cout << "Result matrix is \n";

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

{
for(j = 0; j < M; j++)

cout << " " << B[i][j];

cout << "\n";

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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.

3. In-Place for Square Matrix

Below is the implementation of the method:

 C++

// C++ program to implement


// the above approach

#include <bits/stdc++.h>

using namespace std;

#define N 4

// Converts A[][] to its transpose

void transpose(int A[][N])

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

for (int j = i+1; j < N; j++)

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

// Driver code

int main()

int A[N][N] = {{1, 1, 1, 1},


{2, 2, 2, 2},

{3, 3, 3, 3},

{4, 4, 4, 4}};

transpose(A);

printf("Modified matrix is \n");

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

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

printf("%d ", A[i][j]);

printf("\n");

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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++ Program For Determinant of a Matrix


Last Updated : 07 Apr, 2023



What is the Determinant of a Matrix?


The determinant of a Matrix is a special number that is defined only for square
matrices (matrices that have the same number of rows and columns). A determinant is
used at many places in calculus and other matrices related to algebra, it actually
represents the matrix in terms of a real number which can be used in solving a system
of a linear equation and finding the inverse of a matrix.
How to calculate?
The value of the determinant of a matrix can be calculated by the following procedure

For each element of the first row or first column get the cofactor of those elements
and then multiply the element with the determinant of the corresponding cofactor, and
finally add them with alternate signs. As a base case, the value of the determinant of a
1*1 matrix is the single value itself.
Cofactor of an element is a matrix that we can get by removing the row and column
of that element from that matrix.
Determinant of 2 x 2 Matrix:
Determinant of 3 x 3 Matrix:

Recommended PracticeCost of SweetsTry It!

 C++

#include <iostream>

#include <cmath>

using namespace std;

const int MAXN = 105;

double a[MAXN][MAXN];
double determinant(int n) {

double det = 1.0;

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

int pivot = i;

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

if (abs(a[j][i]) > abs(a[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++) {

double factor = a[j][i] / a[i][i];

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

a[j][k] -= factor * a[i][k];

return det;

int main() {

int n = 4;

double matrix[4][4] = {{1, 0, 2, -1},

{3, 0, 0, 5},

{2, 1, 4, -3},

{1, 0, 5, 0}};

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

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


a[i][j] = matrix[i][j];

double det = determinant(n);

cout << "Determinant = " << det << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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 determinant(int matrix[4][4], int n){

int det = 0;

int submatrix[4][4];

if(n == 1){

return matrix[0][0];

else if(n == 2){

return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));

else{

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

int subi = 0;

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

int subj = 0;

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


if(j == x){

continue;

submatrix[subi][subj] = matrix[i][j];

subj++;

subi++;

det = det + (pow(-1, x) * matrix[0][x] * determinant(submatrix, n-1));

return det;

int main(){

int matrix[4][4] = {{1, 0, 2, -1},

{3, 0, 0, 5},

{2, 1, 4, -3},
{1, 0, 5, 0}};

int n = 4;

int det = determinant(matrix, n);

cout<<"Determinant: "<<det<<endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Determinant of the matrix is : 30
Time complexity: O(n3)
Auxiliary Space: O(n)

Approach: Gauss-Jordan Elimination

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

// C++ program for the above approach


#include <iostream>

using namespace std;

// Function to calculate the determinant

// of a matrix

int determinant(int** matrix, int size)

int det = 0;

int sign = 1;

// Base Case

if (size == 1) {

det = matrix[0][0];

else if (size == 2) {

det = (matrix[0][0] * matrix[1][1])

- (matrix[0][1] * matrix[1][0]);
}

// Perform the Laplace Expansion

else {

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

// Stores the cofactor matrix

int** cofactor = new int*[size - 1];

for (int j = 0; j < size - 1; j++) {

cofactor[j] = new int[size - 1];

int sub_i = 0, sub_j = 0;

for (int j = 1; j < size; j++) {

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

if (k == i) {

continue;

cofactor[sub_i][sub_j] = matrix[j][k];
sub_j++;

sub_i++;

sub_j = 0;

// Update the determinant value

det += sign * matrix[0][i]

* determinant(cofactor, size - 1);

sign = -sign;

for (int j = 0; j < size - 1; j++) {

delete[] cofactor[j];

delete[] cofactor;

// Return the final determinant value


return det;

// Driver Code

int main()

int** matrix = new int*[4];

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

matrix[i] = new int[4];

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;

int det = determinant(matrix, size);

cout << "Determinant: " << det << endl;

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

delete[] matrix[i];

delete[] matrix;
return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program for the above approach

#include <iostream>

using namespace std;

// Function to calculate the determinant

// of a matrix

int determinant(int** matrix, int size)


{

int det = 0;

int sign = 1;

// Base Case

if (size == 1) {

det = matrix[0][0];

else if (size == 2) {

det = (matrix[0][0] * matrix[1][1])

- (matrix[0][1] * matrix[1][0]);

// Perform the Laplace Expansion

else {

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

// Stores the cofactor matrix


int** cofactor = new int*[size - 1];

for (int j = 0; j < size - 1; j++) {

cofactor[j] = new int[size - 1];

int sub_i = 0, sub_j = 0;

for (int j = 1; j < size; j++) {

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

if (k == i) {

continue;

cofactor[sub_i][sub_j] = matrix[j][k];

sub_j++;

sub_i++;

sub_j = 0;

// Update the determinant value


det += sign * matrix[0][i]

* determinant(cofactor, size - 1);

sign = -sign;

for (int j = 0; j < size - 1; j++) {

delete[] cofactor[j];

delete[] cofactor;

// Return the final determinant value

return det;

// Driver Code

int main()

int** matrix = new int*[4];


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

matrix[i] = new int[4];

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;

int det = determinant(matrix, size);

cout << "Determinant: " << det << endl;

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

delete[] matrix[i];

delete[] matrix;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Determinant: 30

C++ Program To Find Normal and Trace of a


Matrix
Last Updated : 17 Jan, 2023


Given a 2D matrix, the task is to find Trace and Normal of matrix.


Normal of a matrix is defined as square root of sum of squares of matrix elements.
Trace of a n x n square matrix is sum of diagonal elements.
Examples :
Input: mat[][] = {{7, 8, 9},
{6, 1, 2},
{5, 4, 3}};
Output: Normal = 16
Trace = 11
Explanation:
Normal = sqrt(7*7+ 8*8 + 9*9 + 6*6 +
1*1 + 2*2 + 5*5 + 4*4 + 3*3)
= 16
Trace = 7+1+3 = 11

Input: mat[][] = {{1, 2, 3},


{6, 4, 5},
{2, 1, 3}};
Output: Normal = 10
Trace = 8
Explanation:
Normal = sqrt(1*1 +2*2 + 3*3 + 6*6 + 4*4 +
5*5 + 2*2 + 1*1 + 3*3)
Trace = 8(1+4+3)
 C++

// C++ program to find trace and

// normal of given matrix

#include<bits/stdc++.h>

using namespace std;

// Size of given matrix

const int MAX = 100;


// Returns Normal of a matrix of

// size n x n

int findNormal(int mat[][MAX], int n)

int sum = 0;

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

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

sum += mat[i][j] * mat[i][j];

return sqrt(sum);

// Returns trace of a matrix of

// size n x n

int findTrace(int mat[][MAX], int n)

int sum = 0;

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

sum += mat[i][i];
return sum;

// Driven code

int main()

int mat[][MAX] = {{1, 1, 1, 1, 1},

{2, 2, 2, 2, 2},

{3, 3, 3, 3, 3},

{4, 4, 4, 4, 4},

{5, 5, 5, 5, 5}};

cout << "Trace of Matrix = " <<

findTrace(mat, 5) << endl;

cout << "Normal of Matrix = " <<

findNormal(mat, 5) << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output :
Trace of matrix = 15
Normal of matrix = 16

Multiply Two Matrices in C++


Last Updated : 21 Sep, 2023



A matrix is a collection of numbers arranged in rows and columns. We can multiply


two matrices if the number of columns in the first matrix should be equal to the
number of rows in the second matrix. The product matrix has the number of rows the
same as the first matrix and the number of columns the same as the second matrix.
In this article, we will learn the multiplication of two matrices in the C++
programming language.

Matrix Multiplication in C++

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.

Algorithm to Multiply Two Matrices


 If the original matrices are of size n1 x n2 and m1 x m2, create a resultant matrix
of size n1 x m2.
 Three nested loops will be used for the multiplication of the matrices.
 The first two loops are used to iterate over the rows and columns of the result
matrix, respectively.
 The innermost loop performs the multiplication of corresponding elements from
the current row of the first matrix and the current column of the second matrix.
 Add these products to get the element of the result matrix.
 Repeat these steps for all elements of the result matrix.
C++ Program to Multiply Two Matrices
We use pointers in C++ to multiply matrices. Please refer to the following post as a
prerequisite for the code How to pass a 2D array as a parameter in C?
 C++

// C++ program to multiply two matrices

#include <bits/stdc++.h>

using namespace std;

// Edit MACROs here, according to your Matrix Dimensions for

// mat1[R1][C1] and mat2[R2][C2]


#define R1 2 // number of rows in Matrix-1

#define C1 2 // number of columns in Matrix-1

#define R2 2 // number of rows in Matrix-2

#define C2 3 // number of columns in Matrix-2

void mulMat(int mat1[][C1], int mat2[][C2])

int rslt[R1][C2];

cout << "Multiplication of given two matrices is:\n";

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

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

rslt[i][j] = 0;

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

rslt[i][j] += mat1[i][k] * mat2[k][j];

}
cout << rslt[i][j] << "\t";

cout << endl;

// Driver code

int main()

// R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these

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

"be equal to the number of rows in "

"Matrix-2"

<< endl;

cout << "Please update MACROs according to your "

"array dimension in #define section"

<< endl;

exit(EXIT_FAILURE);

// Function call

mulMat(mat1, mat2);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Multiplication of given two matrices is:
3 3 3
6 6 6

C++ Program to Rotate Matrix Elements


Last Updated : 22 Aug, 2023



Given a matrix, clockwise rotate elements in it.


Examples:
Input:
1 2 3
4 5 6
7 8 9

Output:
4 1 2
7 5 3
8 9 6

For 4*4 matrix:


Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

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

// C++ program to rotate a matrix

#include <iostream>

#define R 4

#define C 4

using namespace std;

// A function to rotate a matrix

// mat[][] of size R x C.

// Initially, m = R and n = C

void rotatematrix(int m, int n,

int mat[R][C])

int row = 0, col = 0;

int prev, curr;

/* row - Starting row index


m - ending row index

col - starting column index

n - ending column index

i - iterator */

while (row < m && col < n)

if (row + 1 == m ||

col + 1 == n)

break;

// Store the first element of

// next row, this element will

// replace first element of current

// row

prev = mat[row + 1][col];

/* Move elements of first row from

the remaining rows */


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

curr = mat[row][i];

mat[row][i] = prev;

prev = curr;

row++;

/* Move elements of last column

from the remaining columns */

for (int i = row; i < m; i++)

curr = mat[i][n-1];

mat[i][n-1] = prev;

prev = curr;

n--;
/* Move elements of last row from

the remaining rows */

if (row < m)

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

curr = mat[m-1][i];

mat[m-1][i] = prev;

prev = curr;

m--;

/* Move elements of first column from

the remaining rows */

if (col < n)

for (int i = m-1; i >= row; i--)


{

curr = mat[i][col];

mat[i][col] = prev;

prev = curr;

col++;

// Print rotated matrix

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

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

cout << mat[i][j] << " ";

cout << endl;

}
// Driver code

int main()

// Test Case 1

int a[R][C] = {{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12},

{13, 14, 15, 16}};

// Test Case 2

/* int a[R][C] = {{1, 2, 3},

{4, 5, 6},

{7, 8, 9}};

*/ rotatematrix(R, C, a);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12

C++ Program to Interchange elements of first


and last rows in matrix
Last Updated : 07 Jun, 2022



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

// C++ code to swap the element of first


// and last row and display the result

#include <iostream>

using namespace std;

#define n 4

void interchangeFirstLast(int m[][n])

int rows = n;

// Swapping of element between first

// and last rows

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

int t = m[0][i];

m[0][i] = m[rows - 1][i];

m[rows - 1][i] = t;

}
}

// Driver code

int main()

// input in the array

int m[n][n] = {{8, 9, 7, 6},

{4, 7, 6, 5},

{3, 2, 1, 8},

{9, 9, 7, 7}};

interchangeFirstLast(m);

// Printing the interchanged matrix

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

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

cout << m[i][j] << " ";


cout << endl;

// This code is contributed by Anant Agarwal.

Learn Data Structures & Algorithms with GeeksforGeeks

Output :
9 9 7 7
4 7 6 5
3 2 1 8
8 9 7 6

++ Program To Interchange Elements of First


and Last Columns in Matrix
Last Updated : 17 Jan, 2023



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

// C++ code to swap the element of first

// and last column and display the result

#include <iostream>

using namespace std;

#define n 4

void interchangeFirstLast(int m[][n])

// swapping of element between first


// and last columns

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

int t = m[i][0];

m[i][0] = m[i][n - 1];

m[i][n - 1] = t;

// Driver function

int main()

// input in the array

int m[n][n] = {{8, 9, 7, 6},

{4, 7, 6, 5},

{3, 2, 1, 8},

{9, 9, 7, 7}};
interchangeFirstLast(m);

// printing the interchanged matrix

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

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

cout << m[i][j] << " ";

cout << endl;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
6 9 7 8
5 7 6 4
8 2 1 3
7 9 7 9

C++ Pointers Programs


C++ Pointers
Last Updated : 25 Oct, 2022




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

How to use a pointer?


 Define a pointer variable
 Assigning the address of a variable to a pointer using the unary operator (&) which
returns the address of that variable.
 Accessing the value stored in the address using unary operator (*) which returns
the value of the variable located at the address specified by its operand.
The reason we associate data type with a pointer is that it knows how many bytes
the data is stored in. When we increment a pointer, we increase the pointer by the
size of the data type to which it points.

 C++

// C++ program to illustrate Pointers

#include <bits/stdc++.h>

using namespace std;

void geeks()

{
int var = 20;

// declare pointer variable

int* ptr;

// note that data type of ptr and var must be same

ptr = &var;

// assign the address of a variable to a pointer

cout << "Value at ptr = " << ptr << "\n";

cout << "Value at var = " << var << "\n";

cout << "Value at *ptr = " << *ptr << "\n";

// Driver program

int main()

geeks();

return 0;
}

Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20

References and Pointers


There are 3 ways to pass C++ arguments to a function:
 Call-By-Value
 Call-By-Reference with a Pointer Argument
 Call-By-Reference with a Reference Argument
 C++

// C++ program to illustrate call-by-methods

#include <bits/stdc++.h>

using namespace std;

// Pass-by-Value

int square1(int n)

// Address of n in square1() is not the same as n1 in

// main()
cout << "address of n1 in square1(): " << &n << "\n";

// clone modified inside the function

n *= n;

return n;

// Pass-by-Reference with Pointer Arguments

void square2(int* n)

// Address of n in square2() is the same as n2 in main()

cout << "address of n2 in square2(): " << n << "\n";

// Explicit de-referencing to get the value pointed-to

*n *= *n;

// Pass-by-Reference with Reference Arguments

void square3(int& n)

{
// Address of n in square3() is the same as n3 in main()

cout << "address of n3 in square3(): " << &n << "\n";

// Implicit de-referencing (without '*')

n *= n;

void geeks()

// Call-by-Value

int n1 = 8;

cout << "address of n1 in main(): " << &n1 << "\n";

cout << "Square of n1: " << square1(n1) << "\n";

cout << "No change in n1: " << n1 << "\n";

// Call-by-Reference with Pointer Arguments

int n2 = 8;

cout << "address of n2 in main(): " << &n2 << "\n";

square2(&n2);
cout << "Square of n2: " << n2 << "\n";

cout << "Change reflected in n2: " << n2 << "\n";

// Call-by-Reference with Reference Arguments

int n3 = 8;

cout << "address of n3 in main(): " << &n3 << "\n";

square3(n3);

cout << "Square of n3: " << n3 << "\n";

cout << "Change reflected in n3: " << n3 << "\n";

// Driver program

int main() { geeks(); }

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

// C++ program to illustrate Array Name as Pointers

#include <bits/stdc++.h>

using namespace std;

void geeks()

// Declare an array

int val[3] = { 5, 10, 20 };

// declare pointer variable


int* ptr;

// Assign the address of val[0] to ptr

// We can use ptr=&val[0];(both are same)

ptr = val;

cout << "Elements of the array are: ";

cout << ptr[0] << " " << ptr[1] << " " << ptr[2];

// Driver program

int main() { geeks(); }

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>

using namespace std;

void geeks()

// Declare an array

int v[3] = { 10, 100, 200 };

// declare pointer variable

int* ptr;

// Assign the address of v[0] to ptr

ptr = v;

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

cout << "Value at ptr = " << ptr << "\n";


cout << "Value at *ptr = " << *ptr << "\n";

// Increment pointer ptr by 1

ptr++;

// Driver program

int main() { geeks(); }

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)

Pointers and String literals


String literals are arrays containing null-terminated character sequences. String literals
are arrays of type character plus terminating null-character, with each of the elements
being of type const char (as characters of string can’t be modified).

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

// C++ program to illustrate Void Pointer

#include <bits/stdc++.h>

using namespace std;


void increase(void* data, int ptrsize)

if (ptrsize == sizeof(char)) {

char* ptrchar;

// Typecast data to a char pointer

ptrchar = (char*)data;

// Increase the char stored at *ptrchar by 1

(*ptrchar)++;

cout << "*data points to a char"

<< "\n";

else if (ptrsize == sizeof(int)) {

int* ptrint;

// Typecast data to a int pointer

ptrint = (int*)data;
// Increase the int stored at *ptrchar by 1

(*ptrint)++;

cout << "*data points to an int"

<< "\n";

void geek()

// Declare a character

char c = 'x';

// Declare an integer

int i = 10;

// Call increase function using a char and int address

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

int main() { geek(); }

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



An array of pointers is an array of pointer variables. It is also known as pointer arrays.


We will discuss how to create a 1D and 2D array of pointers dynamically. The
word dynamic signifies that the memory is allocated during the runtime, and it
allocates memory in Heap Section. In a Stack, memory is limited but is depending
upon which language/OS is used, the average size is 1MB.
Dynamic 1D Array in C++: An array of pointers is a type of array that consists of
variables of the pointer type. It means that those variables can point to some other
array elements.
Example:
int *p[3];
// Now P[0], P[1], P[2] can point to int memory blocks.
In a dynamically allocated array of size N, the block is created in the heap and returns
the address of the first memory block. By using that address every element can be
accessed. The dynamic array in C++ one should be familiar with the new
keywords or malloc(), calloc() can be used.
Syntax:
<dataType> * <pointer name> = new <dataType> [<size>];
Example:
int *p = new int [5];
Accessing Elements of a Dynamic Array:
 1. 1D array of size N(= 5) is created and the base address is assigned to the
variable P. If the below statement is written then the output is 1000.
cout << p;
 If the value in the 1000th address is wanted then dereferenced it using the *
(asterisk) symbol as illustrated below:
cout << *P;
// It is the same as P[0]. The output is 23.
Basic Pointer Arithmetic: Below is some points regarding Pointer Arithmetic:
 *(P + 1):
P = 1000 and 1 = sizeof(int) = 4 bytes.
Hence, *(1004) and dereferencing by * (asterisk) symbol. Now, the final result is 38.
 *(P) + 1:
P = 1000
Hence, *(1000) and dereferencing by * (asterisk) symbol and then by adding 1
modifies the result to 23 + 1 = 24.
Below is the C++ program to illustrate the above concepts:

 C++

// C++ program to illustrate the concepts

// of creating 1D array of pointers


#include <iostream>

using namespace std;

// Driver Code

int main()

// Dynamically creating the array

// of size = 5

int* p = new int[5];

// Initialize the array p[] as

// {10, 20, 30, 40, 50}

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

p[i] = 10 * (i + 1);

// Print the values using pointers

cout << *p << endl;


cout << *p + 1 << endl;

cout << *(p + 1) << endl;

cout << 2 [p] << endl;

cout << p[2] << endl;

*p++;

// Pointing to next location

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

// C++ program to illustrate the concepts

// of creating 2-D array of pointers

#include <iostream>
using namespace std;

// Driver Code

int main()

int N = 3;

// Creating the array of pointers

// of size N

int** p = new int*[N];

int x = 1;

// For multiplying

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

p[i] = new int[N];

// Creating N sized int memory


// block

for (int j = 0; j < N; j++, x++) {

p[i][j] = 10 * x;

// The above statement can

// also be written as:

// *(*(p+i)+j) = 10 * x

// Print the values using pointers

cout << *p << endl;

cout << **p << endl;

cout << *p + 1 << endl;

cout << **p + 1 << endl;

cout << *(*(p + 1) + 0) << endl;

cout << p[2][2] << endl;


return 0;

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

// C Program to demonstrate that a void pointer

// can hold the address of any type-castable type


#include <stdio.h>

int main()

int a = 10;

char b = 'x';

// void pointer holds address of int 'a'

void* p = &a;

// void pointer holds address of char 'b'

p = &b;

Time Complexity: O(1)


Auxiliary Space: O(1)

Properties of Void Pointers

1. void pointers cannot be dereferenced.


Example
The following program doesn’t compile.

 C

// C Program to demonstrate that a void pointer


// cannot be dereferenced

#include <stdio.h>

int main()

int a = 10;

void* ptr = &a;

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

// C program to dereference the void

// pointer to access the value


#include <stdio.h>

int main()

int a = 10;

void* ptr = &a;

// The void pointer 'ptr' is cast to an integer pointer

// using '(int*)ptr' Then, the value is dereferenced

// with `*(int*)ptr` to get the value at that memory

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

// C program to demonstrate the usage

// of a void pointer to perform pointer

// arithmetic and access a specific memory location

#include <stdio.h>

int main()

// Declare and initialize an integer array 'a' with two

// elements

int a[2] = { 1, 2 };

// Declare a void pointer and assign the address of

// array 'a' to it

void* ptr = &a;

// Increment the pointer by the size of an integer


ptr = ptr + sizeof(int);

// The void pointer 'ptr' is cast to an integer

// pointer using '(int*)ptr' Then, the value is

// dereferenced with `*(int*)ptr` to get the value at

// that memory location

printf("%d", *(int*)ptr);

return 0;

Output
2
Time Complexity: O(1)
Auxiliary Space: O(1)
References in C++
Last Updated : 30 Mar, 2023



When a variable is declared as a reference, it becomes an alternative name for an existing


variable. A variable can be declared as a reference by putting ‘&’ in the declaration.
Also, we can define a reference variable as a type of variable that can act as a reference to
another variable. ‘&’ is used for signifying the address of a variable or any memory.
Variables associated with reference variables can be accessed either by its name or by the
reference variable associated with it.
Prerequisite: Pointers in C++
Syntax:
data_type &ref = variable;
Example:
 C++

// C++ Program to demonstrate

// use of references

#include <iostream>

using namespace std;

int main()

int x = 10;

// ref is a reference to x.

int& ref = x;

// Value of x is now changed to 20

ref = 20;

cout << "x = " << x << '\n';


// Value of x is now changed to 30

x = 30;

cout << "ref = " << ref << '\n';

return 0;

Output:
x = 20
ref = 30
Applications 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++

// C++ Program to demonstrate

// Passing of references as parameters

#include <iostream>
using namespace std;

// Function having parameters as

// references

void swap(int& first, int& second)

int temp = first;

first = second;

second = temp;

// Driver function

int main()

// Variables declared

int a = 2, b = 3;

// function called

swap(a, b);
// changes can be seen

// printing both variables

cout << a << " " << b;

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

// If we remove & in below function, a new


// copy of the student object is created.
// We use const to avoid accidental updates
// in the function as the purpose of the function
// is to print s only.
void print(const Student &s)
{
cout << s.name << " " << s.address << " " << s.rollNo
<< '\n';
}
3. In For Each Loop to modify all objects:
We can use references for each loop to modify all elements.
Example:
 C++

// C++ Program for changing the

// values of elements while traversing

// using references

#include <iostream>

#include <vector>

using namespace std;

// Driver code

int main()

vector<int> vect{ 10, 20, 30, 40 };

// We can modify elements if we

// use reference

for (int& x : vect) {


x = x + 5;

// Printing elements

for (int x : vect) {

cout << x << " ";

cout << '\n';

return 0;

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

// C++ Program to use references

// For Each Loop to avoid the

// copy of objects
#include <iostream>

#include <vector>

using namespace std;

// Driver code

int main()

// Declaring vector

vector<string> vect{ "geeksforgeeks practice",

"geeksforgeeks write",

"geeksforgeeks ide" };

// We avoid copy of the whole string

// object by using reference.

for (const auto& x : vect) {

cout << x << '\n';

}
return 0;

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

// C++ Program to demonstrate

// references and pointers

#include <iostream>

using namespace std;


// Driver Code

int main()

// simple or ordinary variable.

int i = 10;

// single pointer

int* p = &i;

// double pointer

int** pt = &p;

// triple pointer

int*** ptr = &pt;

// All the above pointers differ in the value they store

// or point to.

cout << "i = " << i << "\t"


<< "p = " << p << "\t"

<< "pt = " << pt << "\t"

<< "ptr = " << ptr << '\n';

// simple or ordinary variable

int a = 5;

int& S = a;

int& S0 = S;

int& S1 = S0;

// All the references do not differ in their

// values as they all refer to the same variable.

cout << "a = " << a << "\t"

<< "S = " << S << "\t"

<< "S0 = " << S0 << "\t"

<< "S1 = " << S1 << '\n';

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.

Advantages of using References

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>

using namespace std;

int& fun()
{

static int x = 10;

return x;

int main()

fun() = 30;

cout << fun();

return 0;

Output

30
Question 2
 C++

#include <iostream>

using namespace std;

int fun(int& x) { return x; }


int main()

cout << fun(10);

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>

using namespace std;

void swap(char*& str1, char*& str2)

{
char* temp = str1;

str1 = str2;

str2 = temp;

int main()

char* str1 = "GEEKS";

char* str2 = "FOR GEEKS";

swap(str1, str2);

cout << "str1 is " << str1 << '\n';

cout << "str2 is " << str2 << '\n';

return 0;

Output

str1 is FOR GEEKS


str2 is GEEKS
Question 4
 C++

#include <iostream>
using namespace std;

int main()

int x = 10;

int* ptr = &x;

int&* ptr1 = ptr;

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>

using namespace std;

int main()

int* ptr = NULL;


int& ref = *ptr;

cout << ref << '\n';

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>

using namespace std;

int& fun()

int x = 10;

return x;

int main()

{
fun() = 30;

cout << fun();

return 0;

Output

Function Pointer in C++


Last Updated : 27 Jan, 2023



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.

Function Pointer in C++

Syntax:
return_type (*FuncPtr) (parameter type, ....);

Referencing and Dereferencing of the Function Pointer in C++

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 used to call the function


In this, we see how we point a pointer to a function and call it using that pointer. It is
an efficient way to use
Example:
 C++

// C++ program to implementation

// Function Pointer

#include <iostream>

using namespace std;

int multiply(int a, int b) { return a * b; }

int main()

int (*func)(int, int);


// func is pointing to the multiplyTwoValues function

func = multiply;

int prod = func(15, 2);

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.

Passing a function pointer as a parameter


When declaring a function pointer to store the memory address of the function but,
when we want to pass the return value to the next function. We have two methods to
perform this task. First, either pass the value we got or second pass the function
pointer that already exists.
Example:
 C++
// C++ Program for demonstrating

// function pointer as pointer

#include <iostream>

using namespace std;

const int a = 15;

const int b = 2;

// Function for Multiplication

int multiply() { return a * b; }

// Function containing function pointer

// as parameter

void print(int (*funcptr)())

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



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
How to use a pointer?
 Define a pointer variable
 Assigning the address of a variable to a pointer using the unary operator (&) which
returns the address of that variable.
 Accessing the value stored in the address using unary operator (*) which returns
the value of the variable located at the address specified by its operand.
The reason we associate data type with a pointer is that it knows how many bytes
the data is stored in. When we increment a pointer, we increase the pointer by the
size of the data type to which it points.
 C++

// C++ program to illustrate Pointers

#include <bits/stdc++.h>

using namespace std;

void geeks()

int var = 20;


// declare pointer variable

int* ptr;

// note that data type of ptr and var must be same

ptr = &var;

// assign the address of a variable to a pointer

cout << "Value at ptr = " << ptr << "\n";

cout << "Value at var = " << var << "\n";

cout << "Value at *ptr = " << *ptr << "\n";

// Driver program

int main()

geeks();

return 0;

Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20

References and Pointers


There are 3 ways to pass C++ arguments to a function:
 Call-By-Value
 Call-By-Reference with a Pointer Argument
 Call-By-Reference with a Reference Argument
 C++

// C++ program to illustrate call-by-methods

#include <bits/stdc++.h>

using namespace std;

// Pass-by-Value

int square1(int n)

// Address of n in square1() is not the same as n1 in

// main()

cout << "address of n1 in square1(): " << &n << "\n";

// clone modified inside the function


n *= n;

return n;

// Pass-by-Reference with Pointer Arguments

void square2(int* n)

// Address of n in square2() is the same as n2 in main()

cout << "address of n2 in square2(): " << n << "\n";

// Explicit de-referencing to get the value pointed-to

*n *= *n;

// Pass-by-Reference with Reference Arguments

void square3(int& n)

// Address of n in square3() is the same as n3 in main()

cout << "address of n3 in square3(): " << &n << "\n";


// Implicit de-referencing (without '*')

n *= n;

void geeks()

// Call-by-Value

int n1 = 8;

cout << "address of n1 in main(): " << &n1 << "\n";

cout << "Square of n1: " << square1(n1) << "\n";

cout << "No change in n1: " << n1 << "\n";

// Call-by-Reference with Pointer Arguments

int n2 = 8;

cout << "address of n2 in main(): " << &n2 << "\n";

square2(&n2);

cout << "Square of n2: " << n2 << "\n";

cout << "Change reflected in n2: " << n2 << "\n";


// Call-by-Reference with Reference Arguments

int n3 = 8;

cout << "address of n3 in main(): " << &n3 << "\n";

square3(n3);

cout << "Square of n3: " << n3 << "\n";

cout << "Change reflected in n3: " << n3 << "\n";

// Driver program

int main() { geeks(); }

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

// C++ program to illustrate Array Name as Pointers

#include <bits/stdc++.h>

using namespace std;

void geeks()

// Declare an array

int val[3] = { 5, 10, 20 };

// declare pointer variable

int* ptr;

// Assign the address of val[0] to ptr


// We can use ptr=&val[0];(both are same)

ptr = val;

cout << "Elements of the array are: ";

cout << ptr[0] << " " << ptr[1] << " " << ptr[2];

// Driver program

int main() { geeks(); }

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>

using namespace std;

void geeks()

// Declare an array

int v[3] = { 10, 100, 200 };

// declare pointer variable

int* ptr;

// Assign the address of v[0] to ptr

ptr = v;

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

cout << "Value at ptr = " << ptr << "\n";

cout << "Value at *ptr = " << *ptr << "\n";


// Increment pointer ptr by 1

ptr++;

// Driver program

int main() { geeks(); }

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)

Pointers and String literals


String literals are arrays containing null-terminated character sequences. String literals
are arrays of type character plus terminating null-character, with each of the elements
being of type const char (as characters of string can’t be modified).

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

// C++ program to illustrate Void Pointer

#include <bits/stdc++.h>

using namespace std;

void increase(void* data, int ptrsize)

{
if (ptrsize == sizeof(char)) {

char* ptrchar;

// Typecast data to a char pointer

ptrchar = (char*)data;

// Increase the char stored at *ptrchar by 1

(*ptrchar)++;

cout << "*data points to a char"

<< "\n";

else if (ptrsize == sizeof(int)) {

int* ptrint;

// Typecast data to a int pointer

ptrint = (int*)data;

// Increase the int stored at *ptrchar by 1


(*ptrint)++;

cout << "*data points to an int"

<< "\n";

void geek()

// Declare a character

char c = 'x';

// Declare an integer

int i = 10;

// Call increase function using a char and int address

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

int main() { geek(); }

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

// C++ Program to demonstrate working of a function

#include <iostream>

using namespace std;


// Following function that takes two parameters 'x' and 'y'

// as input and returns max of two input numbers

int max(int x, int y)

if (x > y)

return x;

else

return y;

// main function that doesn't receive any parameter and

// returns integer

int main()

int a = 10, b = 20;

// Calling above function to find max of 'a' and 'b'


int m = max(a, b);

cout << "m is " << m;

return 0;

Output
m is 20

Time complexity: O(1)


Space complexity: O(1)
Why Do We Need Functions?
 Functions help us in reducing code redundancy. If functionality is performed at
multiple places in software, then rather than writing the same code, again and
again, we create a function and call it everywhere. This also helps in maintenance
as we have to make changes in only one place if we make changes to the
functionality in future.
 Functions make code modular. Consider a big file having many lines of code. It
becomes really simple to read and use the code, if the code is divided into
functions.
 Functions provide abstraction. For example, we can use library functions without
worrying about their internal work.
Function Declaration
A function declaration tells the compiler about the number of parameters, data types
of parameters, and returns type of function. Writing parameter names in the function
declaration is optional but it is necessary to put them in the definition. Below is an
example of function declarations. (parameter names are not present in the below
declarations)
Function Declaration

Example:
 C++

// C++ Program to show function that takes

// two integers as parameters and returns

// an integer

int max(int, int);

// A function that takes an int

// pointer and an int variable

// as parameters and returns


// a pointer of type int

int* swap(int*, int);

// A function that takes

// a char as parameter and

// returns a reference variable

char* call(char b);

// A function that takes a

// char and an int as parameters

// and returns an integer

int fun(char, int);

Types of Functions
Types of Function in C++

User Defined Function


User-defined functions are user/customer-defined blocks of code specially customized
to reduce the complexity of big programs. They are also commonly known as “tailor-
made functions” which are built only to satisfy the condition in which the user is
facing issues meanwhile reducing the complexity of the whole program.
Library Function
Library functions are also called “built-in Functions“. These functions are part of a
compiler package that is already defined and consists of a special function with
special and different meanings. Built-in Function gives us an edge as we can directly
use them without defining them whereas in the user-defined function we have to
declare and define a function before using them.
For Example: sqrt(), setw(), strcat(), etc.
Parameter Passing to Functions
The parameters passed to the function are called actual parameters. For example, in
the program below, 5 and 10 are actual parameters.
The parameters received by the function are called formal parameters. For example,
in the above program x and y are formal parameters.

Formal Parameter and Actual Parameter

There are two most popular ways to pass parameters:


1. Pass by Value: In this parameter passing method, values of actual parameters are
copied to the function’s formal parameters. The actual and formal parameters are
stored in different memory locations so any changes made in the functions are not
reflected in the actual parameters of the caller.

2. Pass by Reference: Both actual and formal parameters refer to the same locations,
so any changes made inside the function are 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++

// C++ Program to demonstrate function definition

#include <iostream>

using namespace std;

void fun(int x)

// definition of

// function

x = 30;

int main()

{
int x = 20;

fun(x);

cout << "x = " << x;

return 0;

Output
x = 20

Time complexity: O(1)


Space complexity: O(1)
Functions Using Pointers
The function fun() expects a pointer ptr to an integer (or an address of an integer). It
modifies the value at the address ptr. The dereference operator * is used to access the
value at an address. In the statement ‘*ptr = 30’, the value at address ptr is changed to
30. The address operator & is used to get the address of a variable of any data type. In
the function call statement ‘fun(&x)’, the address of x is passed so that x can be
modified using its address.
 C++

// C++ Program to demonstrate working of

// function using pointers

#include <iostream>

using namespace std;


void fun(int* ptr) { *ptr = 30; }

int main()

int x = 20;

fun(&x);

cout << "x = " << x;

return 0;

Output
x = 30

Time complexity: O(1)


Space complexity: O(1)
Difference between call by value and call by reference in C+
+
Call by value Call by reference

A copy of the value is passed to the An address of value is passed to the


function function
Call by value Call by reference

Changes made inside the function are


Changes made inside the function are not
reflected
reflected on other functions
outside the function as well

Actual and formal arguments will be Actual and formal arguments will be
created at created at
different memory location same memory location.

Points to Remember About Functions in C++


1. Most C++ program has a function called main() that is called by the operating
system when a user runs the program.
2. Every function has a return type. If a function doesn’t return any value, then void is
used as a return type. Moreover, if the return type of the function is void, we still can
use the return statement in the body of the function definition by not specifying any
constant, variable, etc. with it, by only mentioning the ‘return;’ statement which
would symbolize the termination of the function as shown below:
 C++

void function name(int a)

....... // Function Body

return; // Function execution would get terminated

3. To declare a function that can only be called without any parameter, we should use
“void fun(void)“. As a side note, in C++, an empty list means a function can only be
called without any parameter. In C++, both void fun() and void fun(void) are same.
Main Function
The main function is a special function. Every C++ program must contain a function
named main. It serves as the entry point for the program. The computer will start
running the code from the beginning of the main function.
Types of Main Functions
1. Without parameters:

 CPP

// Without Parameters

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

2. With parameters:

 CPP

// With Parameters

int main(int argc, char* const argv[]) { ... return 0; }

The reason for having the parameter option for the main function is to allow input
from the command line. When you use the main function with parameters, it saves
every group of characters (separated by a space) after the program name as elements
in an array named argv.
Since the main function has the return type of int, the programmer must always have a
return statement in the code. The number that is returned is used to inform the calling
program what the result of the program’s execution was. Returning 0 signals that there
were no problems.
C++ Recursion
When function is called within the same function, it is known as recursion in C++.
The function which calls the same function, is known as recursive function.
A function that calls itself, and doesn’t perform any task after function call, is known
as tail recursion. In tail recursion, we generally call the same function with return
statement.
Syntax:
 C++
recursionfunction()

recursionfunction(); // calling self function

To know more see this article.


C++ Passing Array to Function
In C++, to reuse the array logic, we can create a function. To pass an array to a
function in C++, we need to provide only the array name.
function_name(array_name[]); //passing array to function

Example: Print the minimum number in the given array.


 C++

#include <iostream>

using namespace std;

void printMin(int arr[5]);

int main()

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

printMin(ar); // passing array to function

void printMin(int arr[5])


{

int min = arr[0];

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

if (min > arr[i]) {

min = arr[i];

cout << "Minimum element is: " << min << "\n";

// Code submitted by Susobhan Akhuli

Output
Minimum element is: 10

Time complexity: O(n) where n is the size of the array


Space complexity: O(n) where n is the size of the array.
C++ Overloading (Function)
If we create two or more members having the same name but different in number or
type of parameters, it is known as C++ overloading. In C++, we can overload:
 methods,
 constructors and
 indexed properties
Types of overloading in C++ are:
 Function overloading
 Operator overloading
C++ Function Overloading
Function Overloading is defined as the process of having two or more functions with
the same name, but different parameters. In function overloading, the function is
redefined by using either different types or number of arguments. It is only through
these differences a compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the
program because you don’t need to use different names for the same action.
Example: changing number of arguments of add() method
 C++

// program of function overloading when number of arguments

// vary

#include <iostream>

using namespace std;

class Cal {

public:

static int add(int a, int b) { return a + b; }

static int add(int a, int b, int c)

return a + b + c;

};

int main(void)

{
Cal C; // class object declaration.

cout << C.add(10, 20) << endl;

cout << C.add(12, 20, 23);

return 0;

// Code Submitted By Susobhan Akhuli

Output
30
55

Time complexity: O(1)


Space complexity: O(1)
Example: when the type of the arguments vary.
 C++

// Program of function overloading with different types of

// arguments.

#include <iostream>

using namespace std;

int mul(int, int);


float mul(float, int);

int mul(int a, int b) { return a * b; }

float mul(double x, int y) { return x * y; }

int main()

int r1 = mul(6, 7);

float r2 = mul(0.2, 3);

cout << "r1 is : " << r1 << endl;

cout << "r2 is : " << r2 << endl;

return 0;

// Code Submitted By Susobhan Akhuli

Output
r1 is : 42
r2 is : 0.6

Time Complexity: O(1)


Space Complexity: O(1)
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked among the
overloaded function, this situation is known as function overloading ambiguity.
When the compiler shows the ambiguity error, the compiler does not run the program.
Causes of Ambiguity:
 Type Conversion.
 Function with default arguments.
 Function with pass-by-reference.
Type Conversion:-
 C++

#include <iostream>

using namespace std;

void fun(int);

void fun(float);

void fun(int i) { cout << "Value of i is : " << i << endl; }

void fun(float j)

cout << "Value of j is : " << j << endl;

int main()

fun(12);

fun(1.2);
return 0;

// Code Submitted By Susobhan Akhuli

The above example shows an error “call of overloaded ‘fun(double)’ is ambiguous“.


The fun(10) will call the first function. The fun(1.2) calls the second function
according to our prediction. But, this does not refer to any function as in C++, all the
floating point constants are treated as double not as a float. If we replace float to
double, the program works. Therefore, this is a type conversion from float to double.
Function with Default Arguments:-
 C++

#include <iostream>

using namespace std;

void fun(int);

void fun(int, int);

void fun(int i) { cout << "Value of i is : " << i << endl; }

void fun(int a, int b = 9)

cout << "Value of a is : " << a << endl;

cout << "Value of b is : " << b << endl;


}

int main()

fun(12);

return 0;

// Code Submitted By Susobhan Akhuli

The above example shows an error “call of overloaded ‘fun(int)’ is ambiguous“. The
fun(int a, int b=9) can be called in two ways: first is by calling the function with one
argument, i.e., fun(12) and another way is calling the function with two arguments,
i.e., fun(4,5). The fun(int i) function is invoked with one argument. Therefore, the
compiler could not be able to select among fun(int i) and fun(int a,int b=9).
Function with Pass By Reference:-
 C++

#include <iostream>

using namespace std;

void fun(int);

void fun(int&);
int main()

int a = 10;

fun(a); // error, which fun()?

return 0;

void fun(int x) { cout << "Value of x is : " << x << endl; }

void fun(int& b)

cout << "Value of b is : " << b << endl;

// Code Submitted By Susobhan Akhuli

The above example shows an error “call of overloaded ‘fun(int&)’ is ambiguous“.


The first function takes one integer argument and the second function takes a
reference parameter as an argument. In this case, the compiler does not know which
function is needed by the user as there is no syntactical difference between the fun(int)
and fun(int &).
Friend Function
 A friend function is a special function in C++ which in spite of not being a
member function of a class has the privilege to access private and protected data of
a class.
 A friend function is a non-member function or an ordinary function of a class,
which is declared by 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 but not in the
function definition.
 When the friend function is called neither the name of the object nor the dot
operator is used. 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, private, or
protected.
Declaration of friend function in C++
Syntax:
class <class_name> {
friend <return_type> <function_name>(argument/s);
};

Example_1: Find the largest of two numbers using Friend Function


 C++

#include <iostream>

using namespace std;

class Largest {

int a, b, m;

public:

void set_data();

friend void find_max(Largest);

};
void Largest::set_data()

cout << "Enter the first number : ";

cin >> a;

cout << "\nEnter the second number : ";

cin >> b;

void find_max(Largest t)

if (t.a > t.b)

t.m = t.a;

else

t.m = t.b;

cout << "\nLargest number is " << t.m;

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

using namespace std;

/* local variable is same as a member's name */

class Test

private:

int x;
public:

void setX (int x)

// The 'this' pointer is used to retrieve the object's x

// hidden by the local variable 'x'

this->x = x;

void print() { cout << "x = " << x << endl; }

};

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.

2) To return reference to the calling object

/* Reference to the calling object can be returned */

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>

using namespace std;

class Test

private:

int x;
int y;

public:

Test(int x = 0, int y = 0) { this->x = x; this->y = y; }

Test &setX(int a) { x = a; return *this; }

Test &setY(int b) { y = b; return *this; }

void print() { cout << "x = " << x << " y = " << y << endl; }

};

int main()

Test obj1(5, 5);

// Chained function calls. All calls modify the same object

// as the same object is returned by reference

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>

using namespace std;

class Test

private:

int x;

public:

Test(int x = 0) { this->x = x; }

void change(Test *t) { this = t; }

void print() { cout << "x = " << x << endl; }

};
int main()

Test obj(5);

Test *ptr = new Test (10);

obj.change(ptr);

obj.print();

return 0;

Question 2

#include<iostream>

using namespace std;

class Test

private:

int x;
int y;

public:

Test(int x = 0, int y = 0) { this->x = x; this->y = y; }

static void fun1() { cout << "Inside fun1()"; }

static void fun2() { cout << "Inside fun2()"; this->fun1(); }

};

int main()

Test obj;

obj.fun2();

return 0;

Question 3

#include<iostream>

using namespace std;


class Test

private:

int x;

int y;

public:

Test (int x = 0, int y = 0) { this->x = x; this->y = y; }

Test setX(int a) { x = a; return *this; }

Test setY(int b) { y = b; return *this; }

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>

using namespace std;

class Test

private:

int x;

int y;

public:

Test(int x = 0, int y = 0) { this->x = x; this->y = y; }

void setX(int a) { x = a; }

void setY(int b) { y = b; }

void destroy() { delete this; }

void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()

Test obj;

obj.destroy();

obj.print();

return 0;

Opaque Pointer in C++


Last Updated : 20 Jan, 2023



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;

Why Opaque pointer?


There are places where we just want to hint to the compiler that “Hey! This is some
data structure that will be used by our clients. Don’t worry, clients will provide its
implementation while preparing the compilation unit”. Such a type of design is robust
when we deal with shared code. Please see the below example:
Let’s say we are working on an app to deal with images. Since we are living in a
world where everything is moving to the cloud and devices are very affordable to buy,
we want to develop apps for windows, android, and apple platforms. So, it would be
nice to have a good design that is robust, scalable, and flexible as per our
requirements. We can have shared code that would be used by all platforms and then
different end-point can have platform-specific code. To deal with images, we have a
CImage class exposing APIs to deal with various image operations (scale, rotate,
move, save, etc).
Since all the platforms will be providing the same operations, we would define this
class in a header file. But the way an image is handled might differ across platforms.
Like Apple can have a different mechanism to access pixels of an image than
Windows does. This means that APIs might demand different sets of info to perform
operations. So to work on shared code, this is what we would like to do:
Image.h: A header file to store class declaration. We will create a header file that will
contain a class CImage which will provide an API to handle the image operations.
// This class provides API to deal with various
// image operations. Different platforms can
// implement these operations in different ways.
class CImage
{
public:
CImage();

~CImage();

// Opaque pointer

struct SImageInfo* pImageInfo;


void Rotate(double angle);

void Scale(double scaleFactorX,


double scaleFactorY);

void Move(int toX, int toY);

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

// destructor for CImage class

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;

// Initialize apple specific info here


}
void CImage::Rotate()
{
// Make use of apple specific SImageInfo
}
As it can be seen from the above example while defining the blueprint of the
CImage class we are only mentioning that there is a SImageInfo data structure.
The content of SImageInfo is unknown. Now it is the responsibility of
clients(windows, apple, android) to define that data structure and use it as per
their requirements. If in the future we want to develop an app for a new end-point
‘X’, the design is already there. We only need to define SImageInfo for end-point ‘X’
and use it accordingly.
Please note that the above-explained example is one way of doing this. Design is all
about discussion and requirements. A good design is decided to take many factors into
account. We can also have platform-specific classes like CImageWindows, and
CImageApple and put all platform-specific code there.
Downsides of Opaque pointers
It’s also important to note that opaque pointers can have some downsides, as well. For
example, because the client code cannot access the implementation details of the
object, it may be more difficult to debug or troubleshoot issues that arise.
Additionally, opaque pointers can make it more difficult to understand the
relationships between objects and their dependencies, which can make it harder to
maintain and evolve the codebase over time.
Another potential downside is that opaque pointers can increase the complexity of the
codebase, and make it harder to understand how the library is implemented. If a
library is large, it can be difficult to understand the relationships between different
parts of the codebase, and how they interact.
To mitigate these downsides, it’s important to use opaque pointers judiciously, and to
provide clear and comprehensive documentation of the library’s interface. It’s also
important to consider other options, such as PIMPL or Handle-Body idiom, and
choose the one that best fits the needs of the project.
In summary, opaque pointers are a technique that can be used to hide the
implementation details of an object and provide a level of abstraction in C++. They
are useful for hiding the implementation details of an object from the client code, and
also for providing a level of abstraction. However, it’s important to use them
judiciously and to consider other options as well.
It is also important to note that opaque pointers can cause a performance overhead, as
it requires extra memory to store the pointer, and an additional level of indirection
when accessing the object. It also increases the complexity of memory management as
the client code cannot directly deallocate the memory of the object. The library must
provide functions to handle the memory management, such as creating and destroying
the object, or allocating and deallocating memory for the object.
Additionally, opaque pointers can make it more difficult to write unit tests for the
client code as the actual implementation of the object is hidden from the client code.
This can make it more difficult to test the client code’s interaction with the object.
To mitigate these downsides, it’s important to use opaque pointers judiciously, and to
provide clear and comprehensive documentation of the library’s interface and memory
management. It’s also important to consider other options, such as PIMPL or Handle-
Body idiom, and choose the one that best fits the needs of the project.
In conclusion, opaque pointers are a powerful technique that can be used to hide the
implementation details of an object and provide a level of abstraction in C++.
However, it’s important to use them judiciously and to be aware of the potential
downsides, such as performance overhead, memory management, and testing. It’s also
important to consider other options and choose the one that best fits the needs of the
project.
C++ String Programs
5 Different Methods to Find Length of a String
in C++
Last Updated : 19 Jun, 2023



The string is a sequence of characters or an array of characters. The declaration and


definition of the string using an array of chars are similar to the declaration and
definition of an array of any other data type.
Examples:
Input: "Geeksforgeeks"
Output: 13

Input: "Geeksforgeeks \0 345"


Output: 14
Important Points
1. The constructor of the String class will set it to the C++ style string, which ends at
the ‘\0‘.
2. The size() function is consistent with other STL containers (like vector, map, etc.),
and length() is consistent with most people’s intuitive notion of character strings
like a word, sentence, or paragraph. We say a paragraph’s length, not its size, so
length() is to make things more readable.
Methods to Find the Length of a String
There are few methods to find the length of a string is mentioned below:
 Using string::size
 Using string::length:
 Using the C library function strlen() method:
 Using while loop:
 Using for loop:

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

// C++ program to find length

// of a string

#include <iostream>

#include <string.h>

using namespace std;

// Driver code

int main()

// String obj

string str = "GeeksforGeeks";

// size of string object using size() method

cout << str.size() << endl;


return 0;

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

// C++ program to find length

// of a string

#include <iostream>

#include <string.h>

using namespace std;

// Driver code

int main()

{
// String obj

string str = "GeeksforGeeks";

// size of string object using length method

cout << str.length() << endl;

return 0;

Output
13

3. Using strlen() Method

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

// C++ program to find length

// of a string

#include <iostream>

#include <string.h>
using namespace std;

// Driver code

int main()

// String obj

string str = "GeeksforGeeks";

// size using old style

// size of string object using strlen function

cout << strlen(str.c_str()) << endl;

return 0;

Output
13

4. Using a while loop

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

// C++ program to find length

// of a string

#include <iostream>

#include <string.h>

using namespace std;

// Driver code

int main()

// String obj

string str = "GeeksforGeeks";

// The constructor of string will set it to the

// C-style string,

// which ends at the '\0'

// size of string object Using while loop


// while 'NOT NULL'

int i = 0;

while (str[i])

i++;

cout << i << endl;

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

// C++ program to find length

// of a string

#include <iostream>

#include <string.h>
using namespace std;

// Driver code

int main()

int i;

// String obj

string str = "GeeksforGeeks";

// The constructor of string will set it to the

// C-style string,

// which ends at the '\0'

// size of string object using for loop

// for(; NOT NULL

for (i = 0; str[i]; i++);

cout << i << endl;


return 0;

Output
13

Different ways to access characters in a given


String in C++
Last Updated : 19 Mar, 2023



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

// C++ program to implement

// the operator[]

#include <iostream>

using namespace std;

// Driver code

int main()

string str("GeeksforGeeks");

cout << str[4];

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity : O(N)


Space Complexity : O(1)
Output
s
at()
at() function is used for accessing individual characters. With this function, character
by character can be accessed from the given string.
Syntax-
char& string::at (size_type idx)
Below is the C++ to implement at()-

 C++

// C++ program to implement

// at()

#include <iostream>

using namespace std;

// Driver code

int main()

string s("GeeksForGeeks");

cout << s.at(4);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity : O(N)


Space Complexity : O(1)
Output
s
substr()
substr() function is used for retrieving a substring from a given string. This function
takes two values start and len.
 string.h is the header file required for string functions.
 The starting index is 0.
Syntax-
string substr (size_type start, size_type len);
Here,
start: Position of first character to be copied
len: Length of the sub-string.
Below is the C++ program to implement the substr() function-

 C++

// C++ program to implement

// the substr() function

#include <iostream>

using namespace std;

// Driver code

int main()

string s("GeeksForGeeks");

cout << s.substr(1, 5);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to implement

// the find() function

#include <iostream>

using namespace std;

// Driver code

int main()

{
string s("GeeksForGeeks");

cout << s.find("For");

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to implement

// the find_first_of() function

#include <iostream>

using namespace std;


// Driver code

int main()

string s("GeeksForGeeks");

cout << s.find_first_of('s');

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to implement


// the find_last_of() function

#include <iostream>

using namespace std;

// Driver code

int main()

string s("GeeksForGeeks");

cout << s.find_last_of('s');

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
12

C++ Program to Determine the Unicode Code


Point at a Given Index
Last Updated : 07 Oct, 2022



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

// C++ program to demonstrate

// Unicode Code point

// at a given index

#include <iostream>

using namespace std;

// Driver code

int main()

{
// define input array/string

char arr[] = "GeEkS";

int code;

// print arr

cout << " Input String = " << arr;

// execute a loop to traverse the arr elements

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

code = arr[i];

// display unicode code point at i-th index

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

C++ Program to Replace a Character in a


String
Last Updated : 11 Apr, 2023



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

// C++ program to replace c1 with c2

// and c2 with c1

#include <bits/stdc++.h>

using namespace std;

string replace(string s,
char c1, char c2)

int l = s.length();

// loop to traverse in the string

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

// check for c1 and replace

if (s[i] == c1)

s[i] = c2;

// check for c2 and replace

else if (s[i] == c2)

s[i] = c1;

return s;

}
// Driver code

int main()

string s = "grrksfoegrrks";

char c1 = 'e', c2 = 'r';

cout << replace(s, c1, c2);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
geeksforgeeks
Time Complexity: O(n)
Auxiliary Space: O(n), because the program creates a copy of string s.

Two-Temporary-String Character Replacement

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>

using namespace std;

void replaceChar(string& S, char c1, char c2) {

string s1, s2;

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

char c1 = 'z', c2 = 'r';

// Replace characters in string

replaceChar(S, c1, c2);

// Print modified string

cout << "Modified string: " << S << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks


Output
Modified string: Omkhar

Comparing two strings in C++


Last Updated : 23 Jun, 2022



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

Input : Geeks, forGeeks


Output : Geeks is not equal to forGeeks
forGeeks is greater than Geeks
This problem can be solved using any of the following two methods
 C++ Relational operators
 CPP

// CPP code to implement relational

// operators on string objects

#include <iostream>

using namespace std;

void relationalOperation(string s1, string s2)


{

if (s1 != s2)

cout << s1 << " is not equal to " << s2 << endl;

if (s1 > s2)

cout << s1 << " is greater than " << s2 << endl;

else

cout << s2 << " is greater than " << s1 << endl;

else

cout << s1 << " is equal to " << s2 << endl;

// Driver code

int main()

string s1("Geeks");
string s2("forGeeks");

relationalOperation(s1, s2);

string s3("Geeks");

string s4("Geeks");

relationalOperation(s3, s4);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// CPP code perform relational

// operation using compare function

#include <iostream>
using namespace std;

void compareFunction(string s1, string s2)

// comparing both using inbuilt function

int x = s1.compare(s2);

if (x != 0) {

cout << s1

<< " is not equal to "

<< s2 << endl;

if (x > 0)

cout << s1

<< " is greater than "

<< s2 << endl;

else

cout << s2

<< " is greater than "


<< s1 << endl;

else

cout << s1 << " is equal to " << s2 << endl;

// Driver Code

int main()

string s1("Geeks");

string s2("forGeeks");

compareFunction(s1, s2);

string s3("Geeks");

string s4("Geeks");

compareFunction(s3, s4);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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.

Methods of Concatenate String


There are 6 methods to Concatenate String as mentioned below:
1. Using append( ) Function.
2. Using ‘+’ Operator.
3. Using strcat( ) Function.
4. Using C++ for Loop.
5. Using Inheritance.
6. Using the Friend Function and strcat() Function.
1. Using append() Function
The append() function is a member function of the std::string class. Using this function, we
can concatenate two std::string objects (C++ style strings) as shown in the below example.
Syntax:
string& string::append (const string& str);

Here,
str: String to be appended.
Below is the C++ program for string concatenation using the append() function:
 C++

// C++ Program for string

// concatenation using append

#include <iostream>

using namespace std;

// Driver code

int main()

string init("this is init");

string add(" added now");

// Appending the string.

init.append(add);
cout << init << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output

this is init added now


2. Using ‘+’ Operator
This is the easiest method for the concatenation of two strings. The + operator adds
strings and returns a concatenated string. This method only works for C++ style strings
(std::string objects) and doesn’t work on C style strings (character array).
Syntax:
string new_string = init + add;
Below is the C++ program for string concatenation using ‘+’ operator:
 C++

// C++ Program for string

// concatenation using '+' operator

#include <iostream>

using namespace std;

// Driver code

int main()

{
string init("this is init");

string add(" added now");

// Appending the string.

init = init + add;

cout << init << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output

this is init added now


3. Using strcat( ) Function
The C++ strcat( ) function is a built-in function defined in <string.h> header file. This
function concatenates the two strings init and add and the result is stored in the init string.
This function only works for C-style strings (character arrays) and doesn’t work for C++-
style strings (std::string objects).
Syntax:
char * strcat(char * init, const char * add);
Below is the C++ program for string concatenation using strcat() function:
 C++

// C++ Program for string

// concatenation using strcat


#include <iostream>

#include <string.h>

using namespace std;

// Driver code

int main()

char init[] = "this is init";

char add[] = " added now";

// Concatenating the string.

strcat(init, add);

cout << init << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output

this is init added now


4. Using for Loop
Using a loop is one of the most basic methods of string concatenation. Here, we are adding
elements one by one while traversing the whole string and then another string. The final
result will be the concatenated string formed from both strings.
Below is the C++ program for string concatenation using for loop:
 C++

// C++ Program for string

// concatenation using for loop

#include <iostream>

using namespace std;

// Driver code

int main()

string init("this is init");

string add(" added now");

string output;

// Adding element inside output

// from init

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


{

output += init[i];

// Adding element inside output

// fromt add

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

output += add[i];

cout << output << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output

this is init added now


5. Using Inheritance
Below is the C++ program for string concatenation using inheritance:
 C++

// C++ program for string concatenation


// using inheritance

#include <iostream>

#include <string>

using namespace std;

// Base class

class base

protected:

virtual string concatenate(string &str1,

string &str2) = 0;

};

// Derive class

class derive: protected base {

public:

string concatenate (string &str1,

string &str2)
{

string temp;

temp = str1 + str2;

return temp;

};

// Driver code

int main()

string init("this is init");

string add(" added now");

// Create string object

derive obj;

// Print string

cout << obj.concatenate (init, add);


return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output

this is init added now


6. Using the Friend Function and strcat() function
Below is the C++ program for string concatenation using the friend function and strcat()
function:
 C++

// C++ program for string concatenation

// using friend function and strcat()

#include <iostream>

#include <string.h>

using namespace std;

// Base class

class Base {

public:

char init[100] = "this is init";

char add[100] = " added now";


friend void myfun(Base b);

};

void myfun (Base b)

// Pass parameter to concatenate

strcat (b.init, b.add);

cout << b.init;

// Driver code

int main()

// Create object of base class

Base b;

// pass b object to myfun() to print


// the concatenated string

myfun(b);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output

this is init added now

C++ Program To Add Two Binary Strings


Last Updated : 17 Jan, 2023



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

// C++ program to add two

// binary strings
#include <bits/stdc++.h>

using namespace std;

// This function adds two binary strings

// and return result as a third string

string addBinary(string A, string B)

// If the length of string A is greater

// than the length of B then just swap

// the string by calling the same

// function and make sure to return

// the function otherwise recursion

// will occur which leads to calling

// the same function twice

if (A.length() > B.length())

return addBinary(B, A);

// Calculating the difference between


// the length of the two strings.

int diff = B.length() - A.length();

// Initialise the padding string which

// is used to store zeroes that should

// be added as prefix to the string which

// has length smaller than the other string.

string padding;

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

padding.push_back('0');

A = padding + A;

string res;

char carry = '0';

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

// This if condition solves 110 111


// possible cases

if (A[i] == '1' && B[i] == '1')

if (carry == '1')

res.push_back('1'), carry = '1';

else

res.push_back('0'), carry = '1';

// This if condition solves 000 001

// possible cases

else if (A[i] == '0' && B[i] == '0')

if (carry == '1')

res.push_back('1'), carry = '0';

else

res.push_back('0'), carry = '0';

}
// This if condition solves 100 101 010

// 011 possible cases

else if (A[i] != B[i])

if (carry == '1')

res.push_back('0'), carry = '1';

else

res.push_back('1'), carry = '0';

// If at the end their is carry then just

// add it to the result

if (carry == '1')

res.push_back(carry);

// reverse the result

reverse(res.begin(), res.end());
// To remove leading zeroes

int index = 0;

while (index + 1 < res.length() &&

res[index] == '0')

index++;

return (res.substr(index));

// Driver code

int main()

string a = "1101", b = "100";

cout << addBinary(a, b) << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
10001
Remove Leading Zeros From String in C++
Last Updated : 14 Sep, 2022



Given a string of digits, remove leading zeros from it.


Examples:
Input : 00000123569
Output : 123569

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

// C++ program to remove leading zeros

// from a given string

#include <iostream>

using namespace std;

string removeZero(string str)


{

// Count leading zeros

int i = 0;

while (str[i] == '0')

i++;

// The erase function removes i characters

// from given index (0 here)

str.erase(0, i);

return str;

// Driver code

int main()

string str;

str = "00000123569";

str = removeZero(str);
cout << str << endl;

return 0;

Output

123569

2. Using Stoi() Method


stoi() function in C++ is used to convert the given string into an integer value. It takes a
string as an argument and returns its value in integer form. We can simply use this method to
convert our string to an integer value which will remove the leading zeros.
s to i()
| | |___ integer
| |_______ to
|__________ String

 C++

// C++ Program to remove leading zeros

// with the help of stoi() function

#include <iostream>

using namespace std;

int main()

{
string str;

str = "00000123569";

int num = stoi(str);

str = to_string(num);

cout << "String after removing leading zeros is: "

<< str << endl;

return 0;

Output

String after removing leading zeros is: 123569

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.

beg2 : Input iterator to initial position of second sequence.


end2 : Input iterator to final position of second sequence.

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

 CPP

// C++ code to demonstrate the working of

// lexicographical_compare()

#include<iostream>

#include<algorithm> // for lexicographical_compare()

using namespace std;

int main()

// initializing char arrays

char one[] = "geeksforgeeks";

char two[] = "gfg";


// using lexicographical_compare for checking

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

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

cout << "geeksforgeeks is lexicographically less than gfg";

else

cout << "geeksforgeeks is not lexicographically less than gfg";

Time Complexity: O(N)


Space Complexity: O(1)
Output:
geeksforgeeks is lexicographically less than gfg
Syntax 2 : lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2, iter2 end2,
Compare comp)
Template:
template
bool lexicographical_compare(iter1 beg1, iter1 end1, iter2 beg2,
iter2 end2)
Parameters :
beg1 : Input iterator to initial position of first sequence.
end1 : Input iterator to final position of first sequence.

beg2 : Input iterator to initial position of second sequence.


end2 : Input iterator to final position of second sequence.

comp : The comparator function that returns a boolean


true/false of the each elements compared. This function
accepts two arguments. This can be function pointer or
function object and cannot change values.

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

 CPP

// C++ code to demonstrate the working of

// lexicographical_compare()

#include<iostream>

#include<algorithm> // for lexicographical_compare()

using namespace std;

// helper function to convert all into lower case:


bool comp (char s1, char s2)

return tolower(s1)<tolower(s2);

int main()

// initializing char arrays

char one[] = "geeksforgeeks";

char two[] = "Gfg";

// using lexicographical_compare for checking

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

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

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

cout << "geeksforgeeks is lexicographically less than Gfg\n";


}

else

cout << "geeksforgeeks is not lexicographically less than Gfg\n";

// using lexicographical_compare for checking

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

// returns true this time as all converted into lowercase

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

cout << "geeksforgeeks is lexicographically less ";

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

else

{
cout << "geeksforgeeks is not lexicographically less ";

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

Time Complexity: O(N)


Space Complexity: O(1)
Output:
geeksforgeeks is not lexicographically less than Gfg
geeksforgeeks is lexicographically less than Gfg( case-insensitive )
Possible application : Comparing strings can be generally used in dictionary, where
we need to place words in lexicographical order. Example of this can be to find the
word which occurs 1st in dictionary among given set of words.
 CPP

// C++ code to demonstrate the application of

// lexicographical_compare()

#include<bits/stdc++.h>

using namespace std;


int main()

// initializing char arrays

char list[][100]={

{'a','b','a','c','u','s'},

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

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

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

};

char min[100] = "zzzzzz";

// using lexicographical_compare for checking

// the smallest

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

if( lexicographical_compare(list[i], list[i]


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

strcpy(min,list[i]);

// prints "abacus"

cout << "The smallest string is : ";

for(int i = 0; min[i]!='&#092;&#048;'; i++)

cout<<min[i];

Time Complexity: O(N)


Space Complexity: O(1)
Output:
The smallest string is : abacus
Different Methods to Reverse a String in C++
Last Updated : 23 Sep, 2023



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

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


 Making our own reverse function
 Using ‘inbuilt’ reverse function
 Using Constructor
 Using a temp file
1. Making a Custom Reverse Function For Swapping Characters
 Using a first to last approach ‘for’ loop
 CPP

// C++ program to reverse a string

// using first to last approach

// 'for' loop

#include <bits/stdc++.h>

using namespace std;


// Function to reverse a string

void reverseStr(string& str)

int n = str.length();

// Swap character starting from two

// corners

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

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

// Driver program

int main()

string str = "geeksforgeeks";

reverseStr(str);

cout << str;


return 0;

Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
 Using a first to last Approach with while loop

 C++

// C++ program to reverse a string

// using while loop

#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

void reverseStr(string& str)

int len = str.length();

int n = len-1;

int i = 0;
while(i<=n){

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

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

n = n-1;

i = i+1;

// Driver program

int main()

string str = "geeksforgeeks";

reverseStr(str);

cout << str;

return 0;

Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
 Using a Last to First Approach ‘for‘ Loop
 C++

// C++ program to demonstrate reverse

// of a string using Last to First

// Approach 'for' Loop

#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

void reverse(string str)

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

cout << str[i];

// Driver code

int main(void)

{
string s = "GeeksforGeeks";

reverse(s);

return (0);

Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
 Using a Last to First Approach ‘while’ Loop

 C++

// C++ program to demonstrate reverse

// of a string using Last to First

// Approach 'while' Loop

#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

void reverse(string str)

{
int len = str.length();

int n = len;

while(n--)

cout << str[n];

// Driver code

int main(void)

string s = "GeeksforGeeks";

reverse(s);

return (0);

Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
1. Using recursion Function with two pointer approach
Recursion functions are used for iterating to different indexes of the string.
 C++

// C++ program to reverse a string

// using recursion

#include <bits/stdc++.h>

using namespace std;

// Function to reverse a string

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

if(n<=i){return;}

// Swapping the character

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

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

}
// Driver program

int main()

string str = "geeksforgeeks";

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

cout << str;

return 0;

Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
2. Using one pointer approach in recursion
Below is the implementation of the code:
 C++

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

#include <iostream>

using namespace std;

void getreverse(string &str, int i)


{

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

return;

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

i++;

getreverse(str, i);

int main()

string name = "geeksforgeeks";

getreverse(name, 0);

cout << name << endl;

return 0;

//code contributed by pragatikohli

Output
skeegrofskeeg

Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
3. Using the inbuilt “reverse” Function
There is a direct function in the “algorithm” header file for doing reverse that saves
our time when programming.
// Reverses elements in [begin, end]
void reverse (BidirectionalIterator begin,
BidirectionalIterator end);

 CPP

// C++ program to illustrate the

// reversing of a string using

// reverse() function

#include <bits/stdc++.h>

using namespace std;

int main()

string str = "geeksforgeeks";

// Reverse str[begin..end]

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

return 0;

Output
skeegrofskeeg
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
4. Reverse a String Using the Constructor
Passing reverse iterators to the constructor returns us a reversed string.
 CPP

// C++ program to reverse

// string using constructor

#include <bits/stdc++.h>

using namespace std;

int main()

string str = "GeeksforGeeks";

// Use of reverse iterators


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

cout << rev << endl;

return 0;

Output
skeeGrofskeeG

Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
5. Using a Temporary String
 CPP

// C++ program to demonstrate

// reversing of string

// using temporary string

#include <bits/stdc++.h>

using namespace std;

int main()

{
string str = "GeeksforGeeks";

int n = str.length();

// Temporary string to store the reverse

string rev;

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

rev.push_back(str[i]);

cout << rev << endl;

return 0;

Output
skeeGrofskeeG

Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(1)
How could we get the reverse of a const string?
To get the reverse of a const string we have to first declare a ‘const string’ in a user-
defined function following which we have declared then use the following algorithm
for the calling of the desired objects.
“const reverseConstString = function(string) { return
string.split("").reverse().join("")”
Example:
 C++

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

#include <bits/stdc++.h>

using namespace std;

// Function to reverse string and return

// reverse string pointer of that

char* reverseConstString(char const* str)

// find length of string

int n = strlen(str);

// create a dynamic pointer char array

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

// copy of string to ptr array


strcpy(rev, str);

// Swap character starting from two

// corners

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

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

// return pointer of the reversed string

return rev;

// Driver code

int main(void)

const char* s = "GeeksforGeeks";

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

return (0);

Output
skeeGrofskeeG
Time Complexity: O(N)
Auxiliary Space: O(N)
Using Stack Data Structure
 C++

// C++ Program to reverse a string

#include <bits/stdc++.h>

using namespace std;

int main()

string s = "GeeksforGeeks";

stack<char> st;

for (char x : s)

st.push(x);

while (!st.empty()) {

cout << st.top();

st.pop();

return 0;

Output
skeeGrofskeeG
Complexity Analysis:
Time Complexity: O(N)
Auxiliary Space: O(N)
Using Vector Data Structure
 C++

// C++ Program to reverse a string

#include <bits/stdc++.h>

using namespace std;

int main()

string s = "GeeksforGeeks";

int n=s.length();

vector<char> vec;

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

vec.push_back(s[i]);

for(auto i:vec){

cout<<i;

return 0;
}

Output
skeeGrofskeeG

C++ Program to check if a given String is


Palindrome or not
Last Updated : 12 Sep, 2023



Given a string S consisting of N characters of the English alphabet, the task is to


check if the given string is a palindrome. If the given string is a palindrome, then print
“Yes“. Otherwise, print “No“.
Note: A string is said to be palindrome if the reverse of the string is the same as the
string.
For example, The string “racecar” is a palindrome because the reverse of the string is
the same as the original string.
Recommended: Please try your approach on {IDE} first, before moving on to the
solution.

Method 1: Using the Inbuilt reverse() Function in the STL


The simplest approach is to use the inbuilt reverse() function in the STL.
Algorithm

 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++ Program to Check if a Given String is Palindrome or Not

 C++

// C++ program for the above approach

#include <bits/stdc++.h>

using namespace std;

// Function to check whether

// the string is palindrome

string isPalindrome(string S)

// Stores the reverse of the

// string S

string P = S;

// Reverse the string P


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

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

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Yes

Complexity Analysis

 Time Complexity: O(N)


 Auxiliary Space: O(N)
Method 2: By Traversing the String
The above approach can be optimized in space complexity by traversing the string and
checking whether the character at the ith index is equal to the character at the (N-i-
1)th index for every index in the range [0, N/2].

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++ Program to Check if a Given String is Palindrome or Not

 C++

// C++ program for the above approach


#include <bits/stdc++.h>

using namespace std;

// Function to check whether string

// is palindrome

string isPalindrome(string S)

// Iterate over the range [0, N/2]

for (int i = 0; i < S.length() / 2; i++) {

// If S[i] is not equal to

// the S[N-i-1]

if (S[i] != S[S.length() - i - 1]) {

// Return No

return "No";

// Return "Yes"
return "Yes";

// Driver Code

int main()

string S = "ABCDCBA";

cout << isPalindrome(S);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Yes

C++ Program to Print the First Letter of Each


Word of a String
Last Updated : 07 Mar, 2024



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

Input: str = "happy coding"


Output: hc
Source: https://www.geeksforgeeks.org/amazon-interview-set-8-2/
Recommended Practice

Print First Letter Of Every Word In The String


Try It!

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

// C++ program to find the string

// which contain the first character

// of each word of another string.

#include<bits/stdc++.h>

using namespace std;


// Function to find string which has

// first character of each word.

string firstLetterWord(string str)

string result = "";

// Traverse the string.

bool v = true;

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

// If it is space, set v as true.

if (str[i] == ' ')

v = true;

// Else check if v is true or not.

// If true, copy character in output

// string and set v as false.


else if (str[i] != ' ' && v == true)

result.push_back(str[i]);

v = false;

return result;

// Driver code

int main()

string str = "geeks for geeks";

cout << firstLetterWord(str);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ implementation of the above

// approach

#include <bits/stdc++.h>

using namespace std;

string processWords(char *input)

/* We are splitting the input based on

spaces (s)+ : this regular expression

will handle scenarios where we have words

separated by multiple spaces */

char *p;

vector<string> s;
p = strtok(input, " ");

while (p != NULL)

s.push_back(p);

p = strtok(NULL, " ");

string charBuffer;

for (string values : s)

/* charAt(0) will pick only the

first character from the string

and append to buffer */

charBuffer += values[0];

return charBuffer;
}

// Driver code

int main()

char input[] = "geeks for geeks";

cout << processWords(input);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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>

using namespace std;


// Function to find string which has first character of each word.

string firstLetterWord(string str, int index, string result)

// base case: if index is out of range, return the modified string

if (index == str.length())

return result;

// check for space

if (str[index] == ' ')

// copy the character to result string

result.push_back(str[index+1]);

// recursively call the function for the next index

return firstLetterWord(str, index + 1, result);

}
// Driver code

int main()

string str = "geeks for geeks";

cout<< firstLetterWord(str, 0, "g");

return 0;

//This code is contributed by Vinay Pinjala.

Learn Data Structures & Algorithms with GeeksforGeeks

Output
gfg

std::string::insert() in C++
Last Updated : 10 Sep, 2018



insert() is used to insert characters in string at specified position. It supports various


syntaxes to facilitate same, here we will describe them.
Syntax 1: Inserts the characters of str starting from index idx.
string& string::insert (size_type idx, const string& str)
idx :is the index number
str : is the string from which characters is to be picked to insert
Returns *this.
Errors:
Throws out_of_range if idx > size().
Throws length_error if the resulting size exceeds the maximum number
of characters.

// CPP code for insert (size_type idx, const string& str)

#include <iostream>

#include <string>

using namespace std;

// Function to demonstrate insert

void insertDemo(string str1, string str2)

// Inserts str2 in str1 starting

// from 6th index of str1

str1.insert(6, str2);

cout << "Using insert : ";

cout << str1;


}

// Driver code

int main()

string str1("Hello World! ");

string str2("GeeksforGeeks ");

cout << "Original String : " << str1 << endl;

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.

// CPP code for insert (size_type idx, const string& str,

// size_type str_idx, size_type str_num)

#include <iostream>

#include <string>

using namespace std;

// Function to demonstrate insert

void insertDemo(string str1, string str2)

// Inserts 6 characters from index number

// 8 of str2 at index number 6 of str1


str1.insert(6, str2, 8, 6);

cout << "Using insert : ";

cout << str1;

// Driver code

int main()

string str1("Hello World! ");

string str2("GeeksforGeeks ");

cout << "Original String : " << str1 << endl;

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

// CPP code for insert(size_ type idx, const char* cstr)

#include <iostream>

#include <string>

using namespace std;

// Function to demonstrate insert

void insertDemo(string str)

// Inserts " are " at 5th index of str

str.insert(5, " are ");


cout << "Using insert : ";

cout << str;

// Driver code

int main()

string str("GeeksforGeeks ");

cout << "Original String : " << str << endl;

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.

// CPP code for insert (size_type idx, const char* chars,

// size_type chars_len)

#include <iostream>

#include <string>

using namespace std;

// Function to demonstrate insert

void insertDemo(string str)

// Inserts 10 characters from" are here "

// at 5th index of str


str.insert(5, " are here ", 10);

cout << "Using insert : ";

cout << str;

// Driver code

int main()

string str("GeeksforGeeks ");

cout << "Original String : " << str << endl;

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.

// CPP code for :insert (size_type idx, size_type num, char c)

#include <iostream>

#include <string>

using namespace std;

// Function to demonstrate insert

void insertDemo(string str)

// Inserts at 5th index,

// 5 occurrences of '$'

str.insert(5, 5, '$');

cout << "Using insert : ";


cout << str;

// Driver code

int main()

string str("**********");

cout << "Original String : " << str << endl;

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.

// CPP code for :insert (iterator pos, size_type num, char c)

#include <iostream>

#include <string>

using namespace std;

// Function to demonstrate insert

void insertDemo(string str)

// Inserts 5 occurrences of '$'

// at position str.begin() + 5

str.insert(str.begin() + 5, 5, '$');

cout << "Using insert : ";

cout << str;

}
// Driver code

int main()

string str("**********");

cout << "Original String : " << str << endl;

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.

// CPP code for :insert (iterator pos, char c )


#include <iostream>

#include <string>

using namespace std;

// Function to demonstrate insert

void insertDemo(string str)

std::string::iterator pos;

// Inserts '$' at position

// str.begin() + 5

pos = str.insert(str.begin()+5,'$');

cout << "Using insert : ";

cout << str << endl;

cout << "Value at Iterator returned : " << *pos;

}
// Driver code

int main()

string str("**********");

cout << "Original String : " << str << endl;

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>

using namespace std;

// Function to demonstrate insert

void insertDemo(string str1, string str2)

// Inserts str2.begin() + 5 , str2.end() - 6

// at position str1.begin() + 6

str1.insert(str1.begin() + 6, str2.begin() + 5 , str2.end() - 6);

cout << "Using insert : ";

cout << str1;

}
// Driver code

int main()

string str1("Hello World! ");

string str2("GeeksforGeeks ");

cout << "Original String : " << str1 << endl;

insertDemo(str1, str2);

return 0;

Output:
Original String : Hello World!
Using insert : Hello forWorld!

C++ Program to Split a String Into a Number of


Sub-Strings
Last Updated : 27 Jan, 2023




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>

using namespace std;

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

void simple_tokenizer(string s)

{
stringstream ss(s);

string word;

while (ss >> word) {

cout << word << endl;

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

string a = "How do you do!";

// Takes only space separated C++ strings.

simple_tokenizer(a);

cout << endl;

return 0;

Output : How
do
you
do!
Method 2: Using C++ find() and substr() APIs.
Prerequisite: find function and substr().
This method is more robust and can parse a string with any delimiter, not just
spaces(though the default behavior is to separate on spaces.) The logic is pretty simple
to understand from the code below.
 C++

#include <bits/stdc++.h>

using namespace std;

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

int start = 0;

int end = s.find(del);

while (end != -1) {

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

start = end + del.size();

end = s.find(del, start);

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

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

{
// Takes C++ string with any separator

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

tokenize(a, "$%");

cout << endl;

return 0;

Output: Hi
do
you
do
!
Method 3: Using temporary string
If you are given that the length of the delimiter is 1, then you can simply use a temp
string to split the string. This will save the function overhead time in the case of
method 2.

 C++

#include <iostream>

using namespace std;

void split(string str, char del){


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

string temp = "";

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

// If cur char is not del, then append it to the cur "word", otherwise

// you have completed the word, print it, and start a new word.

if(str[i] != del){

temp += str[i];

else{

cout << temp << " ";

temp = "";

cout << temp;

}
int main() {

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

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

split(str, del);

return 0;

Output
geeks for geeks

C++ Program to Reverse a String Using Stack


Last Updated : 18 Dec, 2023



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

Reverse A String Using Stack


Try It!

Following programs implements above algorithm.


 C++
 Java

// C++ program to reverse a string

// using stack

#include <bits/stdc++.h>

using namespace std;

// A structure to represent

// a stack

class Stack

public:

int top;

unsigned capacity;

char* array;
};

// function to create a stack of

// given capacity. It initializes

// size of the stack as 0

Stack* createStack(unsigned capacity)

Stack* stack = new Stack();

stack->capacity = capacity;

stack->top = -1;

stack->array = new char[(stack->capacity *

sizeof(char))];

return stack;

// Stack is full when the top is equal

// to the last index

int isFull(Stack* stack)


{ return stack->top == stack->capacity - 1; }

// Stack is empty when the top is equal to -1

int isEmpty(Stack* stack)

{ return stack->top == -1; }

// Function to add an item to stack.

// It increases the top by 1

void push(Stack* stack, char item)

if (isFull(stack))

return;

stack->array[++stack->top] = item;

// Function to remove an item from

// stack. It decreases the top by 1

char pop(Stack* stack)


{

if (isEmpty(stack))

return -1;

return stack->array[stack->top--];

// A stack-based function to reverse

// a string

void reverse(char str[])

// Create a stack of capacity

//equal to length of string

int n = strlen(str);

Stack* stack = createStack(n);

// Push all characters of string

// to stack

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

push(stack, str[i]);

// Pop all characters of string and

// put them back to str

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

str[i] = pop(stack);

// Driver code

int main()

char str[] = "GeeksQuiz";

reverse(str);

cout << "Reversed string is " <<

str;
return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

Method-1: Without using STL


This approach is based on Hashing.
1. Create a boolean hash table of size 26, one for each letter of the English alphabet.
2. Traverse the given string character by character.
3. For each character in the string, calculate its corresponding index in the hash table
using the ASCII value. For example, the ASCII value of ‘a’ is 97, so its index in
the hash table would be 97 – 97 = 0. Similarly, the index of ‘b’ would be 98 – 97 =
1, and so on.
4. Mark the index in the hash table as true, indicating that the corresponding letter is
present in the string.
5. After complete traversal and marking of the string, traverse the hash table and
check if all the indices have been marked as true or not. If all the indices have been
marked as true, then the string contains all the letters of the English alphabet, and
the algorithm returns true. Otherwise, the string does not contain all the letters of
the English alphabet, and the algorithm returns false.
The time complexity of this algorithm is O(n), where n is the length of the string,
since we are traversing the string only once, and the hash table operations take
constant time. The space complexity is also O(1) since the size of the hash table is
fixed and does not depend on the length of the input string.
Note that this approach can be easily extended to check if a given string contains all
the letters of any other language or character set, by creating a hash table of
appropriate size and mapping the characters to their corresponding indices.
Below is the implementation of the above approach:

 C++

// C++ Program to check if the given

// string is a pangram or not

#include <bits/stdc++.h>

using namespace std;

// Returns true if the string is

// pangram else false

bool checkPangram(string& str)

// Create a hash table to mark


// the characters

// present in the string

vector<bool> mark(26, false);

// For indexing in mark[]

int index;

// Traverse all characters

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

// If uppercase character,

// subtract 'A' to find index.

if ('A' <= str[i] && str[i] <= 'Z')

index = str[i] - 'A';

// If lowercase character,

// subtract 'a' to find index.

else if ('a' <= str[i]


&& str[i] <= 'z')

index = str[i] - 'a';

// If this character is not

// an alphabet, skip to next one.

else

continue;

mark[index] = true;

// Return false

// if any character is unmarked

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

if (mark[i] == false)

return (false);

// If all characters were present


return (true);

// Driver Code

int main()

string str = "We promptly judged"

" antique ivory"

" buckles for the next prize";

if (checkPangram(str) == true)

printf("Yes");

else

printf("No");

return (0);

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ Program to check whether


// a string pangram or not using STL

#include <bits/stdc++.h>

using namespace std;

// Function to return given string

// str is pangrams yes or no

string pangrams(string s)

// Initialization of count

int count = 0;

// Convert each letter into

// uppercase to avoid counting

// of both uppercase and

// lowercase as different letters


transform(s.begin(),

s.end(),

s.begin(),

::toupper);

// Sort the string

sort(s.begin(), s.end());

// Count distinct alphabets

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

if (s[i] != s[i + 1])

count++;

// If count is 27 then the string

// contains all the alphabets

// including space as a

// distinct character
if (count == 27)

return "Yes";

else

return "No";

// Driver code

int main()

// Given string str

string str = "We promptly "

"judged antique"

"ivory buckles for "

"the next prize";

// Function Call

cout << pangrams(str);


return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

Algorithm to Convert Binary Numbers to Decimal


 Initialize a variable dec_value to store the decimal representation and a
variable base to keep track of the current binary place.
 Run a loop till num is non-zero,
 Extract the last digit of num and store it in a variable last_digit.
 Update num by removing the last digit.
 Add last_digit * base (power of 2) to dec_value to calculate the decimal
value of the current binary place.
 Update the base by multiplying it by 2.
 Return dec_value as it holds the decimal representation of the binary number.
Example

The below diagram explains how to convert ( 1010 ) to an equivalent decimal value.

Recommended Practice

Binary number to decimal number

Try It!

C++ Program to Convert Binary Numbers to Decimal


 C++

// C++ program to convert binary

// to decimal

#include <iostream>

using namespace std;


// Function to convert binary

// to decimal

int binaryToDecimal(int n)

int num = n;

int dec_value = 0;

// Initializing base value to

// 1, i.e 2^0

int base = 1;

int temp = num;

while (temp) {

int last_digit = temp % 10;

temp = temp / 10;

dec_value += last_digit * base;

base = base * 2;
}

return dec_value;

// Driver code

int main()

int num = 10101001;

cout << binaryToDecimal(num) << endl;

Output
169

Complexity Analysis

 Time complexity : O(log n)


 Auxiliary Space : O(1)
Note: The program works only with binary numbers in the range of integers. In case
you want to work with long binary numbers like 20 bits or 30 bits, you can use a
string variable to store the binary numbers.
Below is a similar program that uses string variables instead of integers to store
binary values.
 C++
// C++ program to convert binary to decimal

// when input is represented as binary string.

#include <iostream>

#include <string>

using namespace std;

// Function to convert binary

// to decimal

int binaryToDecimal(string n)

string num = n;

int dec_value = 0;

// Initializing base value to 1, i.e 2^0

int base = 1;

int len = num.length();

for (int i = len - 1; i >= 0; i--) {


if (num[i] == '1')

dec_value += base;

base = base * 2;

return dec_value;

// Driver code

int main()

string num = "10101001";

cout << binaryToDecimal(num) << endl;

Output
169

Complexity Analysis

 Time complexity: O(n) where n is the length of the string.


 Auxiliary Space : O(1)
Convert Binary Numbers to Decimal Using std::bitset Class
In C++, the std::bitset class provides an easy way to work with binary numbers. It has
the following member functions to convert Binary Numbers to Decimals.
 to_ulong(): Converts bitset to unsigned long.
 to_ullong(): Converts bitset to unsigned long long.
It is defined inside <bitset> header file.

C++ Program to Convert Binary Numbers to Decimal Using std::bitset

 C++

// C++ program that demonstrates how to convert binary

// numbers to decimal using std::bitset class

#include <bitset>

#include <iostream>

#include <string>

using namespace std;

int main()

string binary_string = "1101";

// Assuming 4-bit integer, adjust the size as needed

bitset<4> bits(binary_string);
unsigned long decimal_value = bits.to_ulong();

cout << decimal_value << endl;

return 0;

Output
13

C++ Program For Binary To Octal Conversion


Last Updated : 23 Jun, 2023



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

// C++ implementation to convert

// a binary number to octal number

#include <bits/stdc++.h>

using namespace std;

// Function to create map between

// binary number and its equivalent

// octal

void createMap(unordered_map<string, char>* um)

(*um)["000"] = '0';

(*um)["001"] = '1';

(*um)["010"] = '2';

(*um)["011"] = '3';

(*um)["100"] = '4';
(*um)["101"] = '5';

(*um)["110"] = '6';

(*um)["111"] = '7';

// Function to find octal equivalent

// of binary

string convertBinToOct(string bin)

int l = bin.size();

int t = bin.find_first_of('.');

// length of string before '.'

int len_left = t != -1 ? t : l;

// Add min 0's in the beginning to make

// left substring length divisible by 3

for (int i = 1; i <= (3 - len_left % 3) % 3; i++)


bin = '0' + bin;

// If decimal point exists

if (t != -1) {

// Length of string after '.'

int len_right = l - len_left - 1;

// Add min 0's in the end to make right

// substring length divisible by 3

for (int i = 1; i <= (3 - len_right % 3) % 3; i++)

bin = bin + '0';

// Create map between binary and its

// equivalent octal code

unordered_map<string, char> bin_oct_map;

createMap(&bin_oct_map);
int i = 0;

string octal = "";

while (1) {

// One by one extract from left, substring

// of size 3 and add its octal code

octal += bin_oct_map[bin.substr(i, 3)];

i += 3;

if (i == bin.size())

break;

// If '.' is encountered add it to result

if (bin.at(i) == '.') {

octal += '.';

i++;

}
// required octal number

return octal;

// Driver code

int main()

string bin = "1111001010010100001.010110110011011";

cout << "Octal number = " << convertBinToOct(bin);

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

// C++ program to convert binary

// to octal

#include <cmath>

#include <iostream>

#include <string>

using namespace std;

// Function to convert binary to

// octal

string binaryToOctal(string binary)

// Check if the binary number is valid

if (binary.find_first_not_of("01.") != string::npos) {

return "Invalid binary number";

// Convert the integer part of the binary number

// to octal
int decimal = stoi(binary.substr(0, binary.find('.')),

nullptr, 2);

string octal = "";

while (decimal > 0) {

octal = to_string(decimal % 8) + octal;

decimal /= 8;

// Convert the fractional part of the binary number

// to octal

if (binary.find('.') != string::npos) {

double fractional = stod(

"0." + binary.substr(binary.find('.') + 1));

octal += ".";

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

fractional *= 8;

octal += to_string((int)floor(fractional));

fractional -= floor(fractional);
}

return octal;

// Dtriver code

int main()

string binary1 = "110001110";

string octal1 = binaryToOctal(binary1);

cout << "Octal equivalent of " << binary1 << " is "

<< octal1 << endl;

string binary2 = "1111001010010100001";

string octal2 = binaryToOctal(binary2);

cout << "Octal equivalent of " << binary2 << " is "

<< octal2 << endl;


string binary3 = "11011.10";

string octal3 = binaryToOctal(binary3);

cout << "Octal equivalent of " << binary3 << " is "

<< octal3 << endl;

string binary4 = "1002";

string octal4 = binaryToOctal(binary4);

cout << "Octal equivalent of " << binary4 << " is "

<< octal4 << endl;

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

// C++ program to convert octal

// to decimal

#include <iostream>
using namespace std;

// Function to convert octal

// to decimal

int octalToDecimal(int n)

int num = n;

int dec_value = 0;

// Initializing base value to 1,

// i.e 8^0

int base = 1;

int temp = num;

while (temp)

// Extracting last digit

int last_digit = temp % 10;


temp = temp / 10;

// Multiplying last digit with

// appropriate base value and adding

// it to dec_value

dec_value += last_digit * base;

base = base * 8;

return dec_value;

// Driver code

int main()

int num = 67;


cout << octalToDecimal(num) << endl;

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

// C++ program to convert octal

// to decimal

#include <iostream>

using namespace std;

int OctToDec(string n)

return stoi(n, 0, 8);

// Driver code
int main()

string n = "67";

cout << OctToDec(n);

return 0;

// This code is contributed by phasing17

Output
55

C++ Program For Decimal To Octal


Conversion
Last Updated : 03 Aug, 2023



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.

C++ Program to Convert Decimal Number To Octal


Number
 C++

// C++ program to convert a decimal

// number to octal number

#include <iostream>

using namespace std;


// Function to convert decimal

// to octal

void decToOctal(int n)

// Array to store octal number

int octalNum[100];

// Counter for octal number array

int i = 0;

while (n != 0) {

// Storing remainder in octal array

octalNum[i] = n % 8;

n = n / 8;

i++;

// Printing octal number array in

// reverse order
for (int j = i - 1; j >= 0; j--)

cout << octalNum[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++

// C++ program to convert hexadecimal

// to decimal

#include <bits/stdc++.h>

using namespace std;


// Function to convert hexadecimal

// to decimal

int hexadecimalToDecimal(string hexVal)

int len = hexVal.size();

// Initializing base value to 1,

// i.e 16^0

int base = 1;

int dec_val = 0;

// Extracting characters as digits

// from last character

for (int i = len - 1; i >= 0; i--) {

// If character lies in '0'-'9',

// converting it to integral 0-9


// by subtracting 48 from ASCII value

if (hexVal[i] >= '0' && hexVal[i] <= '9') {

dec_val += (int(hexVal[i]) - 48) * base;

// incrementing base by power

base = base * 16;

// If character lies in 'A'-'F' , converting

// it to integral 10 - 15 by subtracting 55

// from ASCII value

else if (hexVal[i] >= 'A' && hexVal[i] <= 'F') {

dec_val += (int(hexVal[i]) - 55) * base;

// Incrementing base by power

base = base * 16;

}
return dec_val;

// Driver code

int main()

string hexNum = "1A";

cout << (hexadecimalToDecimal(hexNum));

return 0;

Output
26

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

// C++ program to convert hexadecimal

// to decimal

#include <bits/stdc++.h>

using namespace std;


// Function to convert hexadecimal

// to decimal

int hexadecimalToDecimal(string hexVal)

int len = hexVal.size();

// Initializing base value to 1,

// i.e 16^0

int base = 1;

int dec_val = 0;

// Extracting characters as digits

// from last character

for (int i = len - 1; i >= 0; i--) {

// If character lies in '0'-'9',

// converting it to integral 0-9


// by subtracting 48 from ASCII value

if (hexVal[i] >= '0' && hexVal[i] <= '9') {

dec_val += (int(hexVal[i]) - 48) * base;

// incrementing base by power

base = base * 16;

// If character lies in 'A'-'F' , converting

// it to integral 10 - 15 by subtracting 55

// from ASCII value

else if (hexVal[i] >= 'A' && hexVal[i] <= 'F') {

dec_val += (int(hexVal[i]) - 55) * base;

// Incrementing base by power

base = base * 16;

}
return dec_val;

// Driver code

int main()

string hexNum = "1A";

cout << (hexadecimalToDecimal(hexNum));

return 0;

Output
26

C++ Program For Decimal To Hexadecimal


Conversion
Last Updated : 04 Aug, 2023



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

// C++ program to convert a decimal

// number to hexadecimal number

#include <iostream>

using namespace std;

// Function to convert decimal

// to hexadecimal
void decToHexa(int n)

// char array to store hexadecimal number

char hexaDeciNum[100];

// Counter for hexadecimal number array

int i = 0;

while (n != 0) {

// Temporary variable to store remainder

int temp = 0;

// Storing remainder in temp variable.

temp = n % 16;

// Check if temp < 10

if (temp < 10) {

hexaDeciNum[i] = temp + 48;

i++;
}

else {

hexaDeciNum[i] = temp + 55;

i++;

n = n / 16;

// Printing hexadecimal number

// array in reverse order

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

cout << hexaDeciNum[j];

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

C++ Program For Decimal To Binary


Conversion
Last Updated : 21 Sep, 2023




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.

Recommended PracticeDecimal to binaryTry It!

Decimal to Binary Conversion using Loop


 Create an array to store the binary representation of size 32, Since the binary
representation of an integer can have at most 32 bits.
 Run a loop till n is greater than 0.
 Extract the remainder by taking the mod of number using the modulus operator
and store the remainder in the array as a binary digit.
 Update the number by dividing it by 2 in each iteration.
 Print the array in reverse order.

C++ Program to Convert Decimal To Binary using Loop

 C++

// C++ program to convert a decimal


// number to binary number

#include <iostream>

using namespace std;

// Function to convert decimal

// to binary

void decToBinary(int n)

// Array to store binary number

int binaryNum[32];

// Counter for binary array

int i = 0;

while (n > 0) {

// Storing remainder in binary

// array

binaryNum[i] = n % 2;

n = n / 2;
i++;

// Printing binary array in reverse

// order

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

cout << binaryNum[j];

// Driver code

int main()

int n = 10;

decToBinary(n);

return 0;

Output
1010
Explanation

If the decimal number is 10.


Step 1: Remainder when 10 is divided by 2 is zero. Therefore, arr[0] = 0.
Step 2: Divide 10 by 2. The new number is 10/2 = 5.
Step 3: Remainder when 5 is divided by 2 is 1. Therefore, arr[1] = 1.
Step 4: Divide 5 by 2. The new number is 5/2 = 2.
Step 5: Remainder when 2 is divided by 2 is zero. Therefore, arr[2] = 0.
Step 6: Divide 2 by 2. The new number is 2/2 = 1.
Step 7: Remainder when 1 is divided by 2 is 1. Therefore, arr[3] = 1.
Step 8: Divide 1 by 2. The new number is 1/2 = 0.
Step 9: Since the number becomes = 0.
Print the array in reverse order. Therefore the equivalent binary number is 1010.

Complexity Analysis

 Time complexity: O(log (n))


 Auxiliary Space: O(1)
Decimal to Binary Conversion using std::bitset
C++ Standard Template Library provides std::bitset class that is used to perform
bitwise operations on binary numbers. It can be used to convert Decimal Numbers to
Binary and vice versa.

C++ Program to Convert Decimal To Binary using std::bitset

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

// C++ program to convert decimal numbers to binary using

// bitset class

#include <bitset>

#include <iostream>
#include <math.h>

using namespace std;

int main()

int decimalNumber = 10;

// Assuming 32-bit representation

const int sz = ceil(log2(10));

bitset<sz> binaryRepresentation(decimalNumber);

cout << "Binary representation: "

<< binaryRepresentation << endl;

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.

1. Boolean To String Conversion Using Customized


Function
We have defined a customized boolean-to-string conversion function btos(). It is
responsible for converting a boolean value into its corresponding string
representation.
C++ Program to Convert Boolean Values to String
 C++

// C++ program to convert

// truth table for OR operation

#include <iostream>
using namespace std;

// Function to convert boolean

// into string

string btos(bool x)

if (x)

return "True";

return "False";

// Driver code

int main()

// Conversion of Truth Table

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

 Time complexity: O(1)


 Auxiliary space: O(1)
2. Using Alphanumeric Boolean Values
The boolalpha flag indicates whether to use textual representation for bool values
viz true or false or to use integral values for bool values viz 1 or 0. When the
boolalpha flag is set, the textual representation is used and when it is not set, integral
representation is used. By default, it is not set.

C++ Program to Convert a Boolean to a String Using boolalpha Flag

 C++

// C++ program to convert boolean

// to string using boolalpha flag


#include <iostream>

using namespace std;

// Driver code

int main()

bool value = true;

cout << "Printing true value before boolalpha: "

<< value << endl;

cout << "Printing true value after boolalpha: "

<< boolalpha << value << endl;

return 0;

Output
Printing true value before boolalpha: 1
Printing true value after boolalpha: true
Complexity Analysis

 Time complexity: O(1)


 Auxiliary space: O(1)
C++ Program For String to Double Conversion
Last Updated : 04 Aug, 2023



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++ Program to Convert String to Double Using stod() Function

 C++

// C++ program to convert string


// to double using stod()

#include <iostream>

using namespace std;

// Driver code

int main()

char s1[] = "14.25";

char s2[] = "34.87";

double n1 = stod(s1);

double n2 = stod(s2);

double res = n1 + n2;

cout << res;

return 0;

Output

49.12

Complexity Analysis

 Time complexity: O(1)


 Auxiliary Space: O(1)
2. Using stold() Function
In C++, the stold() function performs a string to long double conversion. Like stod()
function, this function is also defined inside <string.h> header file.
Syntax
long double stold(const string& str, size_t *pos = 0);
Parameters
 str: the string to convert.
 pos: address of integer to store the index of the first unconverted character. This
parameter can also be a null pointer, in which case it is not used.
Return Value
 Converted long double value.

C++ Program to Convert String to Long Double Using stold() Function

 C++

// C++ program to convert string

// to long double using stold()

#include <iostream>

using namespace std;

// Driver code

int main()

char s1[] = "14.25";

char s2[] = "34.87";

long double n1 = stold(s1);

long double n2 = stold(s2);


long double res = n1 + n2;

cout << res;

return 0;

Output

49.12

Complexity Analysis

 Time complexity: O(1)


 Auxiliary Space: O(1)
3. Using atof() Function
In C++, the atof() method translates a string’s contents as a floating-point integer and returns
its value as a double. It is declared inside <cstdlib> header file.
Syntax
double atof (const char * str)
Parameters
 The function accepts a single mandatory parameter str which is the string representation
of a floating-point number.
Return Value
 Converted long double value.

C++ Program to Convert String to Double Using atof() Function

 C++

// C++ program to convert string

// to double using atof()

#include <iostream>
using namespace std;

// Driver code

int main()

char s[] = "14.25";

double num = atof(s);

cout << num;

return 0;

Output

14.25

Complexity Analysis

 Time complexity: O(1)


 Auxiliary Space: O(1)
C++ Program For Double to String Conversion
Last Updated : 26 Jul, 2022



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

// C++ Program to demonstrate Double to

// String Conversion using to_string

#include <iostream>

#include <string.h>

using namespace std;

int main()

double n = 456321.7651234;
string str = to_string(n);

cout << "String is: " << str;

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

// C++ Program to demonstrate Double to

// String Conversion using string stream

#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int main()
{

ostringstream s;

double n = 2332.43;

s << n;

string str = s.str();

cout << "String is:" << str;

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

// C++ Program to demonstrate Double to

// String Conversion using sprintf

#include <cstring>

#include <iostream>
#include <string>

#define Max_Digits 10

using namespace std;

int main()

double N = 1243.3456;

char str[Max_Digits + sizeof(char)];

std::sprintf(str, "%f", N);

std::printf("string is: %s \n", str);

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

// C++ Program to demonstrate Double to


// String Conversion using lexical_cast

#include <boost/lexical_cast.hpp>

#include <iostream>

#include <string>

using namespace std;

int main()

double n = 432.12;

string str = boost::lexical_cast<string>(n);

cout << "string is:" << str;

return 0;

Output
string is:432.12

C++ Program For String to Long Conversion


Last Updated : 03 May, 2023




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

// C++ program to convert

// string to long using stol()

#include <iostream>

using namespace std;


// Driver code

int main()

char s1[] = "20";

char s2[] = "30";

long int n1 = stol(s1);

long int n2 = stol(s2);

long int res = n1 + n2;

cout << res;

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

// C++ program to convert

// string to long using stoul()

#include <iostream>

using namespace std;

// Driver code

int main()

char s1[] = "20";

char s2[] = "30";

unsigned long int n1 = stoul(s1);

unsigned long int n2 = stoul(s2);

unsigned long int res = n1 + n2;

cout << res;


return 0;

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

// C++ program to convert

// string to long using atol()

#include <iostream>

using namespace std;

// Driver code

int main()
{

char s[] = "123456654";

long int n = atol(s);

cout << n;

return 0;

Output
123456654

Convert Long to String in C++


Last Updated : 09 Feb, 2023



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

//add last digit to stack after converting it to char


stringStack.push(long_num % 10 + '0');
long_num /= 10; // remove last digit
}
3. While the stack becomes empty, pop one by one character from the string and
append it to the resultant string.
while (!stringStack.empty()) {

// append top char of stack to string


long_to_string += stringStack.top();
stringStack.pop(); // pop char from the stack
}
4. Return the resultant string with the signValue.
return signValue + long_to_string;
Example:
 C++

// C++ program to demonstrate

// long to string conversion


// digit by digit

#include <bits/stdc++.h>

using namespace std;

string LongToString(long long_num)

stack<char> stringStack;

string signValue = "";

// if long number is negative store the negative sign to

// the signValue variable

if (long_num < 0) {

signValue = "-";

long_num = -long_num;

// while number is greater than 0, get last digit from it

// and convert it to character by adding '0' to it, and


// push to the stack.

while (long_num > 0) {

char convertedDigit = long_num % 10 + '0';

stringStack.push(convertedDigit);

long_num /= 10;

string long_to_string = "";

// while stack is not empty pop the character one by one

// and append to the resultant string.

while (!stringStack.empty()) {

long_to_string += stringStack.top();

stringStack.pop();

// return the resulatant string value by appending

// singValue to it.
return signValue + long_to_string;

int main()

long long_num = -10243213;

string long_to_string = LongToString(long_num);

cout << long_to_string;

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

// long to string conversion

// using stringstream

#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int main()

// initialize the long number

long long_num = 43543422;

// create a new object of stringstream class

stringstream stream;

// add long number to variable of type stringstream

stream << long_num;


string long_to_string;

// get string object from stringstream variable using

// str() method

long_to_string = stream.str();

cout << long_to_string;

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

// C++ program to demonstrate

// long to string conversion

// using std::to_string methods

#include <iostream>
#include <string>

using namespace std;

int main()

// initialize the long number

long long_num = 76456474;

string long_to_string;

// convert long to string using to_string() method

long_to_string = to_string(long_num);

cout << long_to_string;

return 0;

Output
76456474

C++ Program For int to char Conversion


Last Updated : 08 May, 2023




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

// C++ program to convert

// int to char using typecasting

#include <iostream>

using namespace std;

// Driver code

int main()

{
int N = 97;

cout << char(N);

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

// C++ program to convert

// int to char using typecasting

#include <iostream>

using namespace std;

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

// C++ program to convert

// int to char using static_cast

#include <iostream>

using namespace std;

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

// C++ program to convert

// int to char using sprintf()

#include <iostream>

using namespace std;

#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

4. Using to_string() and c_str()


The to string() function transforms a single integer variable or other data types into a string.
The c_str() method converts a string to an array of characters, terminating with a null
character.
Below is the C++ program to convert int to char using to_string() and c_str():

 C++

// C++ program to convert

// int to char using sto_string()


// and c_str()

#include <iostream>

using namespace std;

// Driver code

int main()

int N = 1234;

string t = to_string(N);

char const *n_char = t.c_str();

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

// C++ program to convert

// int to char using

// stringstream

#include <iostream>

using namespace std;

#include <sstream>

// Driver code

int main()

int N = 1234;

std::stringstream t;

t << N;

char const *n_char =

t.str().c_str();

printf("n_char: %s \n",

n_char);;

return 0;
}

Output

n_char: 1234

Method: Converting int value to char by adding 0

 C++

// C++ program to convert

// int to char using typecasting by adding zero

#include <iostream>

using namespace std;

//Driver code

int main()

int number = 65;

char charvalue = (char(number)+0);

cout << charvalue;

return 0;

}
Output

A
Time complexity: O(1).
Auxiliary space: O(1).

Approach: ASCII value offset approach

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>

using namespace std;

int main() {

int num = 65;

cout << "Enter an integer: " << num << endl;

char ch;

if(num >= 65 && num <= 90) {

ch = num;
} else if(num >= 97 && num <= 122) {

ch = num;

} else {

cout << "Invalid input." << endl;

return 0;

cout << "The corresponding character is: " << ch << endl;

num = 97;

cout << "Enter an integer: " << num << endl;

if(num >= 65 && num <= 90) {

ch = num;

} else if(num >= 97 && num <= 122) {

ch = num;

} else {

cout << "Invalid input." << endl;

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.

Approach Name: Arithmetic Conversion

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;

void int_to_char(int num, char *result) {

int temp = num;

int len = 0;

while (temp > 0) {

len++;

temp /= 10;

for (int i = len - 1; i >= 0; i--) {

result[i] = num % 10 + '0';

num /= 10;

result[len] = '\0';

}
int main() {

int num = 12345;

char result[100];

int_to_char(num, result);

cout << result << endl;

return 0;

Output

12345

C++ Program For char to int Conversion


Last Updated : 27 Apr, 2023



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

// C++ program to convert

// char to int (ASCII Value) using typecasting

#include <iostream>

using namespace std;

// Driver code

int main()

char ch = 'A';

cout << int(ch);

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

// C++ program to convert

// char to int (integer value) using typecasting

#include <iostream>

using namespace std;

// Driver code

int main()

char ch = '5';

// Subtracting 48 will produce desired results

cout << int(ch) - 48 << "\n";

// Also subtracting '0' will result in same output

cout << int(ch - '0');


return 0;

// This code is contributed by Susobhan Akhuli

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

// C++ program to convert

// char to int (ASCII value) using typecasting

#include <iostream>

using namespace std;

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

// C++ program to convert char

// to int (ASCII Value) using static_cast

#include <iostream>

using namespace std;

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

// C++ program to convert char

// to int using sscanf()

#include <iostream>

using namespace std;

// Driver code

int main()
{

const char *s = "1234";

int x;

sscanf(s, "%d", &x);

cout << "\nThe integer value of x : " << 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++

// C++ program to convert char

// to int using stoi()

#include <iostream>

#include <string>

using namespace std;


// Driver code

int main()

char s1[] = "45";

int x = stoi(s1);

cout << "The integer value of x : " << x;

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

// C++ program to convert char

// to int using atoi()

#include <iostream>

using namespace std;


// Driver code

int main()

const char *str = "1234";

int y = atoi(str);

cout << "\nThe integer value of y :" << y;

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

// C++ program to convert char

// to int using string stream


#include <iostream>

#include <string>

#include <sstream>

using namespace std;

// Driver code

int main()

stringstream string;

string << "5";

int n;

string >> n;

cout << "Integer value is: " << n;

return 0;

Output
Integer value is: 5

6. Method: Converting char value to int by adding 0


 C++
// C++ program to convert

// char to int using typecasting by adding zero

#include <iostream>

using namespace std;

//Driver code

int main()

char charvalue = 'a';

int number = (int(charvalue)+0);

cout << number;

return 0;

//this code is contributed by uomkar369

Output
97

C++ Searching and Sorting Programs


C++ Program For Linear Search
Last Updated : 20 Feb, 2023



Problem: Given an array arr[] of n elements, write a function to search a given


element x in arr[].
Examples:
Input: arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 110;
Output: 6
Element x is present at index 6
Input: arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 175;
Output: -1
Element x is not present in arr[].
Recommended Problem

Searching a number

Arrays

Searching

+2 more

Solve Problem

Submission count: 1.1L

A simple approach is to do a linear search, i.e


 Start from the leftmost element of arr[] and one by one compare x with each
element of arr[]
 If x matches with an element, return the index.
 If x doesn’t match with any of elements, return -1.

Example:
 C++

// C++ code to linearly search

// x in arr[]. If x is present

// then return its location,

// otherwise return -1

#include <iostream>

using namespace std;

int search(int arr[],

int n, int x)
{

int i;

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

if (arr[i] == x)

return i;

return -1;

// Driver code

int main(void)

int arr[] = {2, 3, 4, 10, 40};

int x = 10;

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

// Function call

int result = search(arr, n, x);

(result == -1) ?
cout << "Element is not present in array" :

cout << "Element is present at index " <<

result;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program for linear search

#include<bits/stdc++.h>

using namespace std;


void search(vector<int> arr,

int search_Element)

int left = 0;

int length = arr.size();

int position = -1;

int right = length - 1;

// Run loop from 0 to right

for(left = 0; left <= right;)

// If search_element is found with

// left variable

if (arr[left] == search_Element)

{
position = left;

cout << "Element found in Array at " <<

position + 1 << " Position with " <<

left + 1 << " Attempt";

break;

// If search_element is found with

// right variable

if (arr[right] == search_Element)

position = right;

cout << "Element found in Array at " <<

position + 1 << " Position with " <<

length - right << " Attempt";

break;
}

left++;

right--;

// If element not found

if (position == -1)

cout << "Not found in Array with "

<< left << " Attempt";

// Driver code

int main()

vector<int> arr{1, 2, 3, 4, 5};

int search_element = 5;

// Function call
search(arr, search_element);

// This code is contributed by mayanktyagi1709

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Element found in Array at 5 Position with 1 Attempt

C++ Program For Binary Search


Last Updated : 07 Aug, 2023



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

Example of Binary Search Algorithm

The middle index of the array can be calculated as:


int mid = low + (high – low)/2;

Binary Search Program in C++ (Recursive)


 C++

// C++ program to implement recursive Binary Search


#include <bits/stdc++.h>

using namespace std;

// Recursive Binary Search function to find the index of an

// element 'x' in a sorted array 'arr' if elements is

// present, otherwise it return -1

// low: The index of the first element in the current

// sub-array high: The index of the last element in the

// current sub-array

int binarySearch(int arr[], int low, int high, int x)

// Base case: If the search space becomes empty, the

// element is not present in the array

if (high >= low) {

// Calculate the middle index to divide the search


// space in half

int mid = low + (high - low) / 2;

// If the middle element is equal to 'x', we have

// found the element, return its index

if (arr[mid] == x)

return mid;

// If the middle element is greater than 'x', search

// in the left half of the array

if (arr[mid] > x)

return binarySearch(arr, low, mid - 1, x);

// If the middle element is less than 'x', search in

// the right half of the array

return binarySearch(arr, mid + 1, high, x);

}
// If the base case is reached, the element is not

// present in the array, return -1

return -1;

// Driver code

int main(void)

int arr[] = { 2, 3, 4, 10, 40 };

// Element to be searched

int x = 10;

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

int result = binarySearch(arr, 0, n - 1, x);

(result == -1)

? cout << "Element is not present in array"

: cout << "Element is present at index " << result;


return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to implement

// iterative Binary Search

#include <bits/stdc++.h>

using namespace std;

// Iretative Binary Search function to find the index of an

// element 'x' in a sorted array 'arr' if elements is

// present, otherwise it return -1

// low: The index of the first element in the current


// sub-array high: The index of the last element in the

// current sub-array

int binarySearch(int arr[], int low, int high, int x)

while (low <= high) {

int mid = low + (high - low) / 2;

// If the middle element is equal to 'x', we have

// found the element, return its index

if (arr[mid] == x)

return mid;

// If the middle element is smaller than 'x', search

// in the right half of the array

if (arr[mid] < x)

low = mid + 1;

// If the middle element is greater than 'x', search


// in the left half of the array

else

high = mid - 1;

// If the base case is reached, the element is not

// present in the array, return -1

return -1;

// Driver code

int main(void)

int arr[] = { 2, 3, 4, 10, 40 };

// Element to be searched

int x = 10;

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


int result = binarySearch(arr, 0, n - 1, x);

(result == -1)

? cout << "Element is not present in array"

: cout << "Element is present at index " << result;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Element is present at index 3
Complexity Analysis
 Time Complexity : O(log n)
 Auxiliary Space : O(1)

C++ Program For Selection Sort


Last Updated : 17 Jan, 2023



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:

How selection sort works?

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!

Below is the implementation of the above approach:

 C++

// C++ program for implementation of

// selection sort

#include <bits/stdc++.h>

using namespace std;

//Swap function

void swap(int *xp, int *yp)

int temp = *xp;

*xp = *yp;

*yp = temp;

}
void selectionSort(int arr[], int n)

int i, j, min_idx;

// One by one move boundary of

// unsorted subarray

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

// Find the minimum element in

// unsorted array

min_idx = i;

for (j = i+1; j < n; j++)

if (arr[j] < arr[min_idx])

min_idx = j;

// Swap the found minimum element


// with the first element

swap(&arr[min_idx], &arr[i]);

//Function to print an array

void printArray(int arr[], int size)

int i;

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

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

cout << endl;

// Driver program to test above functions

int main()

int arr[] = {64, 25, 12, 22, 11};


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

selectionSort(arr, n);

cout << "Sorted array: ";

printArray(arr, n);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output
Sorted array:
11 12 22 25 64

C Program For Bubble Sort


Last Updated : 07 Mar, 2024



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.

 In the inner loop, we will check if the arr[ j ] > arr[ j + 1 ].


 If it’s true, then we will swap places of these elements.
 If false, we will continue to the next iteration.

 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

// C program for implementation of Bubble sort

#include <stdio.h>

// Swap function

void swap(int* arr, int i, int j)

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;
}

// A function to implement bubble sort

void bubbleSort(int arr[], int n)

int i, j;

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

// Last i elements are already

// in place

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

if (arr[j] > arr[j + 1])

swap(arr, j, j + 1);

// Function to print an array

void printArray(int arr[], int size)

{
int i;

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

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

printf("\n");

// Driver code

int main()

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

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

bubbleSort(arr, N);

printf("Sorted array: ");

printArray(arr, N);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

 Swaps since 5 > 1.


1 5 4 2 8

 Swap since 5 > 4.


1 4 5 2 8

 Swap since 5 > 2.


1 4 2 5 8
 Now, since these elements are already in order (8 > 5), algorithm does not swap
them.
Second Pass
Now, during the second iteration arr should look like this
1 4 2 5 8

 No Swapping since 1 < 4.


1 4 2 5 8

 Swap since 4 > 2.


1 2 4 5 8
 No Swapping since 4 < 5.
The array is already sorted, but the algorithm will still move to the third pass
Third Pass
The algorithm needs one whole pass without any swap to know it is sorted.
1 2 4 5 8

 No Swapping since 1 < 2.


1 2 4 5 8

 No swapping since 2 < 4.


Again, we will move to the fourth pass even when the array is sorted.
Fourth Pass
There will be only one comparison in the fourth pass and no swap will be done as 1 <
2.
1 2 4 5 8

Optimized Bubble Sort Program in C


As we have seen in the above example that the bubble sort algorithm still completed
the third and fourth passes even when the array was sorted in the second pass. We can
improve the code to prevent such cases. In the optimized program for bubble sort:
 A new variable swapped is used to signal if the swap operation is done in the inner
loop iteration.
 If the swap doesn’t occur in the iteration, it means that the array is already sorted.

 C

// C Program with Optimized implementation of Bubble sort

#include <stdbool.h>

#include <stdio.h>

// Swap function

void swap(int* a, int* b)


{

int temp = a;

a = b;

b = temp;

// An optimized version of Bubble Sort

void bubbleSort(int arr[], int n)

// swapped variable to signal if there is a

// swap happened in the inner loop

// initially set to false

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

// swapped is initialized as false at the start

bool swapped = false;

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

if (arr[j] > arr[j + 1]) {

swap(arr + j, arr + j + 1);


// swapped is set to true if the swap is

// done

swapped = true;

// If no two elements were swapped

// by inner loop, then break

if (swapped == false)

break;

// Function to print an array

void printArray(int arr[], int size)

int i;

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


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

// Driver code

int main()

int arr[] = { 5, 3, 1, 9, 8, 2, 4, 7 };

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

// bubbleSort function called

bubbleSort(arr, N);

printf("Sorted array: ");

printArray(arr, N);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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.

 After the final merging, the list looks like this:

Refer to below illustrations for further clarity:


The following diagram shows the complete merge sort process for an example array
{38, 27, 43, 3, 9, 82, 10}.
If we take a closer look at the diagram, we can see that the array is recursively divided
into two halves till the size becomes
 Once the size becomes 1, the merge processes come into action and start merging
arrays back till the complete array is merged.
Recommended PracticeMerge SortTry It!

 C++

// C++ program for Merge Sort

#include <iostream>

using namespace std;


// Merges two subarrays of array[].

// First subarray is arr[begin..mid]

// Second subarray is arr[mid+1..end]

void merge(int array[], int const left,

int const mid, int const right)

auto const subArrayOne = mid - left + 1;

auto const subArrayTwo = right - mid;

// Create temp arrays

auto *leftArray = new int[subArrayOne],

*rightArray = new int[subArrayTwo];

// Copy data to temp arrays leftArray[]

// and rightArray[]

for (auto i = 0; i < subArrayOne; i++)

leftArray[i] = array[left + i];


for (auto j = 0; j < subArrayTwo; j++)

rightArray[j] = array[mid + 1 + j];

// Initial index of first sub-array

// Initial index of second sub-array

auto indexOfSubArrayOne = 0,

indexOfSubArrayTwo = 0;

// Initial index of merged array

int indexOfMergedArray = left;

// Merge the temp arrays back into

// array[left..right]

while (indexOfSubArrayOne < subArrayOne &&

indexOfSubArrayTwo < subArrayTwo)

if (leftArray[indexOfSubArrayOne] <=

rightArray[indexOfSubArrayTwo])
{

array[indexOfMergedArray] =

leftArray[indexOfSubArrayOne];

indexOfSubArrayOne++;

else

array[indexOfMergedArray] =

rightArray[indexOfSubArrayTwo];

indexOfSubArrayTwo++;

indexOfMergedArray++;

// Copy the remaining elements of

// left[], if there are any

while (indexOfSubArrayOne < subArrayOne)

{
array[indexOfMergedArray] =

leftArray[indexOfSubArrayOne];

indexOfSubArrayOne++;

indexOfMergedArray++;

// Copy the remaining elements of

// right[], if there are any

while (indexOfSubArrayTwo < subArrayTwo)

array[indexOfMergedArray] =

rightArray[indexOfSubArrayTwo];

indexOfSubArrayTwo++;

indexOfMergedArray++;

// begin is for left index and end is


// right index of the sub-array

// of arr to be sorted */

void mergeSort(int array[],

int const begin,

int const end)

// Returns recursively

if (begin >= end)

return;

auto mid = begin + (end - begin) / 2;

mergeSort(array, begin, mid);

mergeSort(array, mid + 1, end);

merge(array, begin, mid, end);

// UTILITY FUNCTIONS

// Function to print an array


void printArray(int A[], int size)

for (auto i = 0; i < size; i++)

cout << A[i] << " ";

cout<<endl;

// Driver code

int main()

int arr[] = { 12, 11, 13, 5, 6, 7 };

auto arr_size = sizeof(arr) / sizeof(arr[0]);

cout << "Given array is "<<endl;

printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);


cout << "Sorted array is "<<endl;

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.

Algorithmic Paradigm: Divide and Conquer


Is Merge sort In Place?
No in a typical implementation
Is Merge sort Stable:
Yes, merge sort is stabe.
Applications of Merge Sort:
 Merge Sort is useful for sorting linked lists in O(nLogn) time. In the case of linked
lists, the case is different mainly due to the difference in memory allocation of
arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in
memory. Unlike an array, in the linked list, we can insert items in the middle in
O(1) extra space and O(1) time. Therefore, the merge operation of merge sort can
be implemented without extra space for linked lists.
In arrays, we can do random access as elements are contiguous in memory. Let us
say we have an integer (4-byte) array A and let the address of A[0] be x then to
access A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can
not do random access in the linked list. Quick Sort requires a lot of this kind of
access. In a linked list to access i’th index, we have to travel each and every node
from the head to i’th node as we don’t have a continuous block of memory.
Therefore, the overhead increases for quicksort. Merge sort accesses data
sequentially and the need of random access is low.
 Inversion Count Problem
 Used in External Sorting
Drawbacks of Merge Sort:
 Slower comparative to the other sort algorithms for smaller tasks.
 Merge sort algorithm requires an additional memory space of 0(n) for the
temporary array.
 It goes through the whole process even if the array is sorted.
C++ Program To Sort String of Characters
Last Updated : 11 Oct, 2023



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

C++ Program To Sort String Of Characters

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

// C++ program to sort a

// string of characters

#include<bits/stdc++.h>

using namespace std;

// Function to print string

// in sorted order

void sortString(string &str)

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

cout << str;

// Driver code

int main()

string s = "geeksforgeeks";

sortString(s);
return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to sort a

// string of characters

#include<bits/stdc++.h>

using namespace std;

const int MAX_CHAR = 26;

// Function to print string

// in sorted order

void sortString(string &str)


{

// Hash array to keep count of characters.

// Initially count of all characters is

// initialized to zero.

int charCount[MAX_CHAR] = {0};

// Traverse string and increment

// count of characters

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

// 'a'-'a' will be 0, 'b'-'a' will be 1,

// so for location of character in count

// array we will do str[i]-'a'.

charCount[str[i]-'a']++;

// Traverse the hash array and print

// characters

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

for (int j=0;j<charCount[i];j++)


cout << (char)('a'+i);

// Driver code

int main()

string s = "geeksforgeeks";

sortString(s);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:
eeeefggkkorss

Row wise sorting in 2D array


Last Updated : 19 Aug, 2022



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

// sort 2D matrix row-wise

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

void sortRowWise(int m[][4],

int r, int c)

// loop for rows of matrix

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

// loop for column of matrix

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

// loop for comparison and swapping

for (int k = 0; k < c - j - 1; k++)

if (m[i][k] > m[i][k + 1])

// swapping of elements

swap(m[i][k], m[i][k + 1]);


}

// printing the sorted matrix

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

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

cout << m[i][j] << " ";

cout << endl;

// Driver code

int main()

int m[][4] = {{9, 8, 7, 1},


{7, 3, 0, 2},

{9, 5, 3, 2},

{6, 3, 1, 2}};

int c = sizeof(m[0]) / sizeof(m[0][0]);

int r = sizeof(m) / sizeof(m[0]);

sortRowWise(m, r, c);

return 0;

// This code is contributed by Rutvik_56

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ code to sort 2D

// matrix row-wise

#include <bits/stdc++.h>

using namespace std;

#define M 4

#define N 4

int sortRowWise(int m[M][N])

// One by one sort

// individual rows.

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

sort(m[i], m[i] + N);

// Printing the sorted matrix

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

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

cout << (m[i][j]) << " ";

cout << endl;

// Driver code

int main()

int m[M][N] = {{9, 8, 7, 1},

{7, 3, 0, 2},

{9, 5, 3, 2},

{6, 3, 1, 2}};

sortRowWise(m);

// This code is contributed by gauravrajput1

Learn Data Structures & Algorithms with GeeksforGeeks

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.

1. Brute-force Approach Using Bubble Sort


Here, the brute force approach is used using the bubble sort method. Below is the C++
program to sort the array in ascending order using the brute-force method using
bubble sort:
 C++

// C++ program to sort array

// in ascending order using


// Brute-force approach

// using bubble sort

#include <bits/stdc++.h>

using namespace std;

void sort(int num[], int len);

void swapNums(int nums[],

int first, int second);

// Driver code

int main()

// Initializing arrya

int nums[] = {1, 12, 6, 8, 10};

int size_nums = (sizeof(nums) /

sizeof(nums[0]));

cout << "Before sorting the array is: \n";


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

cout << nums[i] << " ";

cout << "\n\n";

sort(nums, size_nums);

cout << "After sorting the array is: \n";

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

cout << nums[i] << " ";

cout << "\n";

return 0;

// Sort function

void sort(int num[], int len)

bool isSwapped;
/**

* Here we are running n-1 steps,

for each step, max item will

come at the last respective

index and swap element if the

element is smaller than the

previous one.

**/

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

isSwapped = false;

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

if (num[j] < num[j - 1])

swapNums(num, j, (j - 1));

isSwapped = true;
}

if (!isSwapped)

break;

// Swaps two numbers in array

void swapNums(int nums[],

int first, int second)

int curr = nums[first];

nums[first] = nums[second];

nums[second] = curr;

Output
Before sorting the array is:
1 12 6 8 10

After sorting the array is:


1 6 8 10 12
 Time Complexity: O(n2)
 Space Complexity: O(1)
2. Optimized Approach Using QuickSort
Here, an optimized solution is presented using the quicksort sorting algorithm. Below
is the C++ program to sort an array in ascending order using an optimized approach
using quicksort:
 C++

// C++ program to sort an array in

// ascending order using optimized

// approach using quick sort

#include <bits/stdc++.h>

using namespace std;

void quickSort(int nums[],

int low, int high);

// Driver code

int main()

{
int nums[] = {1, 6, 3, 10, 50};

int size_nums = (sizeof(nums) /

sizeof(nums[0]));

cout << "Before sorting array is: \n";

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

cout << nums[i] << " ";

cout << "\n\n";

quickSort(nums, 0, size_nums - 1);

cout << "After sorting array is: \n";

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

cout << nums[i] << " ";

cout << "\n";

return 0;

}
/**

* Sorts the specified array into ascending

numerical order.

* @param nums the array to be sorted.

* @param low for explaining the part of

array working on.

* @param high for explaining the part of

array working on.

*/

void quickSort(int nums[],

int low, int high)

// Base Condition

if (low >= high)

return;
// These are just for swapping

// the elements.

int start = low, end = high;

int mid = start + ((end - start) / 2);

int pivot = nums[mid];

while (start <= end) {

while (nums[start] < nums[end])

start++;

while (nums[end] > pivot)

end--;

if (start <= end)

// Swapping the start and end

// elements.

int x = nums[start];

nums[start] = nums[end];

nums[end] = x;
start++;

end--;

quickSort(nums, low, end);

quickSort(nums, start, high);

Output
Before sorting array is:
1 6 3 10 50

After sorting array is:


1 3 6 10 50

C++ Structures Programs


How to pass or return a structure to/from a
Function in C/C++?
Last Updated : 16 Dec, 2019



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

// C++ program to pass structure as an argument

// to the functions using Call By Value Method

#include <bits/stdc++.h>

using namespace std;

struct Distance {

int kilometer;

int meter;

};

// accepts distance as its parameters

void TotalDistance(Distance d1, Distance d2)

// creating a new instance of the structure

Distance d;
// assigning value to new instance of structure

d.kilometer = d1.kilometer

+ d2.kilometer

+ (d1.meter + d2.meter)

/ 1000;

d.meter = (d1.meter + d2.meter) % 1000;

cout << "Total distance:";

cout << "kilometer: "

<< d.kilometer << endl;

cout << "meter: " << d.meter

<< endl;

// Function that initialises the value


// and calls TotalDistance function

void initializeFunction()

// creating two instances of Distance

Distance Distance1, Distance2;

// assigning values to structure elements

Distance1.kilometer = 10;

Distance1.meter = 455;

Distance2.kilometer = 9;

Distance2.meter = 745;

// calling function with (structure)

// distance as parameters

TotalDistance(Distance1, Distance2);

}
// Driver code0

int main()

// Calling function to do required task

initializeFunction();

return 0;

Output:
Total distance:kilometer: 20
meter: 200
Examples 2: Using Call By Reference Method

// C++ program to pass structure as an argument

// to the functions using Call By Reference Method

#include <bits/stdc++.h>

using namespace std;


struct number {

int n;

};

// Accepts structure as an argument

// using call by reference method

void increment(number& n2)

n2.n++;

void initializeFunction()

number n1;

// assigning value to n

n1.n = 10;
cout << " number before calling "

<< "increment function:"

<< n1.n << endl;

// calling increment function

increment(n1);

cout << "number after calling"

<< " increment function:" << n1.n;

// Driver code

int main()

// Calling function to do required task

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:

// C++ program to return a structure from

// a function using Call By Value Method

#include <iostream>

#include <stdlib.h>

using namespace std;

// required structure

struct Employee {

int Id;
string Name;

};

// return type of the function is structure

Employee data(Employee E)

// Assigning the values to elements

E.Id = 45;

E.Name = "aman";

// returning structure

return (E);

// Driver code

int main()

{
// creating object of Employee

Employee Emp;

// calling function data to assign value

Emp = data(Emp);

// display the output

cout << "Employee Id: " << Emp.Id;

cout << "\nEmployee Name: " << Emp.Name;

return 0;

Output:
Employee Id: 45
Employee Name: aman

C++ Program to Store Information of a Student


in a Structure
Last Updated : 21 Jun, 2023


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

 Student Name (String).


 Student Roll Number (String).
 Subjects Enrolled (Array of Strings).
 Marks in each subject (Array of Int).
 CGPA(Float)
Example of the Structure
Yash Gupta
S20200010234
[DSA, OOPS ,DBMS, CCN]
[89,78,86,90]
8.918

1. For a Student
Below is the implementation of the topic:

 C++

// C++ program to demonstrate

// a structure for student details

#include <bits/stdc++.h>

using namespace std;


// Structure Of students

struct student {

// Student Name

string name;

// Student Roll Number

string rollno;

// Subjects Enrolled(Array)

vector<string> subjects;

// Marks in each subject(Array)

vector<int> marks;

// Student's CGPA

float cgpa;

};
// Function to print a vector(for more

// "Different ways to print elements of

// vector" at GFG)

template <typename S> void printv(const vector<S>& v)

cout << "[ ";

// Iterating over all elements of vector

for (auto elem : v) {

cout << elem << " ";

cout << "]";

cout << endl;

// Function to print a Student

void printStudent(student* s)
{

cout << "Student Details:" << endl;

cout << endl;

cout << "Name: " << s->name << endl;

cout << "Roll Number: " << s->rollno << endl;

cout << "Subjects: ";

printv(s->subjects);

cout << "Marks: ";

printv(s->marks);

cout << "CGPA " << s->cgpa << endl;

// Driver Code

int main()

// New Student

student s;
// Declaring all the information of a student

s.name = "GeeksforGeeks";

s.rollno = "S20200010234";

s.subjects = { "DSA", "OOPS", "DBMS", "CCN" };

s.marks = { 89, 78, 86, 90 };

s.cgpa = 8.918;

// Function call to print a Student

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

2. For a Student (Array)


These two details will also be added with the old detail to showcase the use of
structure with multiple parameters.
GFG
S20200010164
[DSA, OOPS ,DBMS, CCN]
[89,80,89,80]
8.45
gfg
Roll Number: S20200010169
Subjects: [ DSA OOPS DBMS CCN ]
Marks: [ 99 0 99 90 ]
CGPA 9.47
Below is the implementation of the above topic

 C++

// C++ program to demonstrate a

// structure for multiple student details

#include <bits/stdc++.h>

using namespace std;

// Structure Of students

struct student {

string name;

string rollno;
// Subjects Enrolled(Array)

vector<string> subjects;

// Marks in each subject(Array)

vector<int> marks;

// Student's CGPA

float cgpa;

};

// Function to print a vector

// (for more "Different ways to

// print elements of vector" at GFG)

template <typename S> void printv(const vector<S>& v)

cout << "[ ";

// Iterating over all elements of vector

for (auto elem : v) {


cout << elem << " ";

cout << "]";

cout << endl;

// Function to print a Student

void printStudent(student* s)

cout << "Student Details:" << endl;

cout << endl;

cout << "Name: " << s->name << endl;

cout << "Roll Number: " << s->rollno << endl;

cout << "Subjects: ";

printv(s->subjects);

cout << "Marks: ";

printv(s->marks);

cout << "CGPA " << s->cgpa << endl;


}

// Driver Code

int main()

// Array of Students

student arrayofstudents[10];

// Student 1

arrayofstudents[0].name = "GeeksforGeeks";

arrayofstudents[0].rollno = "S20200010234";

arrayofstudents[0].subjects

= { "DSA", "OOPS", "DBMS", "CCN" };

arrayofstudnets[0].marks = { 89, 78, 86, 90 };

arrayofstudnets[0].cgpa = 8.918;

// Student 2

arrayofstudnets[1].name = "GFG";
arrayofstudnets[1].rollno = "S20200010164";

arrayofstudnets[1].subjects

= { "DSA", "OOPS", "DBMS", "CCN" };

arrayofstudnets[1].marks = { 89, 80, 89, 80 };

arrayofstudnets[1].cgpa = 8.45;

// Student 3

arrayofstudnets[2].name = "gfg";

arrayofstudnets[2].rollno = "S20200010169";

arrayofstudnets[2].subjects

= { "DSA", "OOPS", "DBMS", "CCN" };

arrayofstudnets[2].marks = { 99, 00, 99, 90 };

arrayofstudnets[2].cgpa = 9.47;

// Loop to print all students

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

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

Sonam Bewafa asks questions

Arrays

Searching

+2 more

Solve Problem

Submission count: 3.7K

We use below structure to store details of students.


struct Student
{
string name; // Given
int math; // Marks in math (Given)
int phy; // Marks in Physics (Given)
int che; // Marks in Chemistry (Given)
int total; // Total marks (To be filled)
int rank; // Rank of student (To be filled)
};
We use std::sort() for Structure Sorting. In Structure sorting, all the respective
properties possessed by the structure object are sorted on the basis of one (or more)
property of the object.
In this example, marks of students in different subjects are provided by user. These
marks in individual subjects are added to calculate the total marks of the student,
which is then used to sort different students on the basis of their ranks (as explained
above).
Implementation:
 C++

// C++ program to demonstrate structure sorting in C++

#include <bits/stdc++.h>

using namespace std;

struct Student

string name; // Given

int math; // Marks in math (Given)


int phy; // Marks in Physics (Given)

int che; // Marks in Chemistry (Given)

int total; // Total marks (To be filled)

int rank; // Rank of student (To be filled)

};

// Function for comparing two students according

// to given rules

bool compareTwoStudents(Student a, Student b)

// If total marks are not same then

// returns true for higher total

if (a.total != b.total)

return a.total > b.total;

// If marks in Maths are same then

// returns true for higher marks

if (a.math != b.math)
return a.math > b.math;

if (a.phy != b.phy)

return a.phy > b.phy;

return (a.che > b.che);

// Fills total marks and ranks of all Students

void computeRanks(Student a[], int n)

// To calculate total marks for all Students

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

a[i].total = a[i].math + a[i].phy + a[i].che;

// Sort structure array using user defined

// function compareTwoStudents()

sort(a, a + n, compareTwoStudents);
// Assigning ranks after sorting

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

a[i].rank = i + 1;

// Driver code

int main()

int n = 5;

// array of structure objects

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

// Column names for displaying data

cout << "Rank"

<< " "

<< "Name"

<< " ";

cout << "Maths"

<< " "

<< "Physics"
<< " "

<< "Chemistry";

cout << " "

<< "Total\n";

// Display details of Students

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

cout << a[i].rank << " ";

cout << a[i].name << " ";

cout << a[i].math << " " << a[i].phy << " "

<< a[i].che << " ";

cout << a[i].total << " ";

cout << "\n";

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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 in C++ is the building block that leads to Object-Oriented programming. It is a


user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A C++ class is
like a blueprint for an object. For Example: Consider the Class of Cars. There may be
many cars with different names and brands but all of them will share some common
properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So
here, Car is the class, and wheels, speed limits, and mileage are their properties.
 A Class is a user-defined data type that has data members and member functions.
 Data members are the data variables and member functions are the functions used
to manipulate these variables together, these data members and member functions
define the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed
limit, mileage, etc, and member functions can be applying brakes, increasing
speed, etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated
but when it is instantiated (i.e. an object is created) memory is allocated.
Defining Class and Declaring Objects
A class is defined in C++ using the keyword class followed by the name of the class.
The body of the class is defined inside the curly brackets and terminated by a
semicolon at the end.
Declaring Objects
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you
need to create objects.
Syntax
ClassName ObjectName;
Accessing data members and member functions: The data members and member
functions of the class can be accessed using the dot(‘.’) operator with the object. For
example, if the name of the object is obj and you want to access the member function
with the name printName() then you will have to write obj.printName().
Accessing Data Members
The public data members are also accessed in the same way given however the private
data members are not allowed to be accessed directly by the object. Accessing a data
member depends solely on the access control of that data member. This access control
is given by Access modifiers in C++. There are three access modifiers: public,
private, and protected.
 C++

// C++ program to demonstrate accessing of data members


#include <bits/stdc++.h>

using namespace std;

class Geeks {

// Access specifier

public:

// Data Members

string geekname;

// Member Functions()

void printname() { cout << "Geekname is:" << geekname; }

};

int main()

// Declare an object of class geeks

Geeks obj1;

// accessing data member

obj1.geekname = "Abhi";

// accessing member function

obj1.printname();

return 0;
}

Output
Geekname is:Abhi

Member Functions in Classes


There are 2 ways to define a member function:
 Inside class definition
 Outside class definition
To define a member function outside the class definition we have to use the scope
resolution:: operator along with the class name and function name.
 C++

// C++ program to demonstrate function

// declaration outside class

#include <bits/stdc++.h>

using namespace std;

class Geeks

public:

string geekname;

int id;
// printname is not defined inside class definition

void printname();

// printid is defined inside class definition

void printid()

cout <<"Geek id is: "<<id;

};

// Definition of printname using scope resolution operator ::

void Geeks::printname()

cout <<"Geekname is: "<<geekname;

int main() {

Geeks obj1;
obj1.geekname = "xyz";

obj1.id=15;

// call printname()

obj1.printname();

cout << endl;

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

// C++ program to demonstrate constructors

#include <bits/stdc++.h>

using namespace std;

class Geeks

public:

int id;

//Default Constructor

Geeks()

cout << "Default Constructor called" << endl;

id=-1;

}
//Parameterized Constructor

Geeks(int x)

cout <<"Parameterized Constructor called "<< endl;

id=x;

};

int main() {

// obj1 will call Default Constructor

Geeks obj1;

cout <<"Geek id is: "<<obj1.id << endl;

// obj2 will call Parameterized Constructor

Geeks obj2(21);

cout <<"Geek id is: " <<obj2.id << endl;

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

// C++ program to explain destructors

#include <bits/stdc++.h>

using namespace std;

class Geeks

public:

int id;
//Definition for Destructor

~Geeks()

cout << "Destructor called for id: " << id <<endl;

};

int main()

Geeks obj1;

obj1.id=7;

int i = 0;

while ( i < 5 )

Geeks obj2;

obj2.id=i;

i++;

} // Scope for obj2 ends here


return 0;

} // Scope for obj1 ends here

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

Interesting Fact (Rare Known Concept)


Why do we give semicolons at the end of class?

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>

using namespace std;


class Demo{

int a, b;

public:

Demo() // default constructor

cout << "Default Constructor" << endl;

Demo(int a, int b):a(a),b(b) //parameterised constructor

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>

using namespace std;

class Demo{

public:

int a, b;

Demo()

cout << "Default Constructor" << endl;

Demo(int a, int b):a(a),b(b)


{

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>

using namespace std;

class temp{

int a;
int b;

public:

int solve(int input){

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>

using namespace std;

class Person {

private:

string name;

int age;

public:

Person(string name, int age) {

this->name = name;

this->age = age;

void setName(string name) {

this->name = name;
}

string getName() {

return name;

void setAge(int age) {

this->age = age;

int getAge() {

return age;

};

int main() {

Person person("John Doe", 30);

cout << "Name: " << person.getName() << endl;

cout << "Age: " << person.getAge() << endl;


person.setName("Jane Doe");

person.setAge(32);

cout << "Name: " << person.getName() << endl;

cout << "Age: " << person.getAge() << endl;

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

// C++ program to demonstrate

// Encapsulation

#include <iostream>

using namespace std;


class Encapsulation {

private:

// Data hidden from outside world

int x;

public:

// Function to set value of

// variable x

void set(int a) { x = a; }

// Function to return value of

// variable x

int get() { return x; }

};

// Driver code

int main()
{

Encapsulation obj;

obj.set(5);

cout << obj.get();

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>

using namespace std;

// declaring class

class Circle {

// access modifier

private:
// Data Member

float area;

float radius;

public:

void getRadius()

cout << "Enter radius\n";

cin >> radius;

void findArea()

area = 3.14 * radius * radius;

cout << "Area of circle=" << area;

};

int main()

{
// creating instance(object) of class

Circle cir;

cir.getRadius(); // calling function

cir.findArea(); // calling function

Output
Enter radius
Area of circle=0

Role of Access Specifiers in Encapsulation


Access specifiers facilitate Data Hiding in C++ programs by restricting
access to the class member functions and data members. There are three
types of access specifiers in C++:
 Private: Private access specifier means that the member function or data
member can only be accessed by other member functions of the same
class.
 Protected: A protected access specifier means that the member function
or data member can be accessed by other member functions of the same
class or by derived classes.
 Public: Public access specifier means that the member function or data
member can be accessed by any code.
By default, all data members and member functions of a class are
made private by the compiler.
Inheritance in C++
Last Updated : 08 Jan, 2024




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

// Example: define member function without argument within

// the class

#include <iostream>

using namespace std;

class Person {
int id;

char name[100];

public:

void set_p()

cout << "Enter the Id:";

cin >> id;

cout << "Enter the Name:";

cin >> name;

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

cout << "Enter the Course Name:";

cin >> course;

cout << "Enter the Course Fee:";

cin >> fee;

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

// Example: define member function without argument outside the class


#include<iostream>

using namespace std;

class Person

int id;

char name[100];

public:

void set_p();

void display_p();

};

void Person::set_p()

cout<<"Enter the Id:";

cin>>id;

cout<<"Enter the Name:";


cin>>name;

void Person::display_p()

cout<<endl<<"id: "<< id<<"\nName: "<<name;

class Student: private Person

char course[50];

int fee;

public:

void set_s();

void display_s();

};
void Student::set_s()

set_p();

cout<<"Enter the Course Name:";

cin>>course;

cout<<"Enter the Course Fee:";

cin>>fee;

void Student::display_s()

display_p();

cout<<"\nCourse: "<<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++

// Example: define member function with argument outside the class

#include<iostream>

#include<string.h>

using namespace std;

class Person
{

int id;

char name[100];

public:

void set_p(int,char[]);

void display_p();

};

void Person::set_p(int id,char n[])

this->id=id;

strcpy(this->name,n);

void Person::display_p()

cout<<endl<<id<<"\t"<<name;
}

class Student: private Person

char course[50];

int fee;

public:

void set_s(int,char[],char[],int);

void display_s();

};

void Student::set_s(int id,char n[],char c[],int f)

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

// C++ program to demonstrate implementation

// of Inheritance
#include <bits/stdc++.h>

using namespace std;

// Base class

class Parent {

public:

int id_p;

};

// Sub class inheriting from Base Class(Parent)

class Child : public Parent {

public:

int id_c;

};

// main function

int main()
{

Child obj1;

// An object of class child has all data members

// and member functions of class parent

obj1.id_c = 7;

obj1.id_p = 91;

cout << "Child id is: " << obj1.id_c << '\n';

cout << "Parent id is: " << obj1.id_p << '\n';

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

// C++ Implementation to show that a derived class

// doesn’t inherit access to private data members.

// However, it does inherit a full parent object.

class A {

public:

int x;

protected:

int y;

private:
int z;

};

class B : public A {

// x is public

// y is protected

// z is not accessible from B

};

class C : protected A {

// x is protected

// y is protected

// z is not accessible from C

};

class D : private A // 'private' is default for classes

// x is private
// y is private

// z is not accessible from D

};

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

// C++ program to explain

// Single inheritance

#include<iostream>

using namespace std;

// base class

class Vehicle {
public:

Vehicle()

cout << "This is a Vehicle\n";

};

// sub class derived from a single base classes

class Car : public Vehicle {

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base classes

Car obj;
return 0;

Output
This is a Vehicle

 C++

// Example:

#include<iostream>

using namespace std;

class A

protected:

int a;

public:

void set_A()
{

cout<<"Enter the Value of 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();

cout<<"Enter the Value of B=";

cin>>b;

void disp_B()

disp_A();

cout<<endl<<"Value of B="<<b;

void cal_product()

p=a*b;

cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;

}
};

main()

B _b;

_b.set_B();

_b.cal_product();

return 0;

Output:- Enter the Value of A= 3 3 Enter the Value of B= 5 5 Product of 3 * 5 = 15

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

void set_B(int x,int y)

set_A(x);

b=y;

void disp_B()

disp_A();

cout<<endl<<"Value of B="<<b;

}
void cal_product()

p=a*b;

cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;

};

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

// C++ program to explain

// multiple inheritance

#include <iostream>
using namespace std;

// first base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// second base class

class FourWheeler {

public:

FourWheeler()

cout << "This is a 4 wheeler Vehicle\n";

};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base classes.

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

cout<<"Enter the Value of A=";

cin>>a;

void disp_A()

cout<<endl<<"Value of A="<<a;
}

};

class B: public A

protected:

int b;

public:

void set_B()

cout<<"Enter the Value of B=";

cin>>b;

void disp_B()

{
cout<<endl<<"Value of B="<<b;

};

class C: public B

int c,p;

public:

void set_C()

cout<<"Enter the Value of C=";

cin>>c;

void disp_C()

cout<<endl<<"Value of C="<<c;
}

void cal_product()

p=a*b*c;

cout<<endl<<"Product of "<<a<<" * "<<b<<" * "<<c<<" = "<<p;

};

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

// C++ program to implement

// Multilevel Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// first sub_class derived from class vehicle

class fourWheeler : public Vehicle {

public:
fourWheeler()

cout << "Objects with 4 wheels are vehicles\n";

};

// sub class derived from the derived base class fourWheeler

class Car : public fourWheeler {

public:

Car() { cout << "Car has 4 Wheels\n"; }

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base classes.

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

// C++ program to implement

// Hierarchical Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }

};

// first sub class

class Car : public Vehicle {

};
// second sub class

class Bus : public Vehicle {

};

// main function

int main()

// Creating object of sub class will

// invoke the constructor of base class.

Car obj1;

Bus obj2;

return 0;

Output
This is a Vehicle
This is a Vehicle

5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining


more than one type of inheritance. For example: Combining Hierarchical inheritance
and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritances:
 CPP

// C++ program for Hybrid Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle {

public:

Vehicle() { cout << "This is a Vehicle\n"; }


};

// base class

class Fare {

public:

Fare() { cout << "Fare of Vehicle\n"; }

};

// first sub class

class Car : public Vehicle {

};

// second sub class

class Bus : public Vehicle, public Fare {

};

// main function

int main()
{

// Creating object of sub class will

// invoke the constructor of base class.

Bus obj2;

return 0;

Output
This is a Vehicle
Fare of Vehicle

 C++

// Example:

#include <iostream>

using namespace std;

class A

protected:
int a;

public:

void get_a()

cout << "Enter the value of 'a' : ";

cin>>a;

};

class B : public A

protected:

int b;

public:

void get_b()

cout << "Enter the value of 'b' : ";

cin>>b;
}

};

class C

protected:

int c;

public:

void get_c()

cout << "Enter the value of c is : ";

cin>>c;

};

class D : public B, public C

protected:

int d;
public:

void mul()

get_a();

get_b();

get_c();

cout << "Multiplication of a,b,c is : " <<a*b*c;

};

int main()

D d;

d.mul();

return 0;

6. A special case of hybrid inheritance: Multipath inheritance:


A derived class with two base classes and these two base classes have one common
base class is called multipath inheritance. Ambiguity can arise in this type of
inheritance.
Example:
 CPP

// C++ program demonstrating ambiguity in Multipath

// Inheritance

#include <iostream>

using namespace std;

class ClassA {

public:

int a;

};

class ClassB : public ClassA {

public:

int b;

};
class ClassC : public ClassA {

public:

int c;

};

class ClassD : public ClassB, public ClassC {

public:

int d;

};

int main()

ClassD obj;

// obj.a = 10; // Statement 1, Error

// obj.a = 100; // Statement 2, Error

obj.ClassB::a = 10; // Statement 3


obj.ClassC::a = 100; // Statement 4

obj.b = 20;

obj.c = 30;

obj.d = 40;

cout << " a from ClassB : " << obj.ClassB::a;

cout << "\n a from ClassC : " << obj.ClassC::a;

cout << "\n b : " << obj.b;

cout << "\n c : " << obj.c;

cout << "\n d : " << obj.d << '\n';

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

obj.ClassB::a = 10; // Statement 3

obj.ClassC::a = 100; // Statement 4

Note: Still, there are two copies of ClassA in Class-D.


2) Avoiding ambiguity using the virtual base class:
 CPP

#include<iostream>

class ClassA

public:
int a;

};

class ClassB : virtual public ClassA

public:

int b;

};

class ClassC : virtual public ClassA

public:

int c;

};

class ClassD : public ClassB, public ClassC

public:
int d;

};

int main()

ClassD obj;

obj.a = 10; // Statement 3

obj.a = 100; // Statement 4

obj.b = 20;

obj.c = 30;

obj.d = 40;

cout << "\n a : " << obj.a;

cout << "\n b : " << obj.b;

cout << "\n c : " << obj.c;

cout << "\n d : " << obj.d << '\n';


}

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.

Abstraction in Header files


One more type of abstraction in C++ can be header files. For example, consider the
pow() method present in math.h header file. Whenever we need to calculate the power
of a number, we simply call the function pow() present in the math.h header file and
pass the numbers as arguments without knowing the underlying algorithm according
to which the function is actually calculating the power of numbers.

Abstraction using Access Specifiers


Access specifiers are the main pillar of implementing abstraction in C++. We can use
access specifiers to enforce restrictions on class members. For example:
 Members declared as public in a class can be accessed from anywhere in the
program.
 Members declared as private in a class, can be accessed only from within the
class. They are not allowed to be accessed from any part of the code outside the
class.
We can easily implement abstraction using the above two features provided by access
specifiers. Say, the members that define the internal implementation can be marked as
private in a class. And the important information needed to be given to the outside
world can be marked as public. And these public members can access the private
members as they are inside the class.
Example:
 C++

// C++ Program to Demonstrate the

// working of Abstraction

#include <iostream>

using namespace std;

class implementAbstraction {

private:

int a, b;

public:

// method to set values of

// private members

void set(int x, int y)

a = x;

b = y;
}

void display()

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

cout << "b = " << b << endl;

};

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>

using namespace std;

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

cout<<"Rs. 60000 to 900000\n";

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

Advantages of Data Abstraction


 Helps the user to avoid writing the low-level code
 Avoids code duplication and increases reusability.
 Can change the internal implementation of the class independently without
affecting the user.
 Helps to increase the security of an application or program as only important
details are provided to the user.
 It reduces the complexity as well as the redundancy of the code, therefore
increasing the readability.
Access Modifiers in C++
Last Updated : 22 Jun, 2022



Access modifiers are used to implement an important aspect of Object-Oriented


Programming known as Data Hiding. Consider a real-life example:
The Research and Analysis Wing (R&AW), having 10 core members, has come into
possession of sensitive confidential information regarding national security. Now we
can correlate these core members to data members or member functions of a class,
which in turn can be correlated to the R&A Wing. These 10 members can directly
access the confidential information from their wing (the class), but anyone apart from
these 10 members can’t access this information directly, i.e., outside functions other
than those prevalent in the class itself can’t access the information (that is not entitled
to them) without having either assigned privileges (such as those possessed by a
friend class or an inherited class, as will be seen in this article ahead) or access to one
of these 10 members who is allowed direct access to the confidential information
(similar to how private members of a class can be accessed in the outside world
through public member functions of the class that have direct access to private
members). This is what data hiding is in practice.
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to
the class members, i.e., they set some restrictions on the class members so that they
can’t be directly accessed by the outside functions.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected
Note: If we do not specify any access modifiers for the members inside the class, then
by default the access modifier for the members will be Private.
Let us now look at each one of these access modifiers in detail:
1. Public: All the class members declared under the public specifier will be available
to everyone. The data members and member functions declared as public can be
accessed by other classes and functions too. The public members of a class can be
accessed from anywhere in the program using the direct member access operator (.)
with the object of that class.
Example:
 CPP

// C++ program to demonstrate public

// access modifier

#include<iostream>

using namespace std;

// class definition

class Circle

public:

double radius;

double compute_area()

return 3.14*radius*radius;

}
};

// main function

int main()

Circle obj;

// accessing public datamember outside class

obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";

cout << "Area is: " << obj.compute_area();

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

// C++ program to demonstrate private

// access modifier

#include<iostream>

using namespace std;

class Circle

// private data member

private:

double radius;

// public member function

public:

double compute_area()
{ // member function can access private

// data member radius

return 3.14*radius*radius;

};

// main function

int main()

// creating object of the class

Circle obj;

// trying to access private data member

// directly outside the class

obj.radius = 1.5;

cout << "Area is:" << obj.compute_area();


return 0;

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

// C++ program to demonstrate private

// access modifier

#include<iostream>

using namespace std;


class Circle

// private data member

private:

double radius;

// public member function

public:

void compute_area(double r)

{ // member function can access private

// data member radius

radius = r;

double area = 3.14*radius*radius;

cout << "Radius is: " << radius << endl;

cout << "Area is: " << area;


}

};

// main function

int main()

// creating object of the class

Circle obj;

// trying to access private data member

// directly outside the class

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

// C++ program to demonstrate

// protected access modifier

#include <bits/stdc++.h>

using namespace std;

// base class

class Parent

// protected data members

protected:

int id_protected;

};
// sub class or derived class from public base class

class Child : public Parent

public:

void setId(int id)

// Child class is able to access the inherited

// protected data members of base class

id_protected = id;

void displayId()

cout << "id_protected is: " << id_protected << endl;


}

};

// main function

int main() {

Child obj1;

// member function of the derived class can

// access the protected data members of the base class

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

// C++ program to demonstrate

// function overloading or

// Compile-time Polymorphism

#include <bits/stdc++.h>

using namespace std;

class Geeks {

public:

// Function with 1 int parameter

void func(int x)

cout << "value of x is " << x << endl;

}
// Function with same name but

// 1 double parameter

void func(double x)

cout << "value of x is " << x << endl;

// Function with same name and

// 2 int parameters

void func(int x, int y)

cout << "value of x and y is " << x << ", " << y

<< endl;

};

// Driver code

int main()
{

Geeks obj1;

// Function being called depends

// on the parameters passed

// func() is called with int value

obj1.func(7);

// func() is called with double value

obj1.func(9.132);

// func() is called with 2 int values

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

// C++ program to demonstrate

// Operator Overloading or

// Compile-Time Polymorphism

#include <iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i = 0)
{

real = r;

imag = i;

// This is automatically called

// when '+' is used with between

// two Complex objects

Complex operator+(Complex const& obj)

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

void print() { cout << real << " + i" << imag << endl; }

};
// Driver code

int main()

Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"

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

Runtime Polymorphism with Data Members


Runtime Polymorphism cannot be achieved by data members in C++. Let’s see an
example where we are accessing the field by reference variable of parent class which
refers to the instance of the derived class.
 C++
// C++ program for function overriding with data members

#include <bits/stdc++.h>

using namespace std;

// base class declaration.

class Animal {

public:

string color = "Black";

};

// inheriting Animal class.

class Dog : public Animal {

public:

string color = "Grey";

};

// Driver code

int main(void)
{

Animal d = Dog(); // accessing the field by reference

// variable which refers to derived

cout << d.color;

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

// C++ Program to demonstrate

// the Virtual Function

#include <iostream>

using namespace std;


// Declaring a Base class

class GFG_Base {

public:

// virtual function

virtual void display()

cout << "Called virtual Base Class function"

<< "\n\n";

void print()

cout << "Called GFG_Base print function"

<< "\n\n";

};
// Declaring a Child Class

class GFG_Child : public GFG_Base {

public:

void display()

cout << "Called GFG_Child Display Function"

<< "\n\n";

void print()

cout << "Called GFG_Child print Function"

<< "\n\n";

};
// Driver code

int main()

// Create a reference of class GFG_Base

GFG_Base* base;

GFG_Child child;

base = &child;

// This will call the virtual function

base->GFG_Base::display();

// this will call the non-virtual function

base->print();

Output
Called virtual Base Class function
Called GFG_Base print function
Example 2:
 C++

// C++ program for virtual function overriding

#include <bits/stdc++.h>

using namespace std;

class base {

public:

virtual void print()

cout << "print base class" << endl;

void show() { cout << "show base class" << endl; }

};

class derived : public base {

public:
// print () is already virtual function in

// derived class, we could also declared as

// virtual void print () explicitly

void print() { cout << "print derived class" << endl; }

void show() { cout << "show derived class" << endl; }

};

// Driver code

int main()

base* bptr;

derived d;

bptr = &d;

// Virtual function, binded at

// runtime (Runtime polymorphism)

bptr->print();
// Non-virtual function, binded

// at compile time

bptr->show();

return 0;

Output
print derived class
show base class

Function Overloading in C++


Last Updated : 16 Mar, 2023



Function overloading is a feature of object-oriented programming where two or more


functions can have the same name but different parameters. When a function name is
overloaded with different jobs it is called Function Overloading. In Function
Overloading “Function” name should be the same and the arguments should be
different. Function overloading can be considered as an example of
a polymorphism feature in C++.
If multiple functions having same name but parameters of the functions should be
different is known as Function Overloading.
If we have to perform only one operation and having same name of the functions
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the function such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you to understand the
behavior of the function because its name differs.

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>

using namespace std;

void add(int a, int b)

cout << "sum = " << (a + b);

void add(double a, double b)

cout << endl << "sum = " << (a + b);


}

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

using namespace std;


void add(int a, int b)

cout << "sum = " << (a + b);

void add(int a, int b, int c)

cout << endl << "sum = " << (a + b + c);

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

using namespace std;

void add(int a, double b)

cout<<"sum = "<<(a+b);

void add(double a, int 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>

using namespace std;


void print(int i) {

cout << " Here is int " << i << endl;

void print(double f) {

cout << " Here is float " << f << endl;

void print(char const *c) {

cout << " Here is char* " << c << endl;

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>

using namespace std;

void add(int a, int b)

cout<<"sum ="<<(a+b);

void add(int a, int b,int c)

cout<<endl<<"sum ="<<(a+b+c);

main()

{
add(10,2);

add(5,6,4);

return 0;

 C++

#include<iostream>

using namespace std;

void add(int a, double b)

cout<<"sum ="<<(a+b);

void add(double a, int b)

cout<<endl<<"sum ="<<(a+b);

}
main()

add(10,2.5);

add(5.5,6);

return 0;

How does Function Overloading work?


 Exact match:- (Function name and Parameter)
 If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
 If no match is found:
->C++ tries to find a match through the standard conversion.

 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

// A CPP program that uses override keyword so

// that any difference in function signature is

// caught during compilation

#include <iostream>

using namespace std;

class Base {

public:

// user wants to override this in


// the derived class

virtual void func() { cout << "I am in base" << endl; }

};

class derived : public Base {

public:

// did a silly mistake by putting

// an argument "int a"

void func(int a) override

cout << "I am in derived class" << endl;

};

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
^

C++ Program to Show Use of This Keyword in


Class
Last Updated : 04 Jul, 2022



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.

1. Resolve Shadowing Issue Using this Keyword


Shadowing occurs when there is a local variable that has the same name as an instance
variable. Below is the C++ program to show how this keyword can be used to resolve
the shadowing issues:

 C++
// C++ program to use this keyword

// to resolve shadowing issue

#include <iostream>

using namespace std;

class GFG

string name;

public:

GFG(string name)

// Use this keyword to initialize value

// of class member name as the parameter

// name passed in the constructor.

this->name = name;

void display()
{

cout << name << endl;

};

// Driver code

int main()

GFG gfg("GeeksforGeeks");

gfg.display();

return 0;

Output
GeeksforGeeks

2. Access Currently Executing Object Using this Keyword


This keyword can be used to chain functions and delete objects via its member
functions.
Example 1: Below is the C++ program to use this keyword to delete the object using
its member functions.
 C++

// C++ program to use this keyword


// to delete object of the class

#include <iostream>

using namespace std;

class GFG

string name;

public:

GFG(string name)

// Use this keyword to assign value

// of class member name as the

// parameter name passed in the

// constructor.

this->name = name;

}
void display()

cout << name << endl;

void del()

// Use this keyword to delete

// the object

delete this;

};

// Driver code

int main()

GFG *gfg = new GFG("GeeksforGeeks");


gfg->display();

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

// C++ program to use this keyword to

// access currently executing object

// to chain function calls:

#include <iostream>

using namespace std;

class GFG

string name;

int data;
public:

GFG setName(string name)

this->name = name;

return *this;

GFG setData(int data)

this->data = data;

return *this;

void display()

cout << name << endl;

cout << data << endl;


}

};

// Driver code

int main()

// Creating object

GFG gfg;

// chaining function calls

gfg = gfg.setName("GeeksforGeeks").setData(20);

gfg.display();

return 0;

Output
GeeksforGeeks
20

3. Access Data Members Using this Keyword


Below is the C++ program to use this keyword to access the data member of the
currently executing object:

 C++

// Below is the C++ program to use

// this keyword to access the data

// members of currently executing

// object

#include <iostream>

using namespace std;

class GFG

string name;

public:

GFG(string name)

// Initialize value of class member

// name as the parameter name passed


// in the constructor.

this->name = name;

void display()

// Accesses string data member name

cout << this->name << endl;

};

// Driver code

int main()

GFG gfg("GeeksforGeeks");

gfg.display();

return 0;

Output
GeeksforGeeks

4. Calling Member Functions Using this Keyword


Below is the C++ program to use this keyword to call member functions associated
with the currently executing objects:

 C++

// C++ program to use this keyword

// to call member functions of currently

// executing objects

#include <iostream>

using namespace std;

class GFG

string name;

public:

GFG(string name)

// Initialize value of class member

// name as the parameter name passed


// in the constructor.

this->name = name;

void displayX(int);

void display();

};

void GFG :: displayX(int x)

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

// Access member functions of currently

// executing object

this->display();

}
void GFG :: display()

// Accesses string data member name

cout << this->name << endl;

// Driver code

int main()

GFG gfg("GeeksforGeeks");

gfg.displayX(4);

return 0;

Output
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Static Keyword in C++


Last Updated : 16 Nov, 2023


Prerequisite: Static variables in C


The static keyword has different meanings when used with different types. We can
use static keywords with:
1. Static Variables: Variables in a function, Variables in a class
2. Static Members of Class: Class objects and Functions in a class Let us now look
at each one of these uses of static in detail.
Static Variables
Static variables in a Function: When a variable is declared as static, space for it gets
allocated for the lifetime of the program. Even if the function is called multiple
times, space for the static variable is allocated only once and the value of the variable
in the previous call gets carried through the next function call. This is useful for
implementing coroutines in C/C++ or any other application where the previous state
of function needs to be stored.
 C++

// C++ program to demonstrate

// the use of static Static

// variables in a Function

#include <iostream>

#include <string>

using namespace std;

void demo()

{
// static variable

static int count = 0;

cout << count << " ";

// value is updated and

// will be carried to next

// function calls

count++;

int main()

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

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

// C++ program to demonstrate static

// variables inside a class

#include <iostream>

using namespace std;

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

cout << obj1.i << " " << obj2.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++

// C++ program to demonstrate static


// variables inside a class

#include <iostream>

using namespace std;

class GfG {

public:

static int i;

GfG(){

// Do nothing

};

};

int GfG::i = 1;

int main()

{
GfG obj;

// prints value of i

cout << obj.i;

Output
1

Static Members of Class


Class objects as static: Just like variables, objects also when declared as static have a
scope till the lifetime of the program. Consider the below program where the object is
non-static.
 C++

// CPP program to illustrate

// when not using static keyword

#include <iostream>

using namespace std;

class GfG {

int i;

public:
GfG()

i = 0;

cout << "Inside Constructor\n";

~GfG() { cout << "Inside Destructor\n"; }

};

int main()

int x = 0;

if (x == 0) {

GfG obj;

cout << "End of main\n";

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

// CPP program to illustrate

// class objects as static

#include <iostream>

using namespace std;

class GfG {

int i = 0;

public:

GfG()

i = 0;

cout << "Inside Constructor\n";

}
~GfG() { cout << "Inside Destructor\n"; }

};

int main()

int x = 0;

if (x == 0) {

static GfG obj;

cout << "End of main\n";

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

// C++ program to demonstrate static

// member function in a class

#include <iostream>

using namespace std;

class GfG {

public:

// static member function

static void printMsg() { cout << "Welcome to GfG!"; }

};

// main function

int main()

// invoking a static member function

GfG::printMsg();

}
Output
Welcome to GfG!

Friend Class and Function in C++


Last Updated : 30 May, 2023



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

// functioning of a friend class

#include <iostream>

using namespace std;

class GFG {

private:

int private_variable;

protected:

int protected_variable;

public:

GFG()

private_variable = 10;

protected_variable = 99;

}
// friend class declaration

friend class F;

};

// Here, class F is declared as a

// friend inside class GFG. Therefore,

// F is a friend of class GFG. Class F

// can access the private members of

// class GFG.

class F {

public:

void display(GFG& t)

cout << "The value of Private Variable = "

<< t.private_variable << endl;

cout << "The value of Protected Variable = "

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

1. Global Function as Friend Function

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

// C++ program to create a global function as a friend

// function of some class

#include <iostream>

using namespace std;

class base {

private:

int private_variable;

protected:

int protected_variable;

public:
base()

private_variable = 10;

protected_variable = 99;

// friend function declaration

friend void friendFunction(base& obj);

};

// friend function definition

void friendFunction(base& obj)

cout << "Private Variable: " << obj.private_variable

<< endl;

cout << "Protected Variable: " << obj.protected_variable;

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

2. Member Function of Another Class as 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++

// C++ program to create a member function of another class


// as a friend function

#include <iostream>

using namespace std;

class base; // forward definition needed

// another class in which function is declared

class anotherClass {

public:

void memberFunction(base& obj);

};

// base class for which friend is declared

class base {

private:

int private_variable;

protected:
int protected_variable;

public:

base()

private_variable = 10;

protected_variable = 99;

// friend function declaration

friend void anotherClass::memberFunction(base&);

};

// friend function definition

void anotherClass::memberFunction(base& obj)

cout << "Private Variable: " << obj.private_variable

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

// C++ Program to demonstrate

// how friend functions work as

// a bridge between the classes

#include <iostream>

using namespace std;

// Forward declaration

class ABC;
class XYZ {

int x;

public:

void set_data(int a)

x = a;

friend void max(XYZ, ABC);

};

class ABC {

int y;

public:

void set_data(int a)

{
y = a;

friend void max(XYZ, ABC);

};

void max(XYZ t1, ABC t2)

if (t1.x > t2.y)

cout << t1.x;

else

cout << t2.y;

// Driver code

int main()

ABC _abc;
XYZ _xyz;

_xyz.set_data(20);

_abc.set_data(35);

// calling friend function

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

Advantages of Friend Functions


 A friend function is able to access members without the need of inheriting the
class.
 The friend function acts as a bridge between two classes by accessing their private
data.
 It can be used to increase the versatility of overloaded operators.
 It can be declared either in the public or private or protected part of the class.
Disadvantages of Friend Functions
 Friend functions have access to private members of a class from outside the class
which violates the law of data hiding.
 Friend functions cannot do any run-time polymorphism in their members.
Important Points About Friend Functions and Classes
1. Friends should be used only for limited purposes. Too many functions or external
classes are declared as friends of a class with protected or private data access
lessens the value of encapsulation of separate classes in object-oriented
programming.
2. Friendship is not mutual. If class A is a friend of B, then B doesn’t become a
friend of A automatically.
3. Friendship is not inherited. (See this for more details)
4. The concept of friends is not in Java.
Virtual Destructor
Last Updated : 20 Feb, 2023



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

// CPP program without virtual destructor

// causing undefined behavior

#include <iostream>

using namespace std;

class base {

public:
base()

{ cout << "Constructing base\n"; }

~base()

{ cout<< "Destructing base\n"; }

};

class derived: public base {

public:

derived()

{ cout << "Constructing derived\n"; }

~derived()

{ cout << "Destructing derived\n"; }

};

int main()

derived *d = new derived();

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

// A program with virtual destructor

#include <iostream>

using namespace std;

class base {

public:

base()
{ cout << "Constructing base\n"; }

virtual ~base()

{ cout << "Destructing base\n"; }

};

class derived : public base {

public:

derived()

{ cout << "Constructing derived\n"; }

~derived()

{ cout << "Destructing derived\n"; }

};

int main()

derived *d = new derived();

base *b = d;

delete b;
getchar();

return 0;

Output
Constructing base
Constructing derived
Destructing derived
Destructing base

Pure Virtual Functions and Abstract Classes in


C++
Last Updated : 11 Jun, 2023



Sometimes implementation of all functions cannot be provided in a base class because


we don’t know the implementation. Such a class is called an abstract class.For
example, let Shape be a base class. We cannot provide the implementation of function
draw() in Shape, but we know every derived class must have an implementation of
draw(). Similarly, an Animal class doesn’t have the implementation of move()
(assuming that all animals move), but all animals must know how to move. We cannot
create objects of abstract classes.
A pure virtual function (or abstract function) in C++ is a virtual function for which
we can have an implementation, But we must override that function in the derived
class, otherwise, the derived class will also become an abstract class. A pure virtual
function is declared by assigning 0 in the declaration.
Example of Pure Virtual Functions
 C++
// An abstract class

class Test {

// Data members of class

public:

// Pure Virtual Function

virtual void show() = 0;

/* Other members */

};

Complete Example

A pure virtual function is implemented by classes that are derived from an Abstract
class.

 C++

// C++ Program to illustrate the abstract class and virtual

// functions

#include <iostream>

using namespace std;


class Base {

// private member variable

int x;

public:

// pure virtual function

virtual void fun() = 0;

// getter function to access x

int getX() { return x; }

};

// This class inherits from Base and implements fun()

class Derived : public Base {

// private member variable

int y;
public:

// implementation of the pure virtual function

void fun() { cout << "fun() called"; }

};

int main(void)

// creating an object of Derived class

Derived d;

// calling the fun() function of Derived class

d.fun();

return 0;

Output
fun() called

Some Interesting Facts

1. A class is abstract if it has at least one pure virtual function.


Example
In the below C++ code, Test is an abstract class because it has a pure virtual function
show().

 C++

// C++ program to illustrate the abstract class with pure

// virtual functions

#include <iostream>

using namespace std;

class Test {

// private member variable

int x;

public:

// pure virtual function

virtual void show() = 0;

// getter function to access x

int getX() { return x; }

};
int main(void)

// Error: Cannot instantiate an abstract class

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

// C++ program that demonstrate that

// we can have pointers and references

// of abstract class type.


#include <iostream>

using namespace std;

class Base {

public:

// pure virtual function

virtual void show() = 0;

};

class Derived : public Base {

public:

// implementation of the pure virtual function

void show() { cout << "In Derived \n"; }

};

int main(void)

// creating a pointer of type


// Base pointing to an object

// of type Derived

Base* bp = new Derived();

// calling the show() function using the

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

// C++ program to demonstrate that if we do not override

// the pure virtual function in the derived class, then

// the derived class also becomes an abstract class


#include <iostream>

using namespace std;

class Base {

public:

// pure virtual function

virtual void show() = 0;

};

class Derived : public Base {

};

int main(void)

// creating an object of Derived class

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

// C++ program to demonstrate that

// an abstract class can have constructors.

#include <iostream>

using namespace std;

// An abstract class with constructor

class Base {

protected:

// protected member variable

int x;
public:

// pure virtual function

virtual void fun() = 0;

// constructor of Base class

Base(int i)

x = i;

cout << "Constructor of base called\n";

};

class Derived : public Base {

// private member variable

int y;

public:
// calling the constructor of Base class

Derived(int i, int j)

: Base(i)

y = j;

// implementation of pure virtual function

void fun()

cout << "x = " << x << ", y = " << y << '\n';

};

int main(void)

// creating an object of Derived class

Derived d(4, 5);


// calling the fun() function of Derived class

d.fun();

// creating an object of Derived class using

// a pointer of the Base class

Base* ptr = new Derived(6, 7);

// calling the fun() function using the

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

Comparison with Java


In Java, a class can be made abstract by using an abstract keyword. Similarly, a
function can be made pure virtual or abstract by using an abstract keyword.
See Abstract Classes in Java for more details.
Interface vs Abstract Classes
An interface does not have an implementation of any of its methods, it can be
considered as a collection of method declarations. In C++, an interface can be
simulated by making all methods pure virtual. In Java, there is a separate keyword for
the interface.
We can think of Interface as header files in C++, like in header files we only provide
the body of the class that is going to implement it. Similarly in Java in Interface we
only provide the body of the class and we write the actual code in whatever class
implements it.

Implementation of Singleton Class in C++


Last Updated : 08 Nov, 2022



A singleton class is a special type of class in object-oriented programming which can


have only one object or instance at a time. In other words, we can instantiate only one
instance of the singleton class. The new variable also points to the initial instance
created if we attempt to instantiate the Singleton class after the first time. This is
implemented by using the core concepts of object-oriented programming namely
access modifiers, constructors & static methods.
Steps to Implement Singleton Class in C++:
1. Make all the constructors of the class private.
2. Delete the copy constructor of the class.
3. Make a private static pointer that can point to the same class object (singleton
class).
4. Make a public static method that returns the pointer to the same class object
(singleton class).
Below is the implementation of the singleton class in C++:

 C++

// Implementation of Singleton Class

// in C++

#include <bits/stdc++.h>

using namespace std;

class Singleton{

private:

// member variables

string name, loves;

static Singleton*

// static pointer which will points

//to the instance of this class

instancePtr;
// Default constructor

Singleton()

public:

// deleting copy constructor

Singleton(const Singleton& obj)

= delete;

/*

getInstance() is a static method that returns an

instance when it is invoked. It returns the same

instance if it is invoked more than once as an instance

of Singleton class is already created. It is static

because we have to invoke this method without any object


of Singleton class and static method can be invoked

without object of class

As constructor is private so we cannot create object of

Singleton class without a static method as they can be

called without objects. We have to create an instance of

this Singleton class by using getInstance() method.

*/

static Singleton* getInstance()

// If there is no instance of class

// then we can create an instance.

if (instancePtr == NULL)

// We can access private members

// within the class.

instancePtr = new Singleton();


// returning the instance pointer

return instancePtr;

else

// if instancePtr != NULL that means

// the class already have an instance.

// So, we are returning that instance

// and not creating new one.

return instancePtr;

// sets values of member variables.

void setValues(string name,

string loves)

this->name = name;
this->loves = loves;

// prints values of member variables

void print()

cout << name << " Loves " <<

loves << "." << endl;

};

// initializing instancePtr with NULL

Singleton* Singleton ::instancePtr = NULL;

// Driver code

int main()

Singleton* GeeksForGeeks
= Singleton ::getInstance();

// setting values of member variables.

GeeksForGeeks->setValues("Manish",

"GeeksForGeeks");

// printing values of member variables.

GeeksForGeeks ->print();

cout << "Address of GeeksForGeeks: " <<

GeeksForGeeks << endl;

cout << endl;

Singleton* gfg = Singleton ::getInstance();

// setting values of member variables.

gfg->setValues("Vartika",
"GeeksForGeeks");

// Printing values of member variables.

gfg->print();

cout << "Address of gfg: " << gfg << endl;

return 0;

Output
Manish Loves GeeksForGeeks.
Address of GeeksForGeeks: 0x1793010

Vartika Loves GeeksForGeeks.


Address of gfg: 0x1793010
Explanation:
 Firstly, we made all the constructor private so that an instance of the Singleton
class can’t be instantiated from outside of it.
 We deleted copy constructor so that copy of the instance cannot be created.
 Created a static member instancePtr and initialized it with NULL. It points to the
instance of Singleton class.
 Created a getInstance() method which returns an instance of the Singleton class. It
is a static method because static variables are accessed by only static methods and
we have to access instancePtr which is a static member.
 If there already exists an instance of the Singleton class then getInstance() will
return a pointer to that instance as we can have only one instance of the Singleton
class.
 If instancePtr == NULL that means there exists no instance of the Singleton class.
So, getInstance() will instantiate an instance of the Singleton class and return a
pointer to it.
 We cannot create an instance of the Singleton class as all constructors are private.
We have to use the getInstance() method to get an instance of it.
Case 1: An instance of the Singleton Class is created beforehand.
In this implementation, we are creating an instance of the Singleton class beforehand
(i.e. initializing instancePtr with an instance instead of NULL using a new keyword)
and returning it when getInstance() is invoked.
Below is the C++ program to implement the above approach:

 C++

// C++ program to implement

// the above approach

#include <bits/stdc++.h>

using namespace std;

class Singleton{

private:

// member variables

string name, loves;

// initializing instancePtr with an


// instance(outside of this class we

// are initializing instancePtr with

// an object.)

static Singleton *instancePtr;

// Default constructor

Singleton()

public:

// deleting copy constructor.

Singleton(const Singleton &obj) = delete;

// returns instancePtr and instancePtr

// is pointing to an instance of

// Singleton class
static Singleton *getInstance()

return instancePtr;

void setValues(string name,

string loves)

this->name = name;

this->loves = loves;

void print()

cout << name << " Loves " <<

loves << "." << endl;

};
// initializing instancePtr with an instance

Singleton *Singleton ::instancePtr

= new Singleton();

// Driver code

int main()

Singleton *gfg

= Singleton::getInstance();

gfg->setValues("Learner",

"GeeksForGeeks");

gfg->print();

cout << "Address of gfg : " <<

gfg << endl;

// for output indentation


cout << endl;

Singleton *geeksForGeeks

= Singleton::getInstance();

geeksForGeeks->setValues("Everyone",

"GeeksForGeeks");

geeksForGeeks->print();

cout << "Address of geeksForGeeks : " <<

geeksForGeeks << endl;

return 0;

Output
Learner Loves GeeksForGeeks.
Address of gfg : 0xd63010

Everyone Loves GeeksForGeeks.


Address of geeksForGeeks : 0xd63010
Explanation:
 Firstly, we made all the constructor private so that an instance of the Singleton
class can’t be instantiated from outside of it.
 We deleted copy constructor so that copy of the instance cannot be created.
 Created a static member instancePtr and initialized it with an instance using the
new keyword. It is pointing to the instance of the Singleton class.
 Created a getInstance() method which returns instancePtr of the Singleton class. It
is a static method because static variables are accessed by only static methods and
we have to access instancePtr which is a static member.
 We cannot create an instance of the Singleton class as all constructors are private.
We have to use the getInstance() method to get an instance of it.
Case 2: When the instance is created without using the getInstance() method to
create the Singleton Class.
Below is the C++ program to implement the singleton class without using
getinstance() method:

 C++

// C++ program to create singleton class

// without using getinstance() method

#include<bits/stdc++.h>

using namespace std;

class Singleton{

private:

// member variables

string name, loves;

// static pointer which points


// to the instance of this class.

static Singleton *instancePtr;

// Default constructor

Singleton()

//same as above

Singleton(string name,

string loves)

this->name = name;

this->loves = loves;

public:
// deleting copy constructor.

Singleton(const Singleton &obj) = delete;

static Singleton *getInstance()

// If there is no instance of class

// then we can create an instance.

if(instancePtr == NULL)

// We can access private members

// within the class.

instancePtr = new Singleton();

// returning the instance pointer.

return instancePtr;

}
else

// if instancePtr != NULL that means

// the class already has an instance.

// So, we are returning that instance

// and not creating new one.

return instancePtr;

// sets values of member variables.

void setValues(string name,

string loves)

this->name = name;

this->loves = loves;

}
// prints values of member variables.

void print()

cout << name << " Loves " <<

loves << "." << endl;

};

// initializing instancePtr with NULL

Singleton *Singleton ::instancePtr = NULL;

// Driver code

int main()

// Gives error

Singleton *geeksForGeeks

= new Singleton();
// Cannot create object of Singleton class

// as default constructor is private &

// no method is used to access it.

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

An abstract class is a class that is specially designed to be used as a base class.


Abstract class must have at least one pure virtual function. It may have variables and
normal functions. The derived classes of an abstract class must implement all the pure
virtual functions of their base class or else they too become abstract.

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.

Rules While Using Interfaces

 Declare only pure virtual functions. (No definition)


 For pure virtual functions assign only 0.
 Cannot create an instance of the class.
 We can create a pointer to the instance of the derived class with a reference of a
base abstract class.
Let’s look into a few sample examples of programs for creating the interface.
Example 1: In the below code, an interface GFG i.e. an abstract class is created with
a pure virtual method, and its function is implemented in the child class, and in the
main function, we called the returnString() method by following the rules of using
interfaces.
 C++

// C++ program to implement


// Interface

#include <iostream>

#include <string>

using namespace std;

// Interface(Abstract class

// with pure virtual function)

class GFG

public:

virtual string returnString() = 0;

};

class child : public GFG

public:

string returnString()
{

return "GeeksforGeeks";

};

// Driver code

int main()

child childObj;

GFG* ptr;

ptr = &childObj;

cout << ptr->returnString();

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>

using namespace std;

// Interface(Abstract class

// with pure virtual function)

class websiteName

public:

virtual string getName() = 0;

};

class shortForm : public websiteName

public:

string getName()
{

return "GFG";

};

class fullForm : public websiteName

public:

string getName()

return "GeeksforGeeks";

};

// Driver code

int main()

shortForm obj1;
fullForm obj2;

websiteName* ptr;

ptr = &obj1;

cout << "Short form - " <<

ptr->getName();

ptr = &obj2;

cout << "\nFull form - " <<

ptr->getName();

return 0;

Output
Short form - GFG
Full form - GeeksforGeeks

Increment (++) and Decrement (–) Operator


Overloading in C++
Last Updated : 16 Nov, 2022



Operator overloading is a feature in object-oriented programming which allows a


programmer to redefine a built-in operator to work with user-defined data types.
Why Operator Overloading?
Let’s say we have defined a class Integer for handling operations on integers. We can
have functions add(), subtract(), multiply() and divide() for handling the respective
operations. However, to make the code more intuitive and enhance readability, it is
preferred to use operators that correspond to the given operations(+, -, *, /
respectively) i.e. we can replace the following code.
Example:
Replace
i5 = divide(add(i1, i2), subtract(i3, i4))

by a simpler code:
i5 = (i1 + i2) / (i3 - i4)

Overloading the Increment Operator

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

// C++ program to demonstrate

// prefix increment operator overloading

#include <bits/stdc++.h>

using namespace std;

class Integer {

private:
int i;

public:

// Parameterised constructor

Integer(int i = 0)

this->i = i;

// Overloading the prefix operator

Integer& operator++()

++i;

// returned value should be a reference to *this

return *this;

// Function to display the value of i


void display()

cout << "i = " << i << endl;

};

// Driver function

int main()

Integer i1(3);

cout << "Before increment: ";

i1.display();

// Using the pre-increment operator

Integer i2 = ++i1;

cout << "After pre increment: " << endl;


cout << "i1: ";

i1.display();

cout << "i2: ";

i2.display();

Output
Before increment: i = 3
After post decrement:
i1: i = 4
i2: i = 4
Example: Post-Increment Overloading
 CPP

// C++ program to demonstrate

// postfix increment operator

// overloading

#include <bits/stdc++.h>

using namespace std;

class Integer {
private:

int i;

public:

// Parameterised constructor

Integer(int i = 0)

this->i = i;

// Overloading the postfix operator

Integer operator++(int)

// returned value should be a copy of the object before increment

Integer temp = *this;

++i;

return temp;

}
// Function to display the value of i

void display()

cout << "i = " << i << endl;

};

// Driver function

int main()

Integer i1(3);

cout << "Before increment: ";

i1.display();

// Using the post-increment operator

Integer i2 = i1++;
cout << "After post increment: " << endl;

cout << "i1: ";

i1.display();

cout << "i2: ";

i2.display();

Output
Before increment: i = 3
After post increment:
i1: i = 4
i2: i = 3

Overloading the Decrement Operator

Similarly, we can also overload the decrement operator as follows:


Example: Pre-Decrement Overloading
 CPP

// C++ program to demonstrate

// prefix decrement operator

// overloading
#include <bits/stdc++.h>

using namespace std;

class Integer {

private:

int i;

public:

// Parameterised constructor

Integer(int i = 0)

this->i = i;

// Overloading the prefix operator

Integer& operator--()

{
--i;

// returned value should be a reference to *this

return *this;

// Function to display the value of i

void display()

cout << "i = " << i << endl;

};

// Driver function

int main()

Integer i1(3);

cout << "Before decrement: ";


i1.display();

// Using the pre-decrement operator

Integer i2 = --i1;

cout << "After pre decrement: " << endl;

cout << "i1: ";

i1.display();

cout << "i2: ";

i2.display();

Output
Before decrement: i = 3
After pre decrement:
i1: i = 2
i2: i = 2
Example: Post-Decrement Overloading
 CPP

// C++ program to demonstrate


// postfix decrement operator

// overloading

#include <bits/stdc++.h>

using namespace std;

class Integer {

private:

int i;

public:

// Parameterised constructor

Integer(int i = 0)

this->i = i;

// Overloading the postfix operator

Integer operator--(int)
{

// returned value should be a copy of the object before decrement

Integer temp = *this;

--i;

return temp;

// Function to display the value of i

void display()

cout << "i = " << i << endl;

};

// Driver function

int main()

Integer i1(3);
cout << "Before decrement: ";

i1.display();

// Using the post-decrement operator

Integer i2 = i1--;

cout << "After post decrement: " << endl;

cout << "i1: ";

i1.display();

cout << "i2: ";

i2.display();

Output
Before decrement: i = 3
After post decrement:
i1: i = 2
i2: i = 3

C++ Program To Add Two Complex Numbers


Last Updated : 23 Jun, 2023


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

Explanation: (4 + i8) + (5 + i7)


= (4 + 5) + i(8 + 7)
= 9 + i15
Below is the C++ program to add two complex numbers:
 C++

// C++ Program to Add

// Two Complex Numbers

// Importing all libraries

#include<bits/stdc++.h>

using namespace std;

// User Defined Complex class

class Complex
{

// Declaring variables

public: int real, imaginary;

// Constructor to accept

// real and imaginary part

Complex(int tempReal = 0,

int tempImaginary = 0)

real = tempReal;

imaginary = tempImaginary;

// Defining addComp() method

// for adding two complex number

Complex addComp(Complex C1, Complex C2)

// Creating temporary variable


Complex temp;

// Adding real part of

// complex numbers

temp.real = C1.real + C2.real;

// Adding Imaginary part of

// complex numbers

temp.imaginary = (C1.imaginary + C2.imaginary);

// Returning the sum

return temp;

};

// Driver code

int main()

{
// First Complex number

Complex C1(3, 2);

// printing first complex number

cout << "Complex number 1 : " <<

C1.real << " + i" <<

C1.imaginary << endl;

// Second Complex number

Complex C2(9, 5);

// Printing second complex number

cout << "Complex number 2 : " <<

C2.real << " + i" <<

C2.imaginary << endl;

// For Storing the sum

Complex C3;
// Calling addComp() method

C3 = C3.addComp(C1, C2);

// Printing the sum

cout << "Sum of complex number : " <<

C3.real << " + i" <<

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:

// C++ implementation to create a file

#include <bits/stdc++.h>

using namespace std;

// Driver code

int main()

// fstream is Stream class to both

// read and write from/to files.

// file is object of fstream class

fstream file;
// opening file "Gfg.txt"

// in out(write) mode

// ios::out Open for output operations.

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

// If no file is created, then

// show the error message.

if(!file)

cout<<"Error in creating file!!!";

return 0;

cout<<"File created successfully.";

// closing the file.

// The reason you need to call close()


// at the end of the loop is that trying

// to open a new file without closing the

// first file will fail.

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

// C++ program to create a temporary file

// read and write to a temporary file.

#include <cstdio>

#include <cstdlib>

#include <iostream>

using namespace std;


// Driver code

int main()

// Creating a file pointer which

// points to the temporary file

// created by tmpfile() method

FILE* fp = tmpfile();

// Content to be written in temporary file

char write[] = "Welcome to Geeks For Geeks";

// If file pointer is NULL there is

// error in creating the file

if (fp == NULL)

perror("Error creating temporary file");

exit(1);

}
// Writing in temporary file the content

fputs(write, fp);

rewind(fp);

// Reading content from temporary file

// and displaying it

char read[100];

fgets(read, sizeof(read), fp);

cout << read;

// Closing the file. Temporary file will

// also be deleted here

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 :

To write object's data members in a file :


// Here file_obj is an object of ofstream
file_obj.write((char *) & class_obj, sizeof(class_obj));

To read file's data members into an object :


// Here file_obj is an object of ifstream
file_obj.read((char *) & class_obj, sizeof(class_obj));
Examples:
Input :
Input.txt :
Michael 19 1806
Kemp 24 2114
Terry 21 2400
Operation : Print the name of the highest
rated programmer.

Output :
Terry

 C++
// C++ program to demonstrate read/write of class

// objects in C++.

#include <iostream>

#include <fstream>

using namespace std;

// Class to define the properties

class Contestant {

public:

// Instance variables

string Name;

int Age, Ratings;

// Function declaration of input() to input info

int input();

// Function declaration of output_highest_rated() to

// extract info from file Data Base


int output_highest_rated();

};

// Function definition of input() to input info

int Contestant::input()

// Object to write in file

ofstream file_obj;

// Opening file in append mode

file_obj.open("Input.txt", ios::app);

// Object of class contestant to input data in file

Contestant obj;

// Feeding appropriate data in variables

string str = "Michael";

int age = 18, ratings = 2500;


// Assigning data into object

obj.Name = str;

obj.Age = age;

obj.Ratings = ratings;

// Writing the object's data in file

file_obj.write((char*)&obj, sizeof(obj));

// Feeding appropriate data in variables

str = "Terry";

age = 21;

ratings = 3200;

// Assigning data into object

obj.Name = str;

obj.Age = age;

obj.Ratings = ratings;
// Writing the object's data in file

file_obj.write((char*)&obj, sizeof(obj));

//close the file

//It's always a good practice to close the file after opening them

file_obj.close();

return 0;

// Function definition of output_highest_rated() to

// extract info from file Data Base

int Contestant::output_highest_rated()

// Object to read from file

ifstream file_obj;
// Opening file in input mode

file_obj.open("Input.txt", ios::in);

// Object of class contestant to input data in file

Contestant obj;

// Reading from file into object "obj"

file_obj.read((char*)&obj, sizeof(obj));

// max to store maximum ratings

int max = 0;

// Highest_rated stores the name of highest rated contestant

string Highest_rated;

// Checking till we have the feed

while (!file_obj.eof()) {

// Assigning max ratings


if (obj.Ratings > max) {

max = obj.Ratings;

Highest_rated = obj.Name;

// Checking further

file_obj.read((char*)&obj, sizeof(obj));

// close the file.

//It's always a good practice to close the file after opening them

file_obj.close();

// Output is the highest rated contestant

cout << Highest_rated;

return 0;

}
// Driver code

int main()

// Creating object of the class

Contestant object;

// Inputting the data

object.input();

// Extracting the max rated contestant

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

 old_name: String that represents the name of an existing file to be renamed.


 new_name: String containing the new name of the file.

Return Value

The return type of the function is an integer.


 If the file is renamed successfully, zero is returned and it prints a success
message.
 On failure, a nonzero value is returned and it prints an error message using
perror().
Example of rename()
Assume that we have a text file having the name geeks.txt, having some content. So,
we are going to rename this file, using the below C program present in the same folder
where this file is present.
C Program to Demonstrate the use of rename() Function

 C

// C program to demonstrate use of rename()

#include <stdio.h>

int main()

// Old file name

char old_name[] = "geeks.txt";

// Any string

char new_name[] = "geeksforgeeks.txt";

int value;

// File name is changed here

value = rename(old_name, new_name);

// Print the result


if (!value) {

printf("%s", "File name changed successfully");

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

C++ Program to Make a File Read-Only


Last Updated : 28 Jul, 2022




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

// C++ program to make the file

// in read-only mode using ifstream

#include <fstream>

#include <iostream>

using namespace std;

int main()

// creating an input stream

ifstream in;

// opening a file in read mode using in


in.open("Geeks for Geeks.txt");

if (!in)

cout << "No file found";

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

// C++ program to make the file

// in read-only mode using fstream

#include <fstream>

#include <iostream>

using namespace std;

int main()

fstream readFile;

// opening a file in read mode

readFile.open("Geeks for Geeks.txt", ios::in);

if (!readFile)

cout << "No such file exist";

else {

char c;

while (1) {

readFile >> c;
if (readFile.eof())

break;

cout << c;

// closing the file

readFile.close();

return 0;

Output:
Geeks_for_Geeks

C++ Program to Compare Paths of Two Files


Last Updated : 15 Dec, 2022



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 :

1. To store paths use string as data type


2. Use pathname1. Compare( pathname2 ), to compare two paths , this will return
three values greater that 0 , less than 0 or equal to 0
Example:
 C++

// C++ Program to Compare Paths of Two Files

#include <iostream>

using namespace std;

// function to compare two paths

void pathCompare(string p1, string p2)

// stores compared value 0 or >0 or <0

const int res = p1.compare(p2);

if (res > 0)

cout << p1 << " is greater than " << p2;

else if (res == 0)

cout << p1 << " is equal to " << p2;


else

cout << p1 << " is less than " << p2;

cout << "\n";

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

pathCompare(p1, p2); // function call

pathCompare(p3, p4); // function call

pathCompare(p5, p6); // function call

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.

Using iteration(for & while loop) :

1. To store paths use string as data type


2. Use for or while loop and compare each character of them one by one.
Syntax:
while(path1[i] != '\0' || path2[i] != '\0'){
//compare the character
//increment value of i
}

OR

for(int i = 0; path1[i] != '\0' || path2[i] != '\0'; i++){


//compare the character
}
Below is the implementation of the above approach:

 C++
 C++

// C++ Program to Compare Paths of Two Files

// using for loop


#include <iostream>

using namespace std;

// function to compare two paths

void pathCompare(string p1, string p2)

// for loop to compare the paths

for (int i = 0; p1[i] != '\0' || p2[i] != '\0'; i++) {

// compare the character

if (p1[i] != p2[i]) {

cout << p1 << " is not equal to " << p2 << endl;

return;

cout << p1 << " is equal to " << p2 << endl;

}
// 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.";

pathCompare(p1, p2); // function call

pathCompare(p3, p4); // function call

pathCompare(p5, p6); // function call

return 0;

// This code is contributed by Susobhan Akhuli

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:

1. To store paths use string as data type


2. Use comparison operators (<, >, ==) to compare two paths.

syntax:

if(path1 > path2)


// path1 is greater
else if(path1 < path2)
// path2 is greater
else
// both paths are same
Example:
 C++

// C++ Program to Compare Paths of Two Files

// using if-else condition

#include <iostream>

using namespace std;

// function to compare two paths

void pathCompare(string p1, string p2)

{
// Comparing using if-else

if (p1 > p2)

cout << p1 << " is greater than " << p2 << endl;

else if (p1 < p2)

cout << p1 << " is less than " << p2 << endl;

else

cout << p1 << " is equal to " << p2 << endl;

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

pathCompare(p1, p2); // function call

pathCompare(p3, p4); // function call

pathCompare(p5, p6); // function call

return 0;

// This code is contributed by Susobhan Akhuli

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

// C++ Program to demonstrate

// copying the content of a .txt file

#include <fstream>

#include <iostream>

using namespace std;

int main()

string line;

// For writing text file

// Creating ofstream & ifstream class object

ifstream ini_file{

"original.txt"
}; // This is the original file

ofstream out_file{ "copy.txt" };

if (ini_file && out_file) {

while (getline(ini_file, line)) {

out_file << line << "\n";

cout << "Copy Finished \n";

else {

// Something went wrong

printf("Cannot read File");

// Closing file

ini_file.close();

out_file.close();

return 0;

Output:
Original File – original.txt:

File: original.txt

Copy program running:


Copy File – copy.txt:
Copied file: copy.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.

C++ program to append content of one text file


to another
Last Updated : 23 Nov, 2022




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

// C++ implementation to append

// content from source file to

// destination file

#include <bits/stdc++.h>

using namespace std;

// driver code

int main()

fstream file;
// Input stream class to

// operate on files.

ifstream ifile("file.txt", ios::in);

// Output stream class to

// operate on files.

ofstream ofile("file2.txt", ios::out | ios::app);

// check if file exists

if (!ifile.is_open()) {

// file not found (i.e, not opened).

// Print an error message.

cout << "file not found";

else {

// then add more lines to


// the file if need be

ofile << ifile.rdbuf();

string word;

// opening file

file.open("file2.txt");

// extracting words form the file

while (file >> word) {

// displaying content of

// destination file

cout << word << " ";

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

// C++ program to Append and Read text of text files

#include <bits/stdc++.h>

using namespace std;

int main()

// open file in read mode to read it's content

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


// open file in append mode to append read content

FILE* file2 = fopen("file2.txt", "a");

if (file2 == NULL) {

cout << "file not found";

return 1;

else if (file == NULL) {

cout << "file not found";

return 1;

// Read contents from file

char ch = fgetc(file);

while (ch != EOF) {

// print read content from file in file2

fprintf(file2, "%c", ch);

ch = fgetc(file);
}

fclose(file);

fclose(file2);

// open file 2 again in read mode to read the content

FILE* file3 = fopen("file2.txt", "r");

// Read contents from file

char ch2 = fgetc(file3);

while (ch2 != EOF) {

// print read content from file

printf("%c", ch2);

ch2 = fgetc(file3);

fclose(file3);

}
// This code is contributed by Shivesh Kumar Dwivedi

Output
file not found

C++ Program to Get the List of Files in a


Directory
Last Updated : 06 Feb, 2023



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.

File explorer to view directories

Code:
 C++

// C++ Program to Getting

// the list of files using


// the system function

#include <bits/stdc++.h>

#include <cstdlib>

#include <iostream>

using namespace std;

int main()

// This variable contains the path to the directory

// The path should be given inside double quotes

// Therefore, escaped the enclosing quotes using

// backslash

string path(

"\"C:\\Users\\Sauleyayan\\Desktop\\New folder\"");

// The command which would do the file listing

// A space is added at the end of the command


// intentionally to make space for the path

string command("dir /a-d ");

// The path is appended after the command string

command.append(path);

// The string is converted to const char * as system

// function requires

const char* final_command = command.c_str();

// Sending the final command as the argument to the

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

// C++ Program for Getting

// the list of files using


// the directory_iterator function

#include <filesystem>

#include <iostream>

#include <string>

#include <sys/stat.h>

namespace fs = std::filesystem;

int main()

// Path to the directory

std::string path

= "C:\\Users\\Sauleyayan\\Desktop\\New folder";

// This structure would distinguish a file from a

// directory

struct stat sb;


// Looping until all the items of the directory are

// exhausted

for (const auto& entry : fs::directory_iterator(path)) {

// Converting the path to const char * in the

// subsequent lines

std::filesystem::path outfilename = entry.path();

std::string outfilename_str = outfilename.string();

const char* path = outfilename_str.c_str();

// Testing whether the path points to a

// non-directory or not If it does, displays path

if (stat(path, &sb) == 0 && !(sb.st_mode & S_IFDIR))

std ::cout << path << std::endl;

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

// C++ program to demonstrate appending of

// a string using ofstream

#include <fstream>

#include <iostream>

#include <string>

using namespace std;

int main()

ofstream of;

fstream f;

// opening file using ofstream

of.open("Geeks for Geeks.txt", ios::app);

if (!of)

cout << "No such file found";

else {
of << " String";

cout << "Data appended successfully\n";

of.close();

string word;

// opening file using fstream

f.open("Geeks for Geeks.txt");

while (f >> word) {

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

// C++ program to demonstrate appending of

// a string using fstream

#include <fstream>

#include <string>

using namespace std;

int main()

fstream f;

f.open("Geeks for Geeks.txt", ios::app);

if (!f)

cout << "No such file found";

else {

f << " String_fstream";

cout << "Data appended successfully\n";

f.close();

string word;

f.open("Geeks for Geeks.txt");

while (f >> word) {


cout << word << " ";

f.close();

return 0;

Output:
Data appended successfully
Geeks for Geeks String_fstream

C++ Program to Read Content From One File


and Write it Into Another File
Last Updated : 04 Jul, 2022



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

// one file and write it to another file

#include<bits/stdc++.h>

using namespace std;

// Driver code

int main()

// Input file stream object to

// read from file.txt

ifstream in("file1.txt");

// Output file stream object to

// write to file2.txt

ofstream f("file2.txt");

// Reading file.txt completely using

// END OF FILE eof() method


while(!in.eof())

// string to extract line from

// file.txt

string text;

// extracting line from file.txt

getline(in, text);

// Writing the extracted line in

// file2.txt

f << text << endl;

return 0;

Output:
file1.txt
GeeksforGeeks is a Computer Science portal for geeks.
file2.txt
GeeksforGeeks is a Computer Science portal for geeks.

C++ Exception Handling Programs


C++ Program to Show Runtime Exceptions
Last Updated : 05 Jul, 2022



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

// C++ program to demonstrate

// division by zero exception

#include <iostream>

using namespace std;

// Driver code
int main()

int a = 10;

int res = a / 0;

cout << res;

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

// C++ program to demonstrate

// segmentation fault
#include <iostream>

using namespace std;

// Driver code

int main()

char *str;

// Stored in read only part

// of data segment

str = "GeeksforGeeks";

// Trying to modify read only

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

// C++ program to demonstrate

// large memory allocation

// runtime exception

#include <iostream>

using namespace std;

// Driver code

int main()

{
int a = 100000000000;

int * arr = new int[a];

return 0;

Output:

4. Type Specifier Error


The below code gives runtime error because here the variable “a” is defined as long
long int but in scanf the format specifier used is %d instead of %lld this will cause the
error.
Below is the C++ program to demonstrate the type specifier error:

 C++

// C++ program to demonstrate

// type specifier error

#include <iostream>

using namespace std;


// Driver code

int main()

long long int a;

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

5. Invalid Memory Access During Runtime


In the below code, the array is assigned with a negative index value and this will
cause invalid memory access. It will give a garbage value. Below is the C++ program
to demonstrate invalid memory access during runtime:

 C++

// C++ program to demonstrate

// invalid memory access during

// runtime
#include <iostream>

using namespace std;

int arr[5];

// Driver code

int main()

int a = arr[-10];

cout << a;

return 0;

Output
281923776

C++ Program to Show Types of Errors


Last Updated : 25 Jul, 2022



In any programming language errors is common. If we miss any syntax like


parenthesis or semicolon then we get syntax errors. Apart from this we also get run
time errors during the execution of code. In a similar way the errors are classified as
below:
1. Syntax Errors
2. Runtime Errors
3. Logical Errors
4. Linked Errors
5. Semantic Errors
1. Syntax Errors
These are also referred to as compile-time errors. These errors have occurred when the
rule of C++ writing techniques or syntax has been broken. These types of errors are
typically flagged by the compiler prior to compilation.
Example: In the below program we are getting an error because of a missing
semicolon at the end of the output statement (cout) called syntax error.
 C++

// C++ program to demonstrate

// a syntax error

#include <iostream>

using namespace std;

int main() {

cout << "Geeks for geeks!" // missing semicolon

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

// C++ program to demonstrate

// a runtime error

#include <iostream>

using namespace std;

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

// C++ program to demonstrate

// a logical error

#include <iostream>

using namespace std;

int main() {
int j;

// Cause of Logical error

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

cout << "Geeks for geeks";

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

// C++ program to demonstrate

// a linker error

#include <iostream>
using namespace std;

int Main() {

cout << "Geeks for geeks";

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

// C++ program to demonstrate


// a semantic error

#include <iostream>

using namespace std;

int main()

int a = 10, b = 20, c;

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

// Throw an exception when a problem arise


throw exception;
}
catch ()
{
// Block of code to handle errors
}
Below are the C++ programs to show how exceptions are handled in C++:
Example 1: Below is the C++ program to show what happens when division by zero
is done and exceptions are not handled.
 C++

// C++ program to show what happens

// when division by zero is done

// and exceptions are not handled

#include <iostream>

using namespace std;

// Driver code

int main()

int numerator = 5;

int denominator = 0;

int ans = numerator/denominator;

// The result will not be displayed

cout << ans << endl;


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

// C++ program to handle

// divide by zero exception

#include <iostream>

using namespace std;

// Driver code

int main()

int numerator = 5;

int denominator = 0;
int result;

try

if(denominator == 0)

throw denominator;

result = numerator / denominator;

catch(int ex)

cout << "Exception: Divide by zero not allowed :" <<

ex << endl;

cout << "Division Result is: " << result;

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

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

#include <iostream>

using namespace std;

// Driver code

int main()

try

{
int age = 10;

if (age >= 18)

cout << "YES, you are old enough.";

else

throw (age);

catch (int num)

cout << "No, You must be at least 18 years old" <<

endl;

cout << "Age is: " << num;

return 0;

Output
No, You must be at least 18 years old
Age is: 10

C++ Standard Exceptions

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

An exception and parent class of all the standard C++


1. std::exception
exceptions.

2. std::bad_alloc This exception can be thrown by new.

3. std::bad_cast This exception can be thrown by dynamic_cast.

This exception is a useful device to handle unexpected


4. std::bad_exception
exceptions in a C++ program.

5. std::bad_typeid This can be thrown by type id.

6. std::logic_error An exception that can be detected by reading the code.

This is an exception thrown when a mathematically


7. std::domain_error
invalid domain is used.

8. std::invalid_argument This exception is thrown due to invalid arguments.


S.No
. Exception Description

This exception is thrown when a too big std::string is


9. std::length_error
created.

This can be thrown by the ‘at’ method, for example a


10. std::out_of_range
std::vector and std::bitset<>::operator[]().

An exception that theoretically cannot be detected by


11. std::runtime_error
reading the code

12. std::overflow_error This is thrown if a mathematical overflow occurs.

This occurs when you try to store a value that is out of


13. std::range_error
range.

14. std::underflow_error This is thrown if a mathematical underflow occurs.

New Exception in C++


The customized exceptions can be defined by inheriting and overriding exception
class functionality.
Syntax:
use std::exception
Below is the C++ program to define a new exception:

 C++

// C++ program to define a


// new exception

#include <iostream>

#include <exception>

using namespace std;

struct Exceptions : public exception

const char* Except() const throw ()

return "GeeksforGeeks";

};

// Driver code

int main()

try

{
throw Exceptions();

catch(Exceptions& it)

cout << "Customised Exception caught" <<

endl;

cout << it.Except() <<endl;

catch(std::exception& it)

{}

Output
Customised Exception caught
GeeksforGeeks

C++ Program to Handle the Checked


Exceptions
Last Updated : 19 Jan, 2023




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

How Do you Handle Exceptions?


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.
The try-catch is the simplest method of handling exceptions. Put the code you want to
run in the try block and any Java exceptions that the code throws are caught by one or
more catch blocks. This method will catch any type of Java exceptions that get
thrown. This is the simplest mechanism for handling exceptions
Below is the C++ program to handle checked exceptions:

 C++

// C++ program to handle

// exceptions
#include <iostream>

using namespace std;

int division(int a, int b)

// Checking if the denominator

// is 0 or not.

if (b == 0)

// If the denominator is 0, then

// we must throw an exception

throw "Division by zero!";

// If there is no exception, then

// we are returning the answer.

return int(a / b);

}
// Driver code

int main()

int x = 50;

int y = 0;

int answer = 0;

/*

Using a try catch block because in division,

the denominator can be 0.

So, we must handle the 0 division inside try block.

*/

try

answer = division(x, y);

cout << " Output: " << answer << endl;

}
// Printing the thrown exception from

// the function

catch (const char *errorMessage)

cout << errorMessage << endl;

return 0;

Output:
Division by zero!

C++ Program to Handle the Unchecked


Exceptions
Last Updated : 02 Aug, 2022



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.

C++ Program to illustrate Division by Zero Exception


 C++
// C++ program to illustrate

// division by zero exception

#include <iostream>

using namespace std;

int main()

int Gfg1 = 9, Gfg2 = 0;

// try block starts here

try {

if (Gfg2 != 0)

cout << Gfg1 / Gfg2;

else

throw Gfg2; // throwing if Gfg2 is zero

// catch block starts here


catch (int i) {

/// if b is zero means division is done 0 hence

// thrown from try block and catch

cout << "Division by zero: " << i << endl;

return 0;

Output:
Division by zero: 0
C++ Program to illustrate Array Index Out of Bounds Exception
 C++

// C++ program to demonstrate

// array index out of bounds

// exception

#include <iostream>

using namespace std;


int main()

// initialize an array of

// size 5 with numbers from 1 to

// 5

int a[5] = { 1, 2, 3, 4, 5 }, i;

// try block starts here

try {

i = 0; // initialize i with 0

// loop for printing value of array till its

// size 5

while (1) {

if (i != 5) {

cout << a[i] << endl;

i++;

}
// if i go beyond 5 then throw exception

else

throw i;

// catch the exception

catch (int i) {

cout << "Array Index out of Bounds Exception: " << 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

// exceptions and define

// multiple catch statement

#include <iostream>

using namespace std;

// function to check if number is

// positive, negative or zero

void num(int k)

try {

if (k == 0)

throw k; // throwing int value

else if (k > 0)

throw 'P'; // throwing char value

else if (k < 0)
throw 1.0; // throwing double value

cout << "*** end of try block ***\n";

// catching char value

catch (char g) {

cout << "Caught a positive value \n";

// catching integer value

catch (int j) {

cout << "caught an null value \n";

// catching double value

catch (double f) {

cout << "Caught a Negative value \n";

cout << "*** end of try catch ***\n \n";


}

int main()

cout << "Demo of Multiple catches" << endl;

num(0); // function call for zero

num(5); // function call for positive

num(-1); // function call for negative

return 0;

Output:
Demo of Multiple catches
caught an null value
*** end of try catch ***

Caught a positive value


*** end of try catch ***

Caught a Negative value


*** end of try catch ***

Handling the Divide by Zero Exception in C++


Last Updated : 23 Jan, 2019




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.

// Program to show division without using

// Exception Handling

#include <iostream>

using namespace std;

// Defining function Division

float Division(float num, float den)

// return the result of division

return (num / den);

} // end Division
int main()

// storing 12.5 in numerator

// and 0 in denominator

float numerator = 12.5;

float denominator = 0;

float result;

// calls Division function

result = Division(numerator, denominator);

// display the value stored in result

cout << "The quotient of 12.5/0 is "

<< result << endl;

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

// Program to depict how to handle

// divide by zero exception

#include <iostream>

#include <stdexcept> // To use runtime_error

using namespace std;

// Defining function Division

float Division(float num, float den)

{
// If denominator is Zero

// throw runtime_error

if (den == 0) {

throw runtime_error("Math error: Attempted to divide by Zero\n");

// Otherwise return the result of division

return (num / den);

} // end Division

int main()

float numerator, denominator, result;

numerator = 12.5;

denominator = 0;

// try block calls the Division function


try {

result = Division(numerator, denominator);

// this will not print in this example

cout << "The quotient is "

<< result << endl;

// catch block catches exception thrown

// by the Division function

catch (runtime_error& e) {

// prints that exception has occurred

// calls the what function

// using runtime_error object

cout << "Exception occurred" << endl

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

// Program to depict user defined exception handling

#include <iostream>

#include <stdexcept>

// For using runtime_error

using namespace std;


// User defined class for handling exception

// Class Exception publicly inherits

// the runtime_error class

class Exception : public runtime_error {

public:

// Defining constructor of class Exception

// that passes a string message to the runtime_error class

Exception()

: runtime_error("Math error: Attempted to divide by Zero\n")

};

// defining Division function

float Division(float num, float den)

{
// If denominator is Zero

// throw user defined exception of type Exception

if (den == 0)

throw Exception();

// otherwise return the result of division

return (num / den);

} // end Division

int main()

float numerator, denominator, result;

numerator = 12.5;

denominator = 0;

// try block calls the Division function


try {

result = Division(numerator, denominator);

// this will not print in this example

cout << "The quotient is " << result << endl;

// catch block catches exception if any

// of type Exception

catch (Exception& e) {

// prints that exception has occurred

// calls the what function using object of

// the user defined class called Exception

cout << "Exception occurred" << endl

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

// Program to depict Exception Handling

// Using stack unwinding

#include <iostream>

#include <stdexcept>

using namespace std;

// defining the CheckDenominator function

float CheckDenominator(float den)


{

// if denominator is zero

// throw exception

if (den == 0) {

throw runtime_error("Math error: Attempted to divide by zero\n");

else

return den;

} // end CheckDenominator

// defining Division function

float Division(float num, float den)

// Division function calls CheckDenominator

return (num / CheckDenominator(den));

} // end Division
int main()

float numerator, denominator, result;

numerator = 12.5;

denominator = 0;

// try block calls the Division function

try {

result = Division(numerator, denominator);

// This will not print in this example

cout << "The quotient is "

<< result << endl;

// catch block catches exception if any

catch (runtime_error& e) {
// prints that exception has occurred

// calls the what function using object of

// runtime_error class

cout << "Exception occurred" << endl

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

// Program to depict use of try catch block

#include <iostream>

#include <stdexcept>
using namespace std;

// defining CheckDenominator

float CheckDenominator(float den)

if (den == 0)

throw "Error";

else

return den;

} // end CheckDenominator

int main()

float numerator, denominator, result;

numerator = 12.5;

denominator = 0;

// try block
try {

// calls the CheckDenominator function

// by passing a string "Error"

if (CheckDenominator(denominator)) {

result = (numerator / denominator);

cout << "The quotient is "

<< result << endl;

// catch block

// capable of catching any type of exception

catch (...) {

// Display a that exception has occurred

cout << "Exception occurred" << endl;


}

} // end main

Output:
Exception occurred

C++ Program to Show Unreachable Code Error


Last Updated : 25 Jul, 2022



Unreachable code is a compile-time error in languages like C++, Java, and C or


Unreachable code error occurs when the code can’t be compiled; but why it is just a
warning in C++ & C ? Warnings are a way that the compiler indicates that the
particular mentioned thing might become an error in future.
Example:
 C++

// C++ Program to demonstrate

// Unreacheable Code error

#include <iostream>

using namespace std;


int c();

int main()

cout << c() << endl;

return 0;

int c()

int a = 3;

return a; // oops it is unreachable code

int b = 6;

cout << b; // program control never goes here

Output
3

C++ Program to Show Thread Interface and


Memory Consistency Errors
Last Updated : 29 Jul, 2022




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

// C++ program to show

// memory consistency

#include <bits/stdc++.h>

#include <thread>

using namespace std;

class thread_obj {

public:

void operator()(int x)

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

cout << "Thread " << x << "\n";

};

// Driver code

int main()

// thread 1

thread th1(thread_obj(), 1);

// thread 2

thread th2(thread_obj(), 2);

// wait for thread1 to join

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

// C++ program to show memory

// consistency error

#include <iostream>

#include <thread>

using namespace std;

int x = 100;

void thread_function()

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

x--;

cout << "Thread 1 " <<

x << "\n";
}

// Driver code

int main()

std::thread t(&thread_function);

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

x++;

cout << "main thread " <<

x << "\n";

return 0;

}
Output – You can see inconsistency in output (It is machine Dependent)

C++ STL Programs


std::sort() in C++ STL
Last Updated : 23 Sep, 2023



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

// C++ program to demonstrate default behaviour of

// sort() in STL.

#include <bits/stdc++.h>

using namespace std;

int main()

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

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


/*Here we take two parameters, the beginning of the

array and the length n upto which we want the array to

be sorted*/

sort(arr, arr + n);

cout << "\nArray after sorting using "

"default sort is : \n";

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

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

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

// C++ program to demonstrate descending order sort using

// greater<>().

#include <bits/stdc++.h>

using namespace std;

int main()

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

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

sort(arr, arr + n, greater<int>());

cout << "Array after sorting : \n";

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

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

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

// C++ program to demonstrate sort()

#include <bits/stdc++.h>

using namespace std;

int main()

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

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


// Sort the elements which lies in the range of 2 to

// (n-1)

sort(arr + 2, arr + n);

cout << "Array after sorting : \n";

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

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

return 0;

// This code is contributed by Suruchi Kumari

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

// A C++ program to demonstrate

// STL sort() using

// our own comparator

#include <bits/stdc++.h>

using namespace std;

// An interval has a start

// time and end time

struct Interval {

int start, end;

};

// Compares two intervals

// according to starting times.

bool compareInterval(Interval i1, Interval i2)

return (i1.start < i2.start);


}

int main()

Interval arr[]

= { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };

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

// sort the intervals in increasing order of

// start time

sort(arr, arr + n, compareInterval);

cout << "Intervals sorted by start time : \n";

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

cout << "[" << arr[i].start << "," << arr[i].end

<< "] ";

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>

using namespace std;

template <class T>

class Comparator { // we pass an object of this class as

// third arg to sort function...

public:

bool operator()(T x1, T x2)

return x1 < x2;


}

};

template <class T> bool funComparator(T x1, T x2)

{ // return type is bool

return x1 <= x2;

void show(int a[], int array_size)

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

cout << a[i] << " ";

int main()

int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int asize = sizeof(a) / sizeof(int);

cout << "The array before sorting is : ";

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

sort(a, a + asize, greater<int>());

show(a, asize);

cout << endl

<< "The array after sorting is(asc but our "

"comparator class) :";

sort(a, a + asize, Comparator<int>());

show(a, asize);

cout << endl

<< "The array after sorting is(asc but our "

"comparator function) :";

sort(a, a + asize, funComparator<int>);

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

// C++ program to create an empty

// vector and push values one

// by one.
#include <iostream>

#include <vector>

using namespace std;

int main()

// Create an empty vector

vector<int> vect;

vect.push_back(10);

vect.push_back(20);

vect.push_back(30);

for (int x : vect)

cout << x << " ";

return 0;

}
Output
10 20 30
2. Specifying size and initializing all values:
 C++

// C++ program to create an empty

// vector and push values one

// by one.

#include <iostream>

#include <vector>

using namespace std;

int main()

int n = 3;

// Create a vector of size n with

// all values as 10.

vector<int> vect(n, 10);


for (int x : vect)

cout << x << " ";

return 0;

Output
10 10 10
3. Initializing like arrays:

 C++

// C++ program to initialize

// a vector like an array.

#include <iostream>

#include <vector>

using namespace std;

int main()

{
vector<int> vect{ 10, 20, 30 };

for (int x : vect)

cout << x << " ";

return 0;

Output
10 20 30
4. Initializing from an array:
 C++

// C++ program to initialize

// a vector from an array.

#include <iostream>

#include <vector>

using namespace std;

int main()
{

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

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

vector<int> vect(arr, arr + n);

for (int x : vect)

cout << x << " ";

return 0;

Output
10 20 30
5. Initializing from another vector:
 C++

// C++ program to initialize a vector from

// another vector.

#include <iostream>
#include <vector>

using namespace std;

int main()

vector<int> vect1{ 10, 20, 30 };

vector<int> vect2(vect1.begin(), vect1.end());

for (int x : vect2)

cout << x << " ";

return 0;

Output
10 20 30
6. Initializing all elements with a particular value:
 C++

// C++ Program to initialize vector using fill()


#include <iostream>

#include <vector>

using namespace std;

int main()

// creating array with size 10

vector<int> vect1(10);

// initializing using fill() function

int value = 5;

fill(vect1.begin(), vect1.end(), value);

// printing vector

for (int x : vect1)

cout << x << " ";


return 0;

Output
5 5 5 5 5 5 5 5 5 5
7. Initialize an array with consecutive numbers using std::iota:
 C++

// C++ program to initialize a

// vector with consecutive

// numbers

#include <iostream>

#include <numeric>

#include <vector>

using namespace std;

int main()

// declaring a vector with size 5

vector<int> vec(5);
// initializing using iota()

iota(vec.begin(), vec.end(), 1);

// printing the vector

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

cout << vec[i] << " ";

return 0;

Output
1 2 3 4 5

Ways to copy a vector in C++


Last Updated : 13 Jul, 2023



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

// C++ code to demonstrate copy of vector

// by iterative method.

#include<iostream>

#include<vector>

using namespace std;

int main()

// Initializing vector with values

vector<int> vect1{1, 2, 3, 4};

// Declaring new vector

vector<int> vect2;

// A loop to copy elements of

// old vector into new vector


// by Iterative method

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

vect2.push_back(vect1[i]);

cout << "Old vector elements are : ";

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

cout << vect1[i] << " ";

cout << endl;

cout << "New vector elements are : ";

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

cout << vect2[i] << " ";

cout<< endl;

// Changing value of vector to show that a new

// copy is created.

vect1[0] = 2;
cout << "The first element of old vector is :";

cout << vect1[0] << endl;

cout << "The first element of new vector is :";

cout << vect2[0] <<endl;

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

// C++ code to demonstrate copy of vector

// by iterative method.

#include<iostream>

#include<vector>
using namespace std;

int main()

// Initializing vector with values

vector<int> vect1{1, 2, 3, 4};

// Declaring new vector

vector<int> vect2;

// Using assignment operator to copy one

// vector to other

vect2 = vect1;

cout << "Old vector elements are : ";

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

cout << vect1[i] << " ";

cout << endl;


cout << "New vector elements are : ";

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

cout << vect2[i] << " ";

cout<< endl;

// Changing value of vector to show that a new

// copy is created.

vect1[0] = 2;

cout << "The first element of old vector is :";

cout << vect1[0] << endl;

cout << "The first element of new vector is :";

cout << vect2[0] <<endl;

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

// C++ code to demonstrate copy of vector

// by constructor method.

#include<bits/stdc++.h>

using namespace std;

int main()

// Initializing vector with values

vector<int> vect1{1, 2, 3, 4};

// Declaring new vector and copying

// element of old vector

// constructor method, Deep copy

vector<int> vect2(vect1);
cout << "Old vector elements are : ";

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

cout << vect1[i] << " ";

cout << endl;

cout << "New vector elements are : ";

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

cout << vect2[i] << " ";

cout<< endl;

// Changing value of vector to show that a new

// copy is created.

vect1[0] = 2;

cout << "The first element of old vector is :";

cout << vect1[0] << endl;

cout << "The first element of new vector is :";


cout << vect2[0] <<endl;

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

// C++ code to demonstrate copy of vector

// by assign() and copy().

#include<iostream>

#include<vector> // for vector

#include<algorithm> // for copy() and assign()

#include<iterator> // for back_inserter


using namespace std;

int main()

// Initializing vector with values

vector<int> vect1{1, 2, 3, 4};

// Declaring new vector

vector<int> vect2;

// Copying vector by copy function

copy(vect1.begin(), vect1.end(), back_inserter(vect2));

cout << "Old vector elements are : ";

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

cout << vect1[i] << " ";

cout << endl;

cout << "New vector elements are : ";


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

cout << vect2[i] << " ";

cout<< endl;

// Changing value of vector to show that a new

// copy is created.

vect1[0] = 2;

cout << "The first element of old vector is :";

cout << vect1[0] << endl;

cout << "The first element of new vector is :";

cout << vect2[0] <<endl;

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

// C++ code to demonstrate copy of vector

// by assign()

#include<iostream>

#include<vector> // for vector

#include<algorithm> // for copy() and assign()

#include<iterator> // for back_inserter

using namespace std;

int main()

// Initializing vector with values

vector<int> vect1{1, 2, 3, 4};

// Declaring another vector

vector<int> vect2;
// Copying vector by assign function

vect2.assign(vect1.begin(), vect1.end());

cout << "Old vector elements are : ";

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

cout << vect1[i] << " ";

cout << endl;

cout << "New vector elements are : ";

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

cout << vect2[i] << " ";

cout<< endl;

// Changing value of vector to show that a new

// copy is created.

vect1[0] = 2;
cout << "The first element of old vector is :";

cout << vect1[0] << endl;

cout << "The first element of new vector is :";

cout << vect2[0] <<endl;

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

// C++ code to demonstrate copy of vector

// by instert() function

#include<iostream>

#include<vector> // for vector


using namespace std;

int main()

// Initializing vector with values

vector<int> vect1{1, 2, 3, 4};

// Declaring new vector

vector<int> vect2;

// Copying vector by insert function

vect2.insert(vect2.begin(), vect1.begin(), vect1.end());

cout << "Old vector elements are : ";

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

cout << vect1[i] << " ";

cout << endl;


cout << "New vector elements are : ";

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

cout << vect2[i] << " ";

cout<< endl;

// Changing value of vector to show that a new

// copy is created.

vect1[0] = 2;

cout << "The first element of old vector is :";

cout << vect1[0] << endl;

cout << "The first element of new vector is :";

cout << vect2[0] <<endl;

return 0;

//This code is contributed by Susobhan AKhuli

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

Merge operations using STL in C++ | merge(),


includes(), set_union(), set_intersection(),
set_difference(), ., inplace_merge,
Last Updated : 30 Jun, 2023



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

// C++ code to demonstrate the working of

// merge() and include()

#include<iostream>

#include<algorithm> // merge operations


#include<vector> // for vector

using namespace std;

int main()

// Initializing 1st vector

vector<int> v1 = {1, 3, 4, 5, 20, 30};

// Initializing 2nd vector

vector<int> v2 = {1, 5, 6, 7, 25, 30};

// Declaring resultant vector

// for merging

vector<int> v3(12);

// Using merge() to merge vectors v1 and v2

// and storing result in v3

merge(v1.begin(), v1.end(), v2.begin(),

v2.end(), v3.begin());
// Displaying resultant container

cout << "The new container after merging is :\n";

for (int &x : v3)

cout << x << " ";

cout << endl;

// Initializing new vector

vector<int> v4 = {1, 3, 4, 5, 6, 20, 25, 30};

// Using include() to check if v4 contains v1

includes(v4.begin(), v4.end(), v1.begin(), v1.end())?

cout << "v4 includes v1":

cout << "v4 does'nt include v1";

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ code to demonstrate the working of

// inplace_merge()

#include<iostream>

#include<algorithm> // merge operations

#include<vector> // for vector

using namespace std;

int main()

// Initializing 1st vector


vector<int> v1 = {1, 3, 4, 5, 20, 30};

// Initializing 2nd vector

vector<int> v2 = {1, 5, 6, 7, 25, 30};

// Declaring resultant vector

// for inplace_merge()

vector<int> v3(12);

// using copy to copy both vectors into

// one container

auto it = copy(v1.begin(), v1.end(), v3.begin());

copy(v2.begin(), v2.end(), it);

// Using inplace_merge() to sort the container

inplace_merge(v3.begin(),it,v3.end());

// Displaying resultant container


cout << "The new container after inplace_merging is :\n";

for (int &x : v3)

cout << x << " ";

cout << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// set_union() and set_intersection()

#include<iostream>

#include<algorithm> // for merge operations

#include<vector> // for vector

using namespace std;

int main()

// Initializing 1st vector

vector<int> v1 = {1, 3, 4, 5, 20, 30};

// Initializing 2nd vector

vector<int> v2 = {1, 5, 6, 7, 25, 30};

// Declaring resultant vector

// for union

vector<int> v3(10);
// Declaring resultant vector

// for intersection

vector<int> v4(10);

// using set_union() to compute union of 2

// containers v1 and v2 and store result in v3

auto it = set_union(v1.begin(), v1.end(), v2.begin(),

v2.end(), v3.begin());

// using set_intersection() to compute intersection

// of 2 containers v1 and v2 and store result in v4

auto it1 = set_intersection(v1.begin(),v1.end(),

v2.begin(), v2.end(), v4.begin());

// resizing new container

v3.resize(it - v3.begin());

// resizing new container


v4.resize(it1 - v4.begin());

// Displaying set union

cout << "Union of two containers is : ";

for (int &x : v3)

cout << x << " ";

cout << endl;

// Displaying set intersection

cout << "Intersection of two containers is : ";

for (int &x : v4)

cout << x << " ";

cout << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ code to demonstrate the working of

// set_difference() and set_symmetric_difference()

#include<iostream>

#include<algorithm> // for merge operations

#include<vector> // for vector

using namespace std;

int main()

// Initializing 1st vector

vector<int> v1 = {1, 3, 4, 5, 20, 30};


// Initializing 2nd vector

vector<int> v2 = {1, 5, 6, 7, 25, 30};

// Declaring resultant vector

// for difference

vector<int> v3(10);

// Declaring resultant vector

// for symmetric_difference

vector<int> v4(10);

// using set_difference() to compute difference

// of 2 containers v1 and v2.

auto it = set_difference(v1.begin(), v1.end(),

v2.begin(), v2.end(), v3.begin());

// using set_symmetric_difference() to compute


// symmetric_difference/ of 2 containers

auto it1 = set_symmetric_difference(v1.begin(),

v1.end(), v2.begin(), v2.end(), v4.begin());

// resizing new container

v3.resize(it - v3.begin());

// resizing new container

v4.resize(it1 - v4.begin());

// Displaying set difference

cout << "Difference of two containers is : ";

for (int &x : v3)

cout << x << " ";

cout << endl;

// Displaying set symmetric_difference

cout << "symmetric_difference of two containers is : ";


for (int &x : v4)

cout << x << " ";

cout << endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// A C++ code to add two arrays


#include <bits/stdc++.h>

using namespace std;

int main()

int arr1[] = {1, 2, 3};

int arr2[] = {4, 5, 6};

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

int res[n];

// Code to add two arrays

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

res[i] = arr1[i] + arr2[i];

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

cout << res[i] << " ";

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

// Using transform() in STL to add two arrays

#include <bits/stdc++.h>

using namespace std;

int main()

int arr1[] = {1, 2, 3};

int arr2[] = {4, 5, 6};

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

int res[n];

// Single line code to add arr1[] and arr2[] and

// store result in res[]

transform(arr1, arr1+n, arr2, res, plus<int>());


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

cout << res[i] << " ";

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

// C++ program to demonstrate working of

// transform with unary operator.

#include <bits/stdc++.h>

using namespace std;

int increment(int x) { return (x+1); }


int main()

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

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

// Apply increment to all elements of

// arr[] and store the modified elements

// back in arr[]

transform(arr, arr+n, arr, increment);

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

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

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.

// vect is a vector of integers.


transform(vect.begin(), vect.end(),
vect.begin(), increment);

Deque in C++ Standard Template Library (STL)


Last Updated : 20 Jun, 2023



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

// CPP Program to implement Deque in STL


#include <deque>

#include <iostream>

using namespace std;

void showdq(deque<int> g)

deque<int>::iterator it;

for (it = g.begin(); it != g.end(); ++it)

cout << '\t' << *it;

cout << '\n';

int main()

deque<int> gquiz;

gquiz.push_back(10);

gquiz.push_front(20);
gquiz.push_back(30);

gquiz.push_front(15);

cout << "The deque gquiz is : ";

showdq(gquiz);

cout << "\ngquiz.size() : " << gquiz.size();

cout << "\ngquiz.max_size() : " << gquiz.max_size();

cout << "\ngquiz.at(2) : " << gquiz.at(2);

cout << "\ngquiz.front() : " << gquiz.front();

cout << "\ngquiz.back() : " << gquiz.back();

cout << "\ngquiz.pop_front() : ";

gquiz.pop_front();

showdq(gquiz);

cout << "\ngquiz.pop_back() : ";

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

Inserts an element. And returns an iterator that points to


deque::insert()
the first of the newly inserted elements.

deque::rbegin() Returns a reverse iterator which points to the last element


Method Definition

of the deque (i.e., its reverse beginning).

Returns a reverse iterator which points to the position


deque::rend() before the beginning of the deque (which is considered its
reverse end).

Returns a constant iterator pointing to the first element of


deque::cbegin() the container, that is, the iterator cannot be used to
modify, only traverse the deque.

Returns the maximum number of elements that a deque


deque::max_size()
container can hold.

deque::assign() Assign values to the same or different deque container.

deque::resize() Function which changes the size of the deque.

deque::push_front() It is used to push elements into a deque from the front.

This function is used to push elements into a deque from


deque::push_back()
the back.

pop_front() function is used to pop or remove elements


deque::pop_front() and
from a deque from the front. pop_back() function is used
deque::pop_back()
to pop or remove elements from a deque from the back.
Method Definition

front() function is used to reference the first element of


deque::front() and
the deque container. back() function is used to reference
deque::back()
the last element of the deque container.

clear() function is used to remove all the elements of the


deque::clear() and deque container, thus making its size 0. erase() function is
deque::erase() used to remove elements from a container from the
specified position or range.

empty() function is used to check if the deque container is


deque::empty() and empty or not. size() function is used to return the size of
deque::size() the deque container or the number of elements in the
deque container.

operator= operator is used to assign new contents to the


deque::operator= and container by replacing the existing contents. operator[]
deque::operator[] operator is used to reference the element present at
position given inside the operator.

at() function is used reference the element present at the


deque::at() and position given as the parameter to the function. swap()
deque::swap() function is used to swap the contents of one deque with
another deque of same type and size.

begin() function is used to return an iterator pointing to


deque::begin() and the first element of the deque container. end() function is
deque::end() used to return an iterator pointing to the last element of
the deque container.
Method Definition

emplace_front() function is used to insert a new element


into the deque container. The new element is added to the
deque::emplace_front() and
beginning of the deque. emplace_back() function is used to
deque::emplace_back()
insert a new element into the deque container. The new
element is added to the end of the deque.

Priority Queue in C++ Standard Template


Library (STL)
Last Updated : 09 Oct, 2023



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

// C++ program to demonstrate the use of priority_queue

#include <iostream>

#include <queue>
using namespace std;

// driver code

int main()

int arr[6] = { 10, 2, 4, 8, 6, 9 };

// defining priority queue

priority_queue<int> pq;

// printing array

cout << "Array: ";

for (auto i : arr) {

cout << i << ' ';

cout << endl;

// pushing array sequentially one by one

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


pq.push(arr[i]);

// printing priority queue

cout << "Priority Queue: ";

while (!pq.empty()) {

cout << pq.top() << ' ';

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)

How to create a min heap for the priority queue?


As we saw earlier, a priority queue is implemented as max heap by default in C++
but, it also provides us an option to change it to min heap by passing another
parameter while creating a priority queue.
Syntax:
priority_queue <int, vector<int>, greater<int>> gq;
where,
 ‘int’ is the type of elements you want to store in the priority queue. In this case,
it’s an integer. You can replace int with any other data type you need.
 ‘vector<int>’ is the type of internal container used to store these
elements. std::priority_queue is not a container in itself but a container adopter. It
wraps other containers. In this example, we’re using a vector, but you could
choose a different container that supports front(), push_back(), and pop_back()
methods.
 ‘greater<int>‘ is a custom comparison function. This determines how the
elements are ordered within the priority queue. In this specific example,
greater<int> sets up a min-heap. It means that the smallest element will be at the
top of the queue.
In the case of max heap, we didn’t have to specify them as the default values for these
are already suitable for max heap.
Example:
 C++

// C++ program to demonstrate

// min heap for priority queue

#include <iostream>

#include <queue>

using namespace std;

void showpq(

priority_queue<int, vector<int>, greater<int> > g)

while (!g.empty()) {

cout << ' ' << g.top();

g.pop();

}
cout << '\n';

void showArray(int* arr, int n)

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

cout << arr[i] << ' ';

cout << endl;

// Driver Code

int main()

int arr[6] = { 10, 2, 4, 8, 6, 9 };

priority_queue<int, vector<int>, greater<int> > gquiz(

arr, arr + 6);


cout << "Array: ";

showArray(arr, 6);

cout << "Priority Queue : ";

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

priority_queue::empty() Returns whether the queue is empty.

priority_queue::size() Returns the size of the queue.


Method Definition

priority_queue::top() Returns a reference to the topmost element of the queue.

priority_queue::push() Adds the element ‘g’ at the end of the queue.

priority_queue::pop() Deletes the first element of the queue.

Used to swap the contents of two queues provided the


priority_queue::swap()
queues must be of the same type, although sizes may differ.

Used to insert a new element into the priority queue


priority_queue::emplace()
container.

Represents the type of object stored as an element in a


priority_queue
priority_queue. It acts as a synonym for the template
value_type
parameter.

Operations on Priority Queue in C++


1. Inserting and Removing Elements of a Priority Queue

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

// method/function in Priority Queue

#include <iostream>

#include <queue>

using namespace std;

// Implementation of priority queue

void showpq(priority_queue<int> gq)

priority_queue<int> g = gq;

while (!g.empty()) {

cout << ' ' << g.top();

g.pop();

cout << '\n';

// Driver Code
int main()

priority_queue<int> gquiz;

// used in inserting the element

gquiz.push(10);

gquiz.push(30);

gquiz.push(20);

gquiz.push(5);

gquiz.push(1);

cout << "The priority queue gquiz is : ";

// used for highlighting the element

showpq(gquiz);

// used for identifying the size

// of the priority queue

cout << "\ngquiz.size() : " <<


gquiz.size();

// used for telling the top element

// in priority queue

cout << "\ngquiz.top() : " <<

gquiz.top();

// used for popping the element

// from a priority queue

cout << "\ngquiz.pop() : ";

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.

2. To Access the Top Element of the Priority Queue

The top element of the Priority Queue could be accessed using the top() method.
 C++

// C++ program to access the top

// element of priority queue

#include <iostream>

#include <queue>

using namespace std;

// Driver code

int main()

// create a priority queue of int

priority_queue<int> numbers;

// add items to priority_queue

numbers.push(1);
numbers.push(20);

numbers.push(7);

// get the element at the top

cout << "Top element: " <<

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.

3. To Check whether the Priority Queue is Empty or Not:

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

// C++ program to demonstrate


// Implementation of empty() function

#include <iostream>

#include <queue>

using namespace std;

// Driver code

int main()

priority_queue<int> pqueueGFG;

pqueueGFG.push(1);

// Priority Queue becomes 1

// check if it is empty or not

if (pqueueGFG.empty())

cout << "Empty or true";

else
{

cout << "Contains element or False";

return 0;

Output
Contains element or False
Refer end for complexity analysis.

4. To Get/Check the Size of the Priority Queue

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

// C++ program to demonstrate the

// size() method of priority queue

#include <iostream>

#include <queue>

using namespace std;


// Driver code

int main()

// create a priority queue of string

priority_queue<string> pqueue;

// add items to priority_queue

pqueue.push("Geeks");

pqueue.push("for");

pqueue.push("Geeks");

pqueue.push("C++");

// get the size of queue

int size = pqueue.size();

cout << "Size of the queue: " << size;

return 0;

Output
Size of the queue: 4
Refer end for complexity analysis.

5. To Swap Contents of a Priority Queue with Another of Similar Type

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

// CPP program to illustrate

// Implementation of swap() function

#include <bits/stdc++.h>

using namespace std;

// Print elements of priority queue

void print(priority_queue<int> pq)

while (!pq.empty()) {

cout << pq.top() << " ";

pq.pop();
}

cout << endl;

int main()

// priority_queue container declaration

priority_queue<int> pq1;

priority_queue<int> pq2;

// pushing elements into the 1st priority queue

pq1.push(1);

pq1.push(2);

pq1.push(3);

pq1.push(4);

// pushing elements into the 2nd priority queue

pq2.push(3);
pq2.push(5);

pq2.push(7);

pq2.push(9);

cout << "Before swapping:-" << endl;

cout << "Priority Queue 1 = ";

print(pq1);

cout << "Priority Queue 2 = ";

print(pq2);

// using swap() function to swap elements of priority

// queues

pq1.swap(pq2);

cout << endl << "After swapping:-" << endl;

cout << "Priority Queue 1 = ";

print(pq1);

cout << "Priority Queue 2 = ";


print(pq2);

return 0;

// This code is contributed by Susobhan Akhuli

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.

6. To emplace a new element into the priority queue container

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

// CPP program to illustrate


// Implementation of emplace() function

#include <bits/stdc++.h>

using namespace std;

int main()

priority_queue<int> pq;

pq.emplace(1);

pq.emplace(2);

pq.emplace(3);

pq.emplace(4);

pq.emplace(5);

pq.emplace(6);

// Priority queue becomes 1, 2, 3, 4, 5, 6

// Printing the priority queue


cout << "Priority Queue = ";

while (!pq.empty()) {

cout << pq.top() << " ";

pq.pop();

return 0;

// This code is contributed by Susobhan Akhuli

Output
Priority Queue = 6 5 4 3 2 1
Refer end for complexity analysis.

7. To represent the type of object stored as an element in a priority_queue

The priority_queue :: value_type method is a built-in function in C++ STL which


represents the type of object stored as an element in a priority_queue. It acts as a
synonym for the template parameter.
Syntax:
priority_queue::value_type variable_name
Below is the C++ program to represent the type of object stored as an element in a
priority_queue:

 C++
// C++ program to illustrate the

// priority_queue :: value_type function

#include <bits/stdc++.h>

using namespace std;

// Driver code

int main()

// declare integer value_type for priority queue

priority_queue<int>::value_type AnInt;

// declare string value_type for priority queue

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

cout << "Top element of the integer priority_queue is: "

<< q1.top() << endl;

// here AString acts as a variable of string data type

AString = "geek";

cout << endl

<< "The value_type is AString = " << AString

<< endl;

q2.push(AString);

AString = "for";

q2.push(AString);
AString = "geeks";

q2.push(AString);

cout << "Top element of the string priority_queue is: "

<< q2.top() << endl;

return 0;

// This code is contributed by Susobhan Akhuli

Output
The value_type is AnInt = 20
Top element of the integer priority_queue is: 30

The value_type is AString = geek


Top element of the string priority_queue is: geeks
Refer end for complexity analysis.
Complexities Of All The Operations:

Methods Time Complexity Auxiliary Space

priority_queue::empty() O(1) O(1)

priority_queue::size() O(1) O(1)

priority_queue::top() O(1) O(1)

priority_queue::push() O(logN) O(1)

priority_queue::pop() O(logN) O(1)

priority_queue::swap() O(1) O(N)

priority_queue::emplace() O(logN) O(1)

priority_queue
value_type O(1) O(1)

Map in C++ Standard Template Library (STL)


Last Updated : 30 Oct, 2023



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

// C++ program to illustrate the begin and end iterator

#include <iostream>

#include <map>

#include <string>

using namespace std;

int main()

// Create a map of strings to integers


map<string, int> mp;

// Insert some values into the map

mp["one"] = 1;

mp["two"] = 2;

mp["three"] = 3;

// Get an iterator pointing to the first element in the

// map

map<string, int>::iterator it = mp.begin();

// Iterate through the map and print the elements

while (it != mp.end()) {

cout << "Key: " << it->first

<< ", Value: " << it->second << endl;

++it;

}
return 0;

Output
Key: one, Value: 1
Key: three, Value: 3
Key: two, Value: 2

Complexity of the above method:


Time complexity: O(n) where n is the size of map.
Auxiliary Space: O(n)
Example 2: size() function
 C++

// C++ program to illustrate the size() function

#include <iostream>

#include <map>

#include <string>

using namespace std;

int main()

// Create a map of strings to integers


map<string, int> map;

// Insert some values into the map

map["one"] = 1;

map["two"] = 2;

map["three"] = 3;

// Print the size of the map

cout << "Size of map: " << map.size() << endl;

return 0;

Output
Size of map: 3

Complexity of the above method:


Time complexity: O(1).
Example 3: Implementing Map
 CPP

// CPP Program to demonstrate the implementation in Map


// divyansh mishra --> divyanshmishra101010

#include <iostream>

#include <iterator>

#include <map>

using namespace std;

int main()

// empty map container

map<int, int> gquiz1;

// insert elements in random order

gquiz1.insert(pair<int, int>(1, 40));

gquiz1.insert(pair<int, int>(2, 30));

gquiz1.insert(pair<int, int>(3, 60));

gquiz1.insert(pair<int, int>(4, 20));


gquiz1.insert(pair<int, int>(5, 50));

gquiz1.insert(pair<int, int>(6, 50));

// another way of inserting a value in a map

gquiz1[7] = 10;

// printing map gquiz1

map<int, int>::iterator itr;

cout << "\nThe map gquiz1 is : \n";

cout << "\tKEY\tELEMENT\n";

for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) {

cout << '\t' << itr->first << '\t' << itr->second

<< '\n';

cout << endl;

// assigning the elements from gquiz1 to gquiz2

map<int, int> gquiz2(gquiz1.begin(), gquiz1.end());


// print all elements of the map gquiz2

cout << "\nThe map gquiz2 after"

<< " assign from gquiz1 is : \n";

cout << "\tKEY\tELEMENT\n";

for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) {

cout << '\t' << itr->first << '\t' << itr->second

<< '\n';

cout << endl;

// remove all elements up to

// element with key=3 in gquiz2

cout << "\ngquiz2 after removal of"

" elements less than key=3 : \n";

cout << "\tKEY\tELEMENT\n";

gquiz2.erase(gquiz2.begin(), gquiz2.find(3));

for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) {


cout << '\t' << itr->first << '\t' << itr->second

<< '\n';

// remove all elements with key = 4

int num;

num = gquiz2.erase(4);

cout << "\ngquiz2.erase(4) : ";

cout << num << " removed \n";

cout << "\tKEY\tELEMENT\n";

for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) {

cout << '\t' << itr->first << '\t' << itr->second

<< '\n';

cout << endl;

// lower bound and upper bound for map gquiz1 key = 5


cout << "gquiz1.lower_bound(5) : "

<< "\tKEY = ";

cout << gquiz1.lower_bound(5)->first << '\t';

cout << "\tELEMENT = " << gquiz1.lower_bound(5)->second

<< endl;

cout << "gquiz1.upper_bound(5) : "

<< "\tKEY = ";

cout << gquiz1.upper_bound(5)->first << '\t';

cout << "\tELEMENT = " << gquiz1.upper_bound(5)->second

<< endl;

return 0;

Output
The map gquiz1 is :
KEY ELEMENT
1 40
2 30
3 60
4 20
5 50
6 50
7 10

The map gquiz2 after assign from gquiz1 is :


KEY ELEMENT
1 40
2 30
3 60
4 20
5 50
6 50
7 10

gquiz2 after remov...


Complexity of the above method:
Time complexity: O(n log(n)) as n is size of the map
Auxiliary space: O(n)
Example 4: Implementing Map of Integers
 C++

// C++ program to implement map container

#include <iostream>

#include <map>

#include <string>
using namespace std;

int main()

// Create a map of strings to integers

map<string, int> map;

// Insert some values into the map

map["one"] = 1;

map["two"] = 2;

map["three"] = 3;

// Print the values in the map

cout << "Key: one, Value: " << map["one"] << endl;

cout << "Key: two, Value: " << map["two"] << endl;

cout << "Key: three, Value: " << map["three"] << endl;

// Check if a key is in the map


if (map.count("four") > 0) {

cout << "Key 'four' is in the map" << endl;

else {

cout << "Key 'four' is not in the map" << endl;

return 0;

Output
Key: one, Value: 1
Key: two, Value: 2
Key: three, Value: 3
Key 'four' is not in the map

List of all Functions of std::map


The following table contains all the functions defined inside std::map class.
Function Definition

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

Returns an iterator of pairs. The pair refers to the bounds of a range


map equal_range() that includes all the elements in the container which have a key
equivalent to k.

map erase() Used to erase elements from the container –> O(log n)

Returns a reverse iterator pointing to the theoretical element right


map rend() before the first key-value pair in the map(which is considered its
reverse end).

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.

crbegin() returns a constant reverse iterator referring to the last


map crbegin() and
element in the map container. crend() returns a constant reverse
crend() iterator pointing to the theoretical element before the first element in
the map.

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 Returns an iterator to the first element that is equivalent to mapped


upper_bound() value with key-value ‘g’ or definitely will go after the element with
key-value ‘g’ in the map
Function Definition

map operator= Assigns contents of a container to a different container, replacing its


current content.

map Returns an iterator to the first element that is equivalent to the


lower_bound() mapped value with key-value ‘g’ or definitely will not go before the
element with key-value ‘g’ in the map –> O(log n)

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::size() Returns the number of elements in the map.

map::empty() Returns whether the map is empty

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::clear() Removes all the elements from the map.

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 in C++ Standard Template Library (STL)


Last Updated : 12 Jul, 2023



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

// CPP program to illustrate Pair in STL

#include <iostream>

#include <utility>

using namespace std;


// Driver Code

int main()

// defining a pair

pair<int, char> PAIR1;

// first part of the pair

PAIR1.first = 100;

// second part of the pair

PAIR1.second = 'G';

cout << PAIR1.first << " ";

cout << PAIR1.second << endl;

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

// CPP program to illustrate

// Initializing of pair STL

#include <iostream>

#include <utility>

using namespace std;

// Driver Code

int main()

// defining a pair

pair<string, double> PAIR2("GeeksForGeeks", 1.23);


cout << PAIR2.first << " ";

cout << PAIR2.second << endl;

return 0;

Output
GeeksForGeeks 1.23
Note: If not initialized, the first value of the pair gets automatically initialized.
 C++

// CPP program to illustrate

// auto-initializing of pair STL

#include <iostream>

#include <utility>

using namespace std;

int main()
{

pair<int, double> PAIR1;

pair<string, char> PAIR2;

// it is initialised to 0

cout << PAIR1.first;

// it is initialised to 0

cout << PAIR1.second;

cout << " ";

// // it prints nothing i.e NULL

cout << PAIR2.first;

// it prints nothing i.e NULL

cout << PAIR2.second;


return 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

// CPP Program to demonstrate make_pair()

// function in pair

#include <iostream>

#include <utility>

using namespace std;

// Driver Code

int main()

pair<int, char> PAIR1;


pair<string, double> PAIR2("GeeksForGeeks", 1.23);

pair<string, double> PAIR3;

PAIR1.first = 100;

PAIR1.second = 'G';

PAIR3 = make_pair("GeeksForGeeks is Best", 4.56);

cout << PAIR1.first << " ";

cout << PAIR1.second << endl;

cout << PAIR2.first << " ";

cout << PAIR2.second << endl;

cout << PAIR3.first << " ";

cout << PAIR3.second << endl;

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

// CPP Program to demonstrate swap()

// function in pair

#include <iostream>

#include <utility>

using namespace std;

// Driver Code

int main()
{

pair<char, int> pair1 = make_pair('A', 1);

pair<char, int> pair2 = make_pair('B', 2);

cout << "Before swapping:\n ";

cout << "Contents of pair1 = " << pair1.first << " "

<< pair1.second;

cout << "Contents of pair2 = " << pair2.first << " "

<< pair2.second;

pair1.swap(pair2);

cout << "\nAfter swapping:\n ";

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

// CPP code to illustrate tie() in Pair

#include <bits/stdc++.h>

using namespace std;

// Driver Code

int main()

{
pair<int, int> pair1 = { 1, 2 };

int a, b;

tie(a, b) = pair1;

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

pair<int, int> pair2 = { 3, 4 };

tie(a, ignore) = pair2;

// prints old value of b

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

// Illustrating pair of pairs

pair<int, pair<int, char> > pair3 = { 3, { 4, 'a' } };

int x, y;

char z;

// tie(x,y,z) = pair3; Gives compilation error

// tie(x, tie(y,z)) = pair3; Gives compilation error


// Each pair needs to be explicitly handled

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

// CPP program to illustrate pair in STL

#include <iostream>

#include <string>

#include <utility>

using namespace std;


int main()

pair<string, int> g1;

pair<string, int> g2("Quiz", 3);

pair<string, int> g3(g2);

pair<int, int> g4(5, 10);

g1 = make_pair(string("Geeks"), 1);

g2.first = ".com";

g2.second = 2;

cout << "This is pair g" << g1.second << " with "

<< "value " << g1.first << "." << endl

<< endl;

cout << "This is pair g" << g3.second << " with value "

<< g3.first

<< "This pair was initialized as a copy of "


<< "pair g2" << endl

<< endl;

cout << "This is pair g" << g2.second << " with value "

<< g2.first << "\nThe values of this pair were"

<< " changed after initialization." << endl

<< endl;

cout << "This is pair g4 with values " << g4.first

<< " and " << g4.second

<< " made for showing addition. \nThe "

<< "sum of the values in this pair is "

<< g4.first + g4.second << "." << endl

<< endl;

cout << "We can concatenate the values of"

<< " the pairs g1, g2 and g3 : "

<< g1.first + g3.first + g2.first << endl


<< endl;

cout << "We can also swap pairs "

<< "(but type of pairs should be same) : " << endl;

cout << "Before swapping, "

<< "g1 has " << g1.first << " and g2 has "

<< g2.first << endl;

swap(g1, g2);

cout << "After swapping, "

<< "g1 has " << g1.first << " and g2 has "

<< g2.first;

return 0;

Output
This is pair g1 with value Geeks.

This is pair g3 with value QuizThis pair was initialized as a copy of


pair g2

This is pair g2 with value .com


The values of this pair were changed after initialization.

This is pair g4 with values 5 and 10 made for showing addition.


The sum of the values in this pair is 15.

We can concatenate the values of the pairs g1, g2 and g3 :


GeeksQuiz.com

We can also swap pairs (but type of pairs should be same) :


Before swapping, g1 has Geeks and g2 has .com
After swapping, g1 has .com and g2 has Geeks
Time complexity: O(1).
Auxiliary space: O(1).

operators(=, ==, !=, >=, <=) in Pair

We can use operators with pairs as well.


1) using equal(=): It assigns a new object for a pair object. Syntax:
pair& operator= (const pair& pr);
This Assigns “pr” as the new content for the “pair” object. The first value is assigned
the first value of pr and the second value is assigned the second value of pr.
2) Comparison (==) operator with pair: For the two given pairs say pair1 and pair2,
the comparison operator compares the “first value and second value of those two pairs
i.e. if pair1.first is equal to pair2.first or not” and “if pair1.second is equal to
pair2.second or not”.
i.e if ( (pari1.first ==pair2.first) && (pair1.second==pair2.second) )
If any of the two conditions is false then it returns false otherwise true.
3) Not equal (!=) operator with pair: For the given two pairs say pair1 and pair2, the
!= operator compares the first values of those two pairs i.e. if pair1.first is equal to
pair2.first or not, if they are equal then it checks the second values of both.
4) Logical( >=, <= )operators with pair: For the given two pairs say pair1 and pair2,
the =, >, can be used with pairs as well. It returns 0 or 1 by only comparing the first
value of the pair. For pairs like p1=(1,20) and p2=(1,10) p2<p1 should give 0 (as it
compares 1st element only & they are equal so it is definitely not less), but that isn’t
true. Here the pair compares the second element and if it satisfies then returns 1 (this
is only the case when the first element gets equal while using a relational operator > or
< only, otherwise these operators work as mentioned above)
&list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB

Multiset in C++ Standard Template Library


(STL)
Last Updated : 02 Jan, 2023



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

// CPP Program to demonstrate the

// implementation of multiset

#include <iostream>

#include <iterator>

#include <set>
using namespace std;

int main()

// empty multiset container

multiset<int, greater<int> > gquiz1;

// insert elements in random order

gquiz1.insert(40);

gquiz1.insert(30);

gquiz1.insert(60);

gquiz1.insert(20);

gquiz1.insert(50);

// 50 will be added again to

// the multiset unlike set

gquiz1.insert(50);
gquiz1.insert(10);

// printing multiset gquiz1

multiset<int, greater<int> >::iterator itr;

cout << "\nThe multiset gquiz1 is : \n";

for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) {

cout << *itr << " ";

cout << endl;

// assigning the elements from gquiz1 to gquiz2

multiset<int> gquiz2(gquiz1.begin(), gquiz1.end());

// print all elements of the multiset gquiz2

cout << "\nThe multiset gquiz2 \n"

"after assign from gquiz1 is : \n";

for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) {

cout << *itr << " ";


}

cout << endl;

// remove all elements up to element

// with value 30 in gquiz2

cout << "\ngquiz2 after removal \n"

"of elements less than 30 : \n";

gquiz2.erase(gquiz2.begin(), gquiz2.find(30));

for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) {

cout << *itr << " ";

// remove all elements with value 50 in gquiz2

int num;

num = gquiz2.erase(50);

cout << "\ngquiz2.erase(50) : \n";

cout << num << " removed \n";

for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) {


cout << *itr << " ";

cout << endl;

// lower bound and upper bound for multiset gquiz1

cout << "\ngquiz1.lower_bound(40) : \n"

<< *gquiz1.lower_bound(40) << endl;

cout << "gquiz1.upper_bound(40) : \n"

<< *gquiz1.upper_bound(40) << endl;

// lower bound and upper bound for multiset gquiz2

cout << "gquiz2.lower_bound(40) : \n"

<< *gquiz2.lower_bound(40) << endl;

cout << "gquiz2.upper_bound(40) : \n"

<< *gquiz2.upper_bound(40) << endl;

return 0;
}

Output
The multiset gquiz1 is :
60 50 50 40 30 20 10

The multiset gquiz2


after assign from gquiz1 is :
10 20 30 40 50 50 60

gquiz2 after removal


of elements less than 30 :
30 40 50 50 60
gquiz2.erase(50) :
2 removed
30 40 60

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

// CPP Code to remove an element from multiset which have

// same value

#include <bits/stdc++.h>

using namespace std;

int main()

multiset<int> a;

a.insert(10);

a.insert(10);

a.insert(10);

// it will give output 3

cout << a.count(10) << endl;


// removing single instance from multiset

// it will remove only one value of

// 10 from multiset

a.erase(a.find(10));

// it will give output 2

cout << a.count(10) << endl;

// removing all instance of element from multiset

// it will remove all instance of value 10

a.erase(10);

// it will give output 0 because all

// instance of value is removed from

// multiset

cout << a.count(10) << endl;


return 0;

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

List of Functions of Multiset

Function Definition

begin() Returns an iterator to the first element in the multiset.

Returns an iterator to the theoretical element that follows


end()
the last element in the multiset.

size() Returns the number of elements in the multiset.

Returns the maximum number of elements that the


max_size()
multiset can hold.

empty() Returns whether the multiset is empty.


Function Definition

pair insert(const g) Adds a new element ‘g’ to the multiset.

iterator insert (iterator Adds a new element ‘g’ at the position pointed by the
position,const g) iterator.

Removes the element at the position pointed by the


erase(iterator position)
iterator.

erase(const g) Removes the value ‘g’ from the multiset.

clear() Removes all the elements from the multiset.

Returns the object that determines how the elements in


key_comp() / value_comp()
the multiset are ordered (‘<‘ by default).

Returns an iterator to the element ‘g’ in the multiset if


find(const g)
found, else returns the iterator to end.

Returns the number of matches to element ‘g’ in the


count(const g)
multiset.

Returns an iterator to the first element that is equivalent


lower_bound(const g) to ‘g’ or definitely will not go before the element ‘g’ in the
multiset if found, else returns the iterator to end.

upper_bound(const g) Returns an iterator to the first element that will go after


Function Definition

the element ‘g’ in the multiset.

This function is used to exchange the contents of two


multiset::swap() multisets but the sets must be of the same type, although
sizes may differ.

This operator is used to assign new contents to the


multiset::operator=
container by replacing the existing contents.

This function is used to insert a new element into the


multiset::emplace()
multiset container.

Returns an iterator of pairs. The pair refers to the range


multiset equal_range() that includes all the elements in the container which have
a key equivalent to k.

multiset::emplace_hint() Inserts a new element in the multiset.

Returns a reverse iterator pointing to the last element in


multiset::rbegin()
the multiset container.

Returns a reverse iterator pointing to the theoretical


multiset::rend() element right before the first element in the multiset
container.

multiset::cbegin() Returns a constant iterator pointing to the first element in


Function Definition

the container.

Returns a constant iterator pointing to the position past


multiset::cend()
the last element in the container.

Returns a constant reverse iterator pointing to the last


multiset::crbegin()
element in the container.

Returns a constant reverse iterator pointing to the


multiset::crend()
position just before the first element in the container.

Returns a copy of the allocator object associated with the


multiset::get_allocator()
multiset.

How to reverse a Vector using STL in C++?


Last Updated : 21 Sep, 2023



Given a vector, reverse this vector using STL in C++.


Example:
Input: vec = {1, 45, 54, 71, 76, 12}
Output: {12, 76, 71, 54, 45, 1}
Input: vec = {1, 7, 5, 4, 6, 12}
Output: {12, 6, 4, 5, 7, 1}
Approach: Reversing can be done with the help of reverse() function provided in
STL. The Time complexity of the reverse() is O(n) where n is the length of the string.
Syntax:
reverse(start_iterator, end_iterator);
Example:
 CPP

// C++ program to reverse Vector

// using reverse() in STL

#include <bits/stdc++.h>

using namespace std;

int main()

// Get the vector

vector<int> a = { 1, 45, 54, 71, 76, 12 };

// Print the vector

cout << "Vector: ";

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

cout << a[i] << " ";

cout << endl;


// Reverse the vector

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

// Print the reversed vector

cout << "Reversed Vector: ";

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

cout << a[i] << " ";

cout << endl;

return 0;

Output
Vector: 1 45 54 71 76 12
Reversed Vector: 12 76 71 54 45 1

How to reverse an Array using STL in C++?


Last Updated : 28 Jul, 2022



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}

Input: arr[] = {1, 7, 5, 4, 6, 12}


Output: {12, 6, 4, 5, 7, 1}
Approach: Reversing can be done with the help of reverse() function provided in
STL. Syntax:
reverse(start_index, index_next_to_last_index);

For example to reverse an array arr[] of size 'n' we need to write as


follows:
reverse(arr, arr+n);
if we observe it is reverse(arr+0, arr+n);
which means, the reverse function reverse the elements in an array
from index-0 to index-(n-1)

Ex: Given an array arr of size 7


reverse(arr, arr+5);
The above reverse function reverses the elements in an array from
index-0 to index-4

 CPP

// C++ program to reverse Array

// using reverse() in STL

#include <algorithm>

#include <iostream>

using namespace std;


int main()

// Get the array

int arr[] = { 1, 45, 54, 71, 76, 12 };

// Compute the sizes

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

// Print the array

cout << "Array: ";

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

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

// Reverse the array

reverse(arr, arr + n);

// Print the reversed array


cout << "\nReversed Array: ";

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

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

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

// the working of STL stack of pairs

#include <bits/stdc++.h>

using namespace std;

// Print the current pair

void printPair(pair<int, int> p)

cout << "("

<< p.first << ", "

<< p.second << ") ";

// Print the Stack of Pairs

void Showstack(stack<pair<int, int> > s)

{
while (!s.empty()) {

printPair(s.top());

s.pop();

cout << '\n';

// Driver code

int main()

stack<pair<int, int> > s;

s.push({ 10, 20 });

s.push({ 15, 5 });

s.push({ 1, 5 });

s.push({ 5, 10 });

s.push({ 7, 9 });
cout << "Stack of Pairs: ";

Showstack(s);

cout << "\nSize of Stack of Pairs: "

<< s.size();

cout << "\nTop of Stack of Pairs: ";

printPair(s.top());

cout << "\n\nRemoving the top pair\n";

s.pop();

cout << "Current Stack of Pairs: ";

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)

Removing the top pair


Current Stack of Pairs: (5, 10) (1, 5) (15, 5) (10, 20)
Below are the images to show the working of Stack of Pairs:

Permutations of a given string using STL


Last Updated : 11 Jul, 2022



A permutation, also called an “arrangement number” or “order”, is a rearrangement of


the elements of an ordered list S into a one-to-one correspondence with S itself. A
string of length n has n! permutation.
Source: Mathword
Below are the permutations of string ABC.
“ABC”, “ACB”, “BAC”, “BCA”, “CBA”, “CAB”
We have discussed C implementation to print all permutations of a given string using
backtracking here. In this post, C++ implementation using STL is discussed.
Method 1 (Using rotate())
std::rotate function rotates elements of a vector/string such that the passed middle
element becomes first. For example, if we call rotate for “ABCD” with middle as
second element, the string becomes “BCDA” and if we again call rotate with middle
as second element, the string becomes “CDAB”. Refer this for a sample program.

Below is C++ implementation.

 C++

// C++ program to print all permutations with


// duplicates allowed using rotate() in STL

#include <bits/stdc++.h>

using namespace std;

// Function to print permutations of string str,

// out is used to store permutations one by one

void permute(string str, string out)

// When size of str becomes 0, out has a

// permutation (length of out is n)

if (str.size() == 0)

cout << out << endl;

return;

// One be one move all characters at


// the beginning of out (or result)

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

// Remove first character from str and

// add it to out

permute(str.substr(1), out + str[0]);

// Rotate string in a way second character

// moves to the beginning.

rotate(str.begin(), str.begin() + 1, str.end());

// Driver code

int main()

string str = "ABC";

permute(str, "");
return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to print all permutations with

// duplicates allowed using next_permutation

#include <bits/stdc++.h>

using namespace std;


// Function to print permutations of string str

// using next_permutation

void permute(string str)

// Sort the string in lexicographically

// ascending order

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

// Keep printing next permutation while there

// is next permutation

do {

cout << str << endl;

} while (next_permutation(str.begin(), str.end()));

// Driver code

int main()

{
string str = "CBA";

permute(str);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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.

All permutations of an array using STL in C++


Last Updated : 01 Mar, 2023



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

Input: a[] = {10, 20, 30, 40}


Output:
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
Approach: The next possible permutation of the array can be found
using next_permutation() function provided in STL. Syntax:
bool next_permutation (BidirectionalIterator first,
BidirectionalIterator last);
Below is the implementation of the above Approach:

 CPP

// C++ program to display all permutations


// of an array using STL in C++

#include <bits/stdc++.h>

using namespace std;

// Function to display the array

void display(int a[], int n)

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

cout << a[i] << " ";

cout << endl;

// Function to find the permutations

void findPermutations(int a[], int n)

{
// Sort the given array

sort(a, a + n);

// Find all possible permutations

cout << "Possible permutations are:\n";

do {

display(a, n);

} while (next_permutation(a, a + n));

// Driver code

int main()

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

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


findPermutations(a, n);

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

Find Maximum and Minimum element in a Set


in C++ STL
Last Updated : 21 Mar, 2023



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

Input: set={10, 20, 30, 40, 50, 60}


Output: max = 60, min = 10
 Using set.begin() and set.end() 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.begin() and set.end() methods
respectively. Program:
 CPP

#include <bits/stdc++.h>

using namespace std;

// Function to print the set

void printSet(set<int> my_set)


{

// Print the set

cout << "Set: ";

for (auto i : my_set)

cout << i << " ";

cout << '\n';

// Function to find the maximum element

int findMax(set<int> my_set)

// Get the maximum element

int max_element;

if (!my_set.empty())

max_element = *(my_set.rbegin());
// return the maximum element

return max_element;

// Function to find the minimum element

int findMin(set<int> my_set)

// Get the minimum element

int min_element;

if (!my_set.empty())

min_element = *my_set.begin();

// return the minimum element

return min_element;

}
int main()

// Get the set

set<int> my_set;

// Add the elements in the set

my_set.insert(1);

my_set.insert(6);

my_set.insert(15);

my_set.insert(10);

my_set.insert(5);

// Print the set

printSet(my_set);

// Get the minimum element

cout << "Minimum element: "


<< findMin(my_set)

<< endl;

// Get the maximum element

cout << "Maximum element: "

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

using namespace std;


// Function to print the set

void printSet(set<int> my_set)

// Print the set

cout << "Set: ";

for (auto i : my_set)

cout << i << " ";

cout << '\n';

// Function to find the maximum element

int findMax(set<int> my_set)

// Get the maximum element


int max_element;

if (!my_set.empty())

max_element = *my_set.rbegin();

// return the maximum element

return max_element;

// Function to find the minimum element

int findMin(set<int> my_set)

// Get the minimum element

int min_element;

if (!my_set.empty())

min_element = *(--my_set.rend());

// return the minimum element


return min_element;

int main()

// Get the set

set<int> my_set;

// Add the elements in the set

my_set.insert(1);

my_set.insert(6);

my_set.insert(15);

my_set.insert(10);

my_set.insert(5);

// Print the set

printSet(my_set);
// Get the minimum element

cout << "Minimum element: "

<< findMin(my_set)

<< endl;

// Get the maximum element

cout << "Maximum element: "

<< findMax(my_set)

<< endl;

Output:
Set: 1 5 6 10 15
Minimum element: 1
Maximum element: 15

C++ STL Set Insertion and Deletion


Last Updated : 09 Mar, 2023



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

1. Insertion Using insert() 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>

#include <set> // for set operations

using namespace std;

int main()

// declaring set

set<int> st;

// declaring iterators

set<int>::iterator it = st.begin();

set<int>::iterator it1, it2;

// declaring pair for return value of set containing

// set iterator and bool

pair<set<int>::iterator, bool> ptr;


// using insert() to insert single element

// inserting 20

ptr = st.insert(20);

// checking if the element was already present or newly

// inserted

if (ptr.second)

cout << "The element was newly inserted";

else

cout << "The element was already present";

// printing set elements after insertion

cout << "\nThe set elements after 1st insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// inserting set elements using hint

st.insert(it, 24);
// printing set elements after insertion

cout << "\nThe set elements after 2nd insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// inserting array elements in set

// 24 is not inserted again

int arr[3] = { 25, 24, 26 };

st.insert(arr, arr + 3);

// printing set elements after insertion

cout << "\nThe set elements after 3rd insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

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

// C++ code to demonstrate the working of emplace()

// and emplace_hint()

#include <iostream>

#include <set> // for set operations

using namespace std;

int main()

{
// declaring set

set<int> st;

// declaring iterators

set<int>::iterator it = st.begin();

set<int>::iterator it1, it2;

// declaring pair for return value of set containing

// set iterator and bool

pair<set<int>::iterator, bool> ptr;

// using emplace() to insert single element

// inserting 24

ptr = st.emplace(24);

// checking if the element was already present or

// newly inserted returns true. newly inserted

if (ptr.second)
cout << "The element was newly inserted";

else

cout << "The element was already present";

// printing set elements after insertion

cout << "\nThe set elements after 1st insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// using emplace() to insert single element

// inserting 24 // not inserted this time

ptr = st.emplace(24);

// checking if the element was already present or

// newly inserted returns false. already inserted

if (ptr.second)

cout << "\nThe element was newly inserted";

else
cout << "\nThe element was already present";

// printing set elements after insertion

cout << "\nThe set elements after 2nd insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// inserting set elements using hint

st.emplace_hint(it, 25);

// printing set elements after insertion

cout << "\nThe set elements after 3rd insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

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

// C++ code to demonstrate the working of erase()

#include <iostream>

#include <set> // for set operations

using namespace std;

int main()

// declaring set

set<int> st;
// declaring iterators

set<int>::iterator it;

set<int>::iterator it1;

set<int>::iterator it2;

// declaring pair for return value of set containing

// set iterator and bool

pair<set<int>::iterator, bool> ptr;

// inserting values in set

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

st.insert(i * 5);

// printing initial set elements

cout << "The set elements after insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";


it = st.begin();

cout << endl;

// erasing element using iterator

// erases 2nd element i.e., 10

++it;

st.erase(it);

// printing set elements after deletion

cout << "The set elements after 1st deletion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// erasing element using value

st.erase(40);

// printing set elements after deletion


cout << "\nThe set elements after 2nd deletion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

++it;

++it;

++it;

++it;

// erasing element using range iterator

// deletes 25 - last(45)

st.erase(it, st.end());

// printing set elements 3rd deletion

cout << "\nThe set elements after 3rd deletion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";


cout << endl;

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

C++ STL Set Insertion and Deletion


Last Updated : 09 Mar, 2023



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

1. Insertion Using insert() 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>

#include <set> // for set operations

using namespace std;

int main()

// declaring set

set<int> st;
// declaring iterators

set<int>::iterator it = st.begin();

set<int>::iterator it1, it2;

// declaring pair for return value of set containing

// set iterator and bool

pair<set<int>::iterator, bool> ptr;

// using insert() to insert single element

// inserting 20

ptr = st.insert(20);

// checking if the element was already present or newly

// inserted

if (ptr.second)

cout << "The element was newly inserted";

else
cout << "The element was already present";

// printing set elements after insertion

cout << "\nThe set elements after 1st insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// inserting set elements using hint

st.insert(it, 24);

// printing set elements after insertion

cout << "\nThe set elements after 2nd insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// inserting array elements in set

// 24 is not inserted again

int arr[3] = { 25, 24, 26 };


st.insert(arr, arr + 3);

// printing set elements after insertion

cout << "\nThe set elements after 3rd insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

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

// C++ code to demonstrate the working of emplace()

// and emplace_hint()

#include <iostream>

#include <set> // for set operations

using namespace std;

int main()

// declaring set

set<int> st;

// declaring iterators

set<int>::iterator it = st.begin();

set<int>::iterator it1, it2;

// declaring pair for return value of set containing

// set iterator and bool

pair<set<int>::iterator, bool> ptr;


// using emplace() to insert single element

// inserting 24

ptr = st.emplace(24);

// checking if the element was already present or

// newly inserted returns true. newly inserted

if (ptr.second)

cout << "The element was newly inserted";

else

cout << "The element was already present";

// printing set elements after insertion

cout << "\nThe set elements after 1st insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// using emplace() to insert single element


// inserting 24 // not inserted this time

ptr = st.emplace(24);

// checking if the element was already present or

// newly inserted returns false. already inserted

if (ptr.second)

cout << "\nThe element was newly inserted";

else

cout << "\nThe element was already present";

// printing set elements after insertion

cout << "\nThe set elements after 2nd insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// inserting set elements using hint

st.emplace_hint(it, 25);
// printing set elements after insertion

cout << "\nThe set elements after 3rd insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

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

// C++ code to demonstrate the working of erase()


#include <iostream>

#include <set> // for set operations

using namespace std;

int main()

// declaring set

set<int> st;

// declaring iterators

set<int>::iterator it;

set<int>::iterator it1;

set<int>::iterator it2;

// declaring pair for return value of set containing

// set iterator and bool

pair<set<int>::iterator, bool> ptr;


// inserting values in set

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

st.insert(i * 5);

// printing initial set elements

cout << "The set elements after insertion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

it = st.begin();

cout << endl;

// erasing element using iterator

// erases 2nd element i.e., 10

++it;

st.erase(it);
// printing set elements after deletion

cout << "The set elements after 1st deletion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

// erasing element using value

st.erase(40);

// printing set elements after deletion

cout << "\nThe set elements after 2nd deletion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

++it;

++it;

++it;

++it;
// erasing element using range iterator

// deletes 25 - last(45)

st.erase(it, st.end());

// printing set elements 3rd deletion

cout << "\nThe set elements after 3rd deletion are : ";

for (it1 = st.begin(); it1 != st.end(); ++it1)

cout << *it1 << " ";

cout << endl;

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

How to find the sum of elements of a Vector


using STL in C++?
Last Updated : 16 Apr, 2023


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

Input: vec = {1, 7, 5, 4, 6, 12}


Output: 35
Approach:
Sum can be found with the help of accumulate() function provided in STL.
Syntax:
accumulate(first_index, last_index, initial value of sum);

 CPP

// C++ program to find the sum

// of Array using accumulate() in STL

#include <bits/stdc++.h>

using namespace std;

int main()

// Get the vector

vector<int> a = { 1, 45, 54, 71, 76, 12 };


// Print the vector

cout << "Vector: ";

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

cout << a[i] << " ";

cout << endl;

// Find the sum of the vector

cout << "\nSum = " << accumulate(a.begin(), a.end(), 0);

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)

Another Approach: (Using the for_each() function)

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

// C++ program to find the sum

// of Array using for_each() function in STL

#include <bits/stdc++.h>

using namespace std;

int main()

// Get the vector

vector<int> a = { 1, 45, 54, 71, 76, 12 };

int sum = 0;

// Print the vector and calculate sum

cout << "Vector: ";


for_each(a.begin(), a.end(), [&](int i) {

cout << i << " ";

sum += i;

});

// Print the sum of the vector

cout << "\nSum = " << sum << endl;

return 0;

// This code is contributed by Susobhan Akhuli

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

// C++ code to demonstrate the working of copy()

// and copy_n()

#include<iostream>

#include<algorithm> // for copy() and copy_n()

#include<vector>
using namespace std;

int main()

// initializing source vector

vector<int> v1 = { 1, 5, 7, 3, 8, 3 };

// declaring destination vectors

vector<int> v2(6);

vector<int> v3(6);

// using copy() to copy 1st 3 elements

copy(v1.begin(), v1.begin()+3, v2.begin());

// printing new vector

cout << "The new vector elements entered using copy() : ";

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


cout << v2[i] << " ";

cout << endl;

// using copy_n() to copy 1st 4 elements

copy_n(v1.begin(), 4, v3.begin());

// printing new vector

cout << "The new vector elements entered using copy_n() : ";

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

cout << v3[i] << " ";

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

// C++ code to demonstrate the working of copy_if()

// and copy_backward()

#include<iostream>

#include<algorithm> // for copy_if() and copy_backward()

#include<vector>

using namespace std;

int main()

// initializing source vector

vector<int> v1 = { 1, 5, 6, 3, 8, 3 };

// declaring destination vectors

vector<int> v2(6);
vector<int> v3(6);

// using copy_if() to copy odd elements

copy_if(v1.begin(), v1.end(), v2.begin(), [](int i){return i%2!=0;});

// printing new vector

cout << "The new vector elements entered using copy_if() : ";

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

cout << v2[i] << " ";

cout << endl;

// using copy_backward() to copy 1st 4 elements

// ending at second last position

copy_backward(v1.begin(), v1.begin() + 4, v3.begin()+ 5);

// printing new vector

cout << "The new vector elements entered using copy_backward() : ";
for(int i=0; i<v3.size(); i++)

cout << v3[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);

x: Destination container where the new elements will


be inserted.
it: Iterator pointing to the insertion point.

Returns: An insert_iterator that inserts elements into


x at the position indicated by it.
The syntax for copy using inserter():
copy(strt_iter1, end_iter1, inserter(Container& x, typename
Container::iterator it));

C++

// C++ code to demonstrate the working of copy() using inserter()

#include <iostream>

#include <algorithm>

#include <vector>

using namespace std;

int main()

vector<int> v1 = {1, 5, 7, 3, 8, 3};

vector<int>::iterator itr;

vector<int> v2;

//using inserter()

copy(v1.begin(), v1.end(), inserter(v2, itr));


cout << "\nThe new vector elements entered using inserter: ";

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

cout << v2[i] << " ";

Output:
The new vector elements entered using inserter: 1 5 7 3 8 3

Binary Search functions in C++ STL


(binary_search, lower_bound and
upper_bound)
Last Updated : 20 Jun, 2023



Binary search is an important component in competitive programming or any


algorithmic competition, having knowledge of shorthand functions reduces the time to
code them. Binary search is the most efficient search algorithm.
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing
the search interval in half. The idea of binary search is to use the information that the
array is sorted and reduce the time complexity to O(Log N).

General operations performed using binary search:

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.

Coding implementation of binary_search function:

 CPP

// C++ code to demonstrate the working of binary_search()

#include <bits/stdc++.h>

using namespace std;

// Driver's code

int main()

// initializing vector of integers

vector<int> arr = { 10, 15, 20, 25, 30, 35 };

// using binary_search to check if 15 exists

if (binary_search(arr.begin(), arr.end(), 15))


cout << "15 exists in vector";

else

cout << "15 does not exist";

cout << endl;

// using binary_search to check if 23 exists

if (binary_search(arr.begin(), arr.end(), 23))

cout << "23 exists in vector";

else

cout << "23 does not exist";

cout << endl;

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.

Coding implementation of lower_bound function:

 CPP

// C++ code to demonstrate the working of lower_bound()

#include <bits/stdc++.h>

using namespace std;

// Driver's code

int main()

// initializing vector of integers

// for single occurrence

vector<int> arr1 = { 10, 15, 20, 25, 30, 35 };


// initializing vector of integers

// for multiple occurrences

vector<int> arr2 = { 10, 15, 20, 20, 25, 30, 35 };

// initializing vector of integers

// for no occurrence

vector<int> arr3 = { 10, 15, 25, 30, 35 };

// using lower_bound() to check if 20 exists

// single occurrence

// prints 2

cout << "The position of 20 using lower_bound "

" (in single occurrence case) : ";

cout << lower_bound(arr1.begin(), arr1.end(), 20)

- arr1.begin();

cout << endl;


// using lower_bound() to check if 20 exists

// multiple occurrence

// prints 2

cout << "The position of 20 using lower_bound "

"(in multiple occurrence case) : ";

cout << lower_bound(arr2.begin(), arr2.end(), 20)

- arr2.begin();

cout << endl;

// using lower_bound() to check if 20 exists

// no occurrence

// prints 2 ( index of next higher)

cout << "The position of 20 using lower_bound "

"(in no occurrence case) : ";

cout << lower_bound(arr3.begin(), arr3.end(), 20)

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

Coding implementation of upper_bound function:

 CPP

// C++ code to demonstrate the working of upper_bound()

#include <bits/stdc++.h>

using namespace std;


// Driver's code

int main()

// initializing vector of integers

// for single occurrence

vector<int> arr1 = { 10, 15, 20, 25, 30, 35 };

// initializing vector of integers

// for multiple occurrences

vector<int> arr2 = { 10, 15, 20, 20, 25, 30, 35 };

// initializing vector of integers

// for no occurrence

vector<int> arr3 = { 10, 15, 25, 30, 35 };

// using upper_bound() to check if 20 exists

// single occurrence

// prints 3
cout << "The position of 20 using upper_bound"

" (in single occurrence case) : ";

cout << upper_bound(arr1.begin(), arr1.end(), 20)

- arr1.begin();

cout << endl;

// using upper_bound() to check if 20 exists

// multiple occurrence

// prints 4

cout << "The position of 20 using upper_bound "

"(in multiple occurrence case) : ";

cout << upper_bound(arr2.begin(), arr2.end(), 20)

- arr2.begin();

cout << endl;

// using upper_bound() to check if 20 exists


// no occurrence

// prints 2 ( index of next higher)

cout << "The position of 20 using upper_bound"

" (in no occurrence case) : ";

cout << upper_bound(arr3.begin(), arr3.end(), 20)

- arr3.begin();

cout << endl;

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



Unlike normal C/C++ arrays, we don’t need to do element by element comparison to


find if two given vectors contain same elements or not.
In case of vectors, the operator “==” is overloaded to find the result quickly. Below is
an example to demonstrate same.

 C++14

// C++ implementation to check whether elements

// in vector is equal or not

#include<bits/stdc++.h>

using namespace std;

// Check if all elements is equal or not

int main()

// Comparing equal vectors

vector<int> v1{3, 1, 2, 3};

vector<int> v2{3, 1, 2, 3};

(v1 == v2)? cout << "Equal\n" : cout << "Not Equal\n";

// Comparing non-equal vectors

vector<int> v3{1, 2, 3, 4};

(v1 == v3)? cout << "Equal\n" : cout << "Not Equal\n";


// comparing with empty

vector<int> v4;

(v1 == v4)? cout << "Equal\n" : cout << "Not Equal\n";

// comparing two empty

vector<int> v5;

(v5 == v4)? cout << "Equal\n" : cout << "Not Equal\n";

return 0;

Output:
Equal
Not Equal
Not Equal
Equal

C++ Date and Time Programs


Print calendar for a given year in C++
Last Updated : 21 Jun, 2021




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

// A C++ Program to Implement a Calendar

// of an year

#include<bits/stdc++.h>

using namespace std;

/*A Function that returns the index of the day

of the date- day/month/year

For e.g-

Index Day

0 Sunday

1 Monday

2 Tuesday

3 Wednesday

4 Thursday
5 Friday

6 Saturday*/

int dayNumber(int day, int month, int year)

static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1,

4, 6, 2, 4 };

year -= month < 3;

return ( year + year/4 - year/100 +

year/400 + t[month-1] + day) % 7;

/*

A Function that returns the name of the month

with a given month number

Month Number Name

0 January
1 February

2 March

3 April

4 May

5 June

6 July

7 August

8 September

9 October

10 November

11 December */

string getMonthName(int monthNumber)

string months[] = {"January", "February", "March",

"April", "May", "June",

"July", "August", "September",

"October", "November", "December"

};
return (months[monthNumber]);

/* A Function to return the number of days in

a month

Month Number Name Number of Days

0 January 31

1 February 28 (non-leap) / 29 (leap)

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

*/

int numberOfDays (int monthNumber, int year)

// January

if (monthNumber == 0)

return (31);

// February

if (monthNumber == 1)

// If the year is leap then February has

// 29 days

if (year % 400 == 0 ||

(year % 4 == 0 && year % 100 != 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);

// Function to print the calendar of the given year

void printCalendar(int year)

printf (" Calendar - %d\n\n", year);

int days;

// Index of the day from 0 to 6

int current = dayNumber (1, 1, year);


// i --> Iterate through all the months

// j --> Iterate through all the days of the

// month - i

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

days = numberOfDays (i, year);

// Print the current month name

printf("\n ------------%s-------------\n",

getMonthName (i).c_str());

// Print the columns

printf(" Sun Mon Tue Wed Thu Fri Sat\n");

// Print appropriate spaces

int k;

for (k = 0; k < current; 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;

// Driver Program to check above functions

int main()

int year = 2016;

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

// C++ Program to print current Day, Date and Time


#include <ctime>

#include <iostream>

using namespace std;

int main()

// Declaring argument for time()

time_t tt;

// Declaring variable to store return value of

// localtime()

struct tm* ti;

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

 current_time: It specifies a pointer to a time_t object.


Return Value

 On Success, returns a pointer to a tm object.


 Otherwise, the Null pointer is returned.
Examples of gmtime()
Example 1
 C

// C program to illustrate the gmtime() function

#include <stdio.h>

#include <time.h>

#define CST (+8)

#define IND (-5)

int main()

// object

time_t current_time;

// pointer

struct tm* ptime;


// use time function

time(¤t_time);

// gets the current-time

ptime = gmtime(¤t_time);

// print the current time

printf("Current time:\n");

printf("Beijing ( China ):%2d:%02d:%02d\n",

(ptime->tm_hour + CST) % 24, ptime->tm_min,

ptime->tm_sec);

printf("Delhi ( India ):%2d:%02d:%02d\n",

(ptime->tm_hour + IND) % 24, ptime->tm_min,

ptime->tm_sec);

return 0;
}

Output
Current time:
Beijing ( China ):20:00:04
Delhi ( India ): 7:00:04
Example 2
 C

// C++ program to illustrate the

// gmtime() function

#include <stdio.h>

#include <time.h>

#define UTC (0)

#define ART (-3)

int main()

// object

time_t current_time;
// pointer

struct tm* ptime;

// use time function

time(¤t_time);

// print the current time

ptime = gmtime(¤t_time);

printf("Current time:\n");

printf("Monrovia ( Liberia ) :%2d:%02d:%02d\n",

(ptime->tm_hour + UTC) % 24, ptime->tm_min, ptime->tm_sec);

printf("Buenos Aires ( Argentina ) :%2d:%02d:%02d\n",

(ptime->tm_hour + ART) % 24, ptime->tm_min, ptime->tm_sec);

return 0;

Output
Current time:
Monrovia ( Liberia ) :11:45:36
Buenos Aires ( Argentina ) : 8:45:36

C++ Miscellaneous Programs


C++ Program to Find Quotient and Remainder
Last Updated : 03 Aug, 2023



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

// C++ program to find quotient

// and remainder

#include <bits/stdc++.h>

using namespace std;

// Driver code

int main()

int Dividend, Quotient, Divisor, Remainder;

cout << "Enter Dividend & Divisor: ";

cin >> Dividend >> Divisor;

Quotient = Dividend / Divisor;

Remainder = Dividend % Divisor;

cout << "The Quotient = " << Quotient << endl;


cout << "The Remainder = " << Remainder << endl;

return 0;

Output
Enter Dividend & Divisor: The Quotient = 0
The Remainder = 32767

C++ Program to Find the Size of int, float,


double and char
Last Updated : 02 Aug, 2023



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

// C++ program to find the size of int, char,

// float and double data types

#include <iostream>

using namespace std;

int main()

{
int integerType;

char charType;

float floatType;

double doubleType;

// Calculate and Print

// the size of integer type

cout << "Size of int is: " << sizeof(integerType)

<< "\n";

// Calculate and Print

// the size of doubleType

cout << "Size of char is: " << sizeof(charType) << "\n";

// Calculate and Print

// the size of charType

cout << "Size of float is: " << sizeof(floatType)

<< "\n";
// Calculate and Print

// the size of floatType

cout << "Size of double is: " << sizeof(doubleType)

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

 Time complexity: O(1)


 Auxiliary space: O(1)
Data Types with Their Size, Range, and Format Specifiers
Here is a list of all the data types with their size, range and format specifiers:
/tbody>
Memory Format
Data Type (bytes) Range Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

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

-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

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

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

unsigned long long 0 to


8 %llu
int 18,446,744,073,709,551,615

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.17549e-38 to 3.40282e+38 %f


Memory Format
Data Type (bytes) Range Specifier

2.22507e-308 to
double 8 %lf
1.79769e+308

C++ Program to Find Initials of a Name


Last Updated : 27 Jan, 2023



Given a string name, we have to find the initials of the name


Examples:
Input: Kamlesh Joshi
Output: K J
We take the first letter of all
words and print in capital letter.

Input: Jude Law


Output: J L

Input: Abhishek Kumar Bisht


Output: A K B
1) Print first character in capital.
2) Traverse rest of the string and print every character after space in capital letter.

 C++

// C++ program to print initials of a name

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

void printInitials(const string& name)

if (name.length() == 0)

return;

// Since toupper() returns int,

// we do typecasting

cout << (char)toupper(name[0]);

// Traverse rest of the string and print the

// characters after spaces.

for (int i = 1; i < name.length() - 1; i++)

if (name[i] == ' ')

cout << " " << (char)toupper(name[i + 1]);

}
// Driver code

int main()

string name = "Kamlesh Joshi";

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

// C++ program to solve the

// above approach

#include <bits/stdc++.h>

using namespace std;

void printInitials(string name)

{
if (name.length() == 0)

return;

// split the string using 'space'

// and print the first character of

// every word

// X is an object of stringstream

// that references the S string

stringstream X(name);

// use while loop to check the

// getline() function condition

while (getline(X, name, ' '))

/* X represents to read the string from

stringstream, T use for store the

token string and, ' ' whitespace


represents to split the string where

whitespace is found. */

// Print split string

cout << (char)toupper(name[0]) << " ";

// Driver code

int main()

string name = "Kamlesh Joshi";

printInitials(name);

return 0;

Output:
K J

C++ Program To Find Power Without Using


Multiplication(*) And Division(/) Operators
Last Updated : 17 Jan, 2023


Method 1 (Using Nested Loops):


We can calculate power by using repeated addition.
For example to calculate 5^6.
1) First 5 times add 5, we get 25. (5^2)
2) Then 5 times add 25, we get 125. (5^3)
3) Then 5 times add 125, we get 625 (5^4)
4) Then 5 times add 625, we get 3125 (5^5)
5) Then 5 times add 3125, we get 15625 (5^6)
 C++

// C++ code for power function

#include <bits/stdc++.h>

using namespace std;

// Works only if a >= 0

// and b >= 0

int pow(int a, int b)

if (b == 0)

return 1;

int answer = a;

int increment = a;
int i, j;

for(i = 1; i < b; i++)

for(j = 1; j < a; j++)

answer += increment;

increment = answer;

return answer;

// Driver Code

int main()

cout << pow(5, 3);

return 0;

}
// This code is contributed by rathbhupendra

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to implement

// the above approach

#include<bits/stdc++.h>

using namespace std;

// A recursive function

// to get x*y

int multiply(int x, int y)

if(y)
return (x + multiply(x,

y - 1));

else

return 0;

// A recursive function to get a^b

// Works only if a >= 0 and b >= 0

int pow(int a, int b)

if(b)

return multiply(a,

pow(a, b - 1));

else

return 1;

// Driver Code
int main()

cout << pow(5, 3);

getchar();

return 0;

// This code is contributed by Akanksha Rai

Learn Data Structures & Algorithms with GeeksforGeeks

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

// C++ program to implement

// the above approach

#include <iostream>

using namespace std;


// Function calculating power

long long pow(int a, int n)

int ans = 1;

while(n > 0)

// Calculate last bit(right most)

// bit of n

int last_bit = n&1;

// if last bit is 1 then multiply

// ans and a

if(last_bit)

ans = ans*a;

}
// Make a equal to square of a as on

// every succeeding bit it got squared

// like a^0, a^1, a^2, a^4, a^8

a = a * a;

n = n >> 1;

return ans;

// Driver code

int main()

cout << pow(3, 5);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(log n)


Auxiliary Space: O(1)
C++ Program To Find The Roots Of Quadratic
Equation
Last Updated : 20 Mar, 2024



Given a quadratic equation in the form ax2 + bx + c, find roots of it.

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.

There are the following important cases:


1. If b*b < 4*a*c, then roots are complex (not real).
Example:
roots of x2 + x + 1, roots are:
-0.5 + i0.86603 and -0.5 – i0.86603
2. If b*b == 4*a*c, then roots are real and both roots are same.
Example:
roots of x2 – 2x + 1 are 1 and 1
3. If b*b > 4*a*c, then roots are real and different.
Example:
roots of x2 – 7x – 12 are 3 and 4
Roots of Quadratic Equation Flowchart

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


C++
// C++ program to find roots of
// a quadratic equation
#include <bits/stdc++.h>
using namespace std;

// Prints roots of quadratic equation


// ax*2 + bx + x
void findRoots(int a, int b, int c)
{
// If a is 0, then equation is
// not quadratic, but linear
if (a == 0) {
cout << "Invalid";
return;
}

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

Methods to generate random double

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.

1. Using random() function

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

// C++ program to generate random double

// Using random function

#include <iostream>
#include <time.h>

using namespace std;

// Driver Code

int main()

const long max_rand = 1000000L;

double lower_bound = 0;

double upper_bound = 100;

srandom(time(NULL));

// Using random function to

// get random double value

double random_double = lower_bound

+ (upper_bound - lower_bound)

* (random() % max_rand)
/ max_rand;

cout << random_double << endl;

return 0;

Output
35.9952

2. Using uniform_real_distribution and default_random_engine

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

// C++ program to generate random double

// uniform_real_distribution and
// default_random_engine

#include <iostream>

#include <random>

using namespace std;

// Driver Code

int main()

// Declaring the upper and lower

// bounds

double lower_bound = 0;

double upper_bound = 100;

uniform_real_distribution<double> unif(lower_bound,

upper_bound);

default_random_engine re;
// Getting a random double value

double random_double = unif(re);

cout << random_double << endl;

return 0;

Output
13.1538

How to Hide and Show a Console Window in


C++?
Last Updated : 27 Nov, 2022



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

// C++ program to hide and show a console window


#include <iostream>

#include <windows.h>

using namespace std;

void countdown()

cout << "3" << endl;

Sleep(1000);

cout << "2" << endl;

Sleep(1000);

cout << "1" << endl;

Sleep(1000);

cout << "0" << endl;

int main()

{
countdown();

HWND window;

AllocConsole();

// You Can Find HANDLE of other windows too

window = FindWindowA("ConsoleWindowClass", NULL);

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



Prerequisite: Namespace in C++


If we want to run a program without using a namespace, we have to the std
keyword along with the space resolution operator (::) in every printing line and
variable declaration,
For example,
std::cout<<"geeksforgeeks";
Example:
 C++

// C++ Program without the use of using namespace std;

#include <iostream>

#include <string>
int main()

std::cout << "geeksforgeeks";

return 0;

Output
geeksforgeeks

Build a custom Map using Header file in C++


Last Updated : 03 Apr, 2023



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 {

static class Map* root;

// Number of elements in the map

static int cnt;

// Left child, right child and parent

Map *left, *right, *par;

// First is key, second is value

// and depth is height of the subtree

// for the given node

int first, second, depth;

};

Learn Data Structures & Algorithms with GeeksforGeeks


Functions/Operations To Be Implemented Using Custom
Map
We will cover the following functionalities and methods in our map:
1. insert()
2. find()
3. update()
4. accessing any key
5. erase()
6. count()
7. size()
8. empty()
9. clear()
10.iterate the map
The methods and functionalities are discussed below:
1. insert():
This method is used to insert a key-value pair in the map. There are two insert()
methods used here.
One is made public and it takes two parameters:
 first – It is the key
 second – It is the respective value of the key
Syntax:
map.insert(first, second);
Below is the implementation of this method

 C++

void insert(int first, int second)

Map* temp = iterator(first);

// If element doesnot exist already


if (temp == nullptr)

insert(first)->second = second;

// If element exists already update it

else

temp->second = second;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(logN) where N is the size of map


The other one is made private. This method is called inside the operator overloading
function of [].
 It takes only one parameter: first (It is the key).
 Creates the new node with “first” as the key and returns the instance of the node.
Syntax:
map[first] = second;
Below is the implementation of this method:

 C++

Map* insert(int first)

// Increase the number of elements

cnt++;
Map* newnode = create(first);

// If empty tree simply create the root

if (root == nullptr) {

root = newnode;

return root;

Map *temp = root, *prev = nullptr;

while (temp != nullptr) {

prev = temp;

if (first < temp->first)

temp = temp->left;

else if (first > temp->first)

temp = temp->right;

else {

free(newnode);

// If element already exists


// decrease the count

cnt--;

// If the key is found then it is

// returned by reference so that it is

// updatable

return temp;

if (first < prev->first)

prev->left = newnode;

else

prev->right = newnode;

newnode->par = prev;

// Once inserted Check and balance the tree

// at every node in path from "newnode" to "root"


balance(newnode);

// New object is inserted and returned to

// initialize in the main during assignment

return newnode;

int& operator[](int key) {

return insert(key)->second;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(logN) where N is the size of the map


2. find():
It is used to find an element. This is a public method. It takes one
parameter: first (which is the key) and returns the reference associated with the key.
Internally it calls the private method iterator() to find the key
Syntax:
map.find(first);
Below is the implementation of the method

 C++

Map* iterator(int first)


{

Map* temp = root;

while (temp != nullptr && temp->first != first) {

if (first < temp->first) {

temp = temp->left;

else {

temp = temp->right;

return temp;

Map* find(int first) {

return iterator(first);

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(logN) where N is the size of the map.


3. update():
This value is used to update the value associated with a key. This is a public method.
It takes two parameters:
 first: It is the key to be found.
 second: It is the new value of the key.
The function calls the iterator() function to get the instance of the key and updates
the value associated to that key. If no such key exists then no operation is performed.
Syntax:
map.update(first, second);
Below is the implementation of the method.

 C++

void update(int first, int second)

Map* temp = iterator(first);

if (temp != nullptr) {

temp->second = second;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(logN) where N is the size of the map


4. Accessing any key:
Any value can be accessed using the subscript operator[]. The concept of method
overloading is used to implement the functionality. It is a public method and
the search() function is called inside the overloading function. It takes one
parameter: first (it is the value of the key)
Syntax:
map[first];
Below is the implementation of the method.

 C++
const Map* iterator(int first) const

Map* temp = root;

while (temp != nullptr

&& temp->first != first) {

if (first < temp->first)

temp = temp->left;

else

temp = temp->right;

return temp;

const int search(int first) const

const Map* temp = iterator(first);

// If element exists with the given key


// return its value

if (temp != nullptr)

return temp->second;

// If element doesn't exist

// return default value of 0

return 0;

const int operator[](int key) const

// Search method is also qualified with const

return search(key);

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(logN) where N is the size of the map.


5. erase():
It deletes the node with the given key and replaces it with either its in-order
predecessor or in-order successor. It is a public method. It takes one
parameter: first (it is the key whose value needs to be deleted). At the end of the
function, it calls balance() method on the parent of that node which replaced the
deleted node to balance the AVL tree.
Syntax:
map.erase(first);
Below is the implementation of the method.

 C++

void erase(int first, Map* temp = root)

Map* prev = 0;

cnt--;

while (temp != 0 && temp->first != first) {

prev = temp;

if (first < temp->first) {

temp = temp->left;

else if (first > temp->first) {

temp = temp->right;

if (temp == nullptr) {

cnt++;

return;
}

if (cnt == 0 && temp == root) {

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;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(logN) where N is the size of the map.


6. count():
This method returns the count of a key in the map. This is a public method. It takes
one parameter: first(which is the key of value whose count should be found). This
method calls the iterator() method internally and if no node is found then count is 0.
Otherwise, count returns 1.
Syntax:
map.count(first);
Below is the implementation of the method.

 C++

int count(int first)


{

Map* temp = iterator(first);

// If key is found

if (temp != nullptr)

return 1;

// If key is not found

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(logN) where N is the size of the map.


7. size():
This method returns the size of the map. This is a public method. This method does
not take any parameter.
Syntax:
map.size();
Below is the implementation of the method.

 C++

int size(void) {
return cnt;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(1)


8. empty():
This method checks if the map is empty or not. This is a public method. It returns true
if the map is empty, else false. This method does not take any parameter.
Syntax:
map.empty();
Below is the implementation of the method.

 C++

bool empty(void)

if (root == 0)

return true;

return false;

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(1)


9. clear():
This method is used to delete the whole map in. This is a public method. It does not
take any parameter. It takes the erase() method internally.
Syntax:
map.clear();
Below is the implementation of the method.

 C++

void clear(void)

while (root != nullptr) {

erase(root->first);

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(N * logN) where N is the size of the map


10. iterate():
This method is used to traverse the whole map. This is a public method. It also does
not take any parameter. The nodes are printed in the sorted manner of key.
Syntax:
map.iterate();
Below is the implementation of the method.

 C++

void iterate(Map* head = root)

if (root == 0)
return;

if (head->left != 0) {

iterate(head->left);

cout << head->first << ' ';

if (head->right != 0) {

iterate(head->right);

Learn Data Structures & Algorithms with GeeksforGeeks

Time Complexity: O(N) where N is the size of the map


Creation of Custom Map Header
 C++

// map.h

// C++ Program to implement Map class(using AVL tree)


// This is a header file map.h and doesnot contain main()

#include <iostream>

using namespace std;

// Custom Map Class

class Map {

private:

Map* iterator(int first)

// A temporary variable created

// so that we do not

// lose the "root" of the tree

Map* temp = root;

// Stop only when either the key is found

// or we have gone further the leaf node

while (temp != nullptr &&


temp->first != first) {

// Go to left if key is less than

// the key of the traversed node

if (first < temp->first) {

temp = temp->left;

// Go to right otherwise

else {

temp = temp->right;

// If there doesn't exist any element

// with first as key, nullptr is returned

return temp;

}
// Returns the pointer to element

// whose key matches first.

// Specially created for search method

// (because search() is const qualified).

const Map* iterator(int first) const

Map* temp = root;

while (temp != nullptr

&& temp->first != first) {

if (first < temp->first) {

temp = temp->left;

else {

temp = temp->right;

return temp;

}
// The const property is used to keep the

// method compatible with the method "const

// int&[]operator(int) const"

// Since we are not allowed to change

// the class attributes in the method

// "const int&[]operator(int) const"

// we have to assure the compiler that

// method called(i.e "search") inside it

// doesn't change the attributes of class

const int search(int first) const

const Map* temp = iterator(first);

if (temp != nullptr) {

return temp->second;

return 0;

}
// Utility function to return the Map* object

// with its members initialized

// to default values except the key

Map* create(int first)

Map* newnode = (Map*)malloc(sizeof(Map));

newnode->first = first;

newnode->second = 0;

newnode->left = nullptr;

newnode->right = nullptr;

newnode->par = nullptr;

// Depth of a newnode shall be 1

// and not zero to differentiate

// between no child (which returns

// nullptr) and having child(returns 1)

newnode->depth = 1;
return newnode;

// All the rotation operation are performed

// about the node itself

// Performs all the linking done when there is

// clockwise rotation performed at node "x"

void right_rotation(Map* x)

Map* y = x->left;

x->left = y->right;

if (y->right != nullptr) {

y->right->par = x;

if (x->par != nullptr && x->par->right == x) {

x->par->right = y;

else if (x->par != nullptr && x->par->left == x) {


x->par->left = y;

y->par = x->par;

y->right = x;

x->par = y;

// Performs all the linking done when there is

// anti-clockwise rotation performed at node "x"

void left_rotation(Map* x)

Map* y = x->right;

x->right = y->left;

if (y->left != nullptr) {

y->left->par = x;

if (x->par != nullptr && x->par->left == x) {

x->par->left = y;
}

else if (x->par != nullptr && x->par->right == x) {

x->par->right = y;

y->par = x->par;

y->left = x;

x->par = y;

// Draw the initial and final graph of each

// case(take case where every node has two child)

// and update the nodes depth before any rotation

void helper(Map* node)

// If left skewed

if (depthf(node->left)

- depthf(node->right) > 1) {
// If "depth" of left subtree of

// left child of "node" is

// greater than right

// subtree of left child of "node"

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

// If "depth" of right subtree

// of left child of "node" is

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

- depthf(node->right) < -1) {

// If "depth" of right subtree of right

// child of "node" is greater than

// left subtree of right child

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

// If "depth" of left subtree


// of right child of "node" is

// greater than that of right

// subtree of right child of "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"

void balance(Map* node)

while (node != root) {

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;

else if (node == root

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

// Utility method to return the

// "depth" of the subtree at the "node"

int depthf(Map* node)

if (node == nullptr)

// If it is null node

return 0;

return node->depth;

// Function to insert a value in map

Map* insert(int first)

{
cnt++;

Map* newnode = create(first);

if (root == nullptr) {

root = newnode;

return root;

Map *temp = root, *prev = nullptr;

while (temp != nullptr) {

prev = temp;

if (first < temp->first) {

temp = temp->left;

else if (first > temp->first) {

temp = temp->right;

else {

free(newnode);

cnt--;

return temp;
}

if (first < prev->first) {

prev->left = newnode;

else {

prev->right = newnode;

newnode->par = prev;

balance(newnode);

return newnode;

// Returns the previous node in

// inorder traversal of the AVL Tree.

Map* inorderPredecessor(Map* head)

if (head == nullptr)
return head;

while (head->right != nullptr) {

head = head->right;

return head;

// Returns the next node in

// inorder traversal of the AVL Tree.

Map* inorderSuccessor(Map* head)

if (head == nullptr)

return head;

while (head->left != nullptr) {

head = head->left;

return head;

}
public:

// Root" is kept static because it's a class

// property and not an instance property

static class Map* root;

static int cnt;

// "first" is key and "second" is value

Map *left, *right, *par;

int first, second, depth;

// overloaded [] operator for assignment or

// inserting a key-value pairs in the map

// since it might change the members of

// the class therefore this is

// invoked when any assignment is done

int& operator[](int key) {

return insert(key)->second;
}

// Since we have two methods with

// the same name "[]operator(int)" and

// methods/functions cannot be

// distinguished by their return types

// it is mandatory to include a const

// qualifier at the end of any of the methods

// This method will be called from a const

// reference to the object of Map class

// It will not be called for assignment

// because it doesn't allow to change

// member variables

// We cannot make it return by reference

// because the variable "temp" returned


// by the "search" method is

// statically allocated and therefore

// it's been destroyed when it is called out

const int operator[](int key) const

return search(key);

// Count returns whether an element

// exists in the Map or not

int count(int first)

Map* temp = iterator(first);

if (temp != nullptr) {

return 1;

return 0;

}
// Returns number of elements in the map

int size(void) {

return cnt;

// Removes an element given its key

void erase(int first, Map* temp = root)

Map* prev = nullptr;

cnt--;

while (temp != nullptr &&

temp->first != first) {

prev = temp;

if (first < temp->first) {

temp = temp->left;

else if (first > temp->first) {


temp = temp->right;

if (temp == nullptr) {

cnt++;

return;

if (cnt == 0 && temp == root) {

free(temp);

root = nullptr;

return;

Map* l

= inorderPredecessor(temp->left);

Map* r

= inorderSuccessor(temp->right);

if (l == nullptr && r == nullptr) {

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;

// Given the key of an element it updates

// the value of the key

void update(int first, int second)

Map* temp = iterator(first);

if (temp != nullptr) {

temp->second = second;

}
// Deleting the root of

// the tree each time until the map

// is not empty

void clear(void)

while (root != nullptr) {

erase(root->first);

// Inorder traversal of the AVL tree

void iterate(Map* head = root)

if (root == nullptr)

return;

if (head->left != nullptr) {

iterate(head->left);

}
cout << head->first << ' ';

if (head->right != nullptr) {

iterate(head->right);

// Returns a pointer/iterator to the element

// whose key is first

Map* find(int first) {

return iterator(first);

// Overloaded insert method,

// takes two parameters - key and value

void insert(int first, int second)

Map* temp = iterator(first);

if (temp == nullptr) {
insert(first)->second = second;

else {

temp->second = second;

};

Map* Map::root = nullptr;

int Map::cnt = 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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>

using namespace std;

int main()

Map map;

// 1st way of insertion

map[132] = 3;

map[34] = 5;

map[42] = -97;

map[22] = 10;

map[12] = 42;

// 2nd way of insertion

map.insert(-2,44);
map.insert(0,90);

// accessing elements

cout<<"Value at key 42 before updating = "

<<map[42]<<endl;

cout<<"Value at key -2 before updating = "

<<map[-2]<<endl;

cout<<"Value at key 12 before updating = "

<<map[12]<<endl;

// Updating value at key 42

map[42] = -32;

// Updating value at key -2

map.insert(-2,8);

// Updating value at key 12

map.update(12,444);
// accessing elements

cout<<"Value at key 42 after updating = "

<<map[42]<<endl;

cout<<"Value at key -2 after updating = "

<<map[-2]<<endl;

cout<<"Value at key 12 after updating = "

<<map[12]<<endl;

cout<<"Value at key 0 = "<<map[0]<<endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:

Example 2: Programme to demonstrate the use of erase(), clear() and iterate()


methods:
 C++
#include "map.h"

#include <iostream>

using namespace std;

int main()

Map map;

map[132] = 3;

map[34] = 5;

map[42] = -97;

map[22] = 10;

map[12] = 42;

// Iterating the Map elements before erasing 22

map.iterate();

map.erase(22);

// Iterating the Map elements after erasing 22


map.iterate();

// Deleting the whole map

map.clear();

// Now since there are zero elements

// in the Map the output is blank

cout<<"\nElements in Map after clear operation: ";

map.iterate();

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:

Example 3: Programme to demonstrate the use of find(), count(), empty() and


size() methods:
 C++

#include "map.h"
#include <iostream>

using namespace std;

int main()

Map map;

map[132] = 3;

map[34] = 5;

map[42] = -97;

cout<<"Value at 132 before updating = "

<<map[132]<<endl;

// Find method returns pointer to element

// whose key matches given key

Map *it = map.find(132);

// Updating the value at key 132

it->second = 98;
cout<<"Value at 132 after updating = "

<<map[132]<<endl;

// Count of an element which is not present

// in the map is 0

cout<<"Count of 77 = "<<map.count(77)<<endl;

// Count of an element which is present

// in the map is 1

cout<<"Count of 34 = "<<map.count(34)<<endl;

// Size of map/number of elements in map

cout<<"Map size = "<<map.size()<<endl;

// Map is not empty therefore returned 0

cout<<"Is map empty: "<<map.empty()<<endl;


// Clearing the map

map.clear();

// Map is empty therefore return 1

cout<<"Is map empty: "<<map.empty()<<endl;

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

Output:

C++ Program for Number of unique triplets


whose XOR is zero
Last Updated : 27 Aug, 2022



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.

Input : a[] = {4, 7, 5, 8, 3, 9};


Output : 1
Explanation : {4, 7, 3} is the only triplet whose XOR is 0
Naive Approach: A naive approach is to run three nested loops, the first runs from 0
to n, the second from i+1 to n, and the last one from j+1 to n to get the unique triplets.
Calculate the XOR of ai, aj, ak, check if it equals 0. If so, then increase the count.
Time Complexity: O(n3)
Efficient Approach: An efficient approach is to use one of the properties of XOR: the
XOR of two of the same numbers gives 0. So we need to calculate the XOR of unique
pairs only, and if the calculated XOR is one of the array elements, then we get the
triplet whose XOR is 0. Given below are the steps for counting the number of unique
triplets:
Below is the complete algorithm for this approach:
1. With the map, mark all the array elements.
2. Run two nested loops, one from i-n-1, and the other from i+1-n to get all the pairs.
3. Obtain the XOR of the pair.
4. Check if the XOR is an array element and not one of ai or aj.
5. Increase the count if the condition holds.
6. Return count/3 as we only want unique triplets. Since i-n and j+1-n give us unique
pairs but not triplets, we do a count/3 to remove the other two possible
combinations.
Below is the implementation of the above idea:

 C++

// CPP program to count the number of


// unique triplets whose XOR is 0

#include <bits/stdc++.h>

using namespace std;

// function to count the number of

// unique triplets whose xor is 0

int countTriplets(int a[], int n)

// To store values that are present

unordered_set<int> s;

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

s.insert(a[i]);

// stores the count of unique triplets

int count = 0;

// traverse for all i, j pairs such that j>i

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


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

// xor of a[i] and a[j]

int xr = a[i] ^ a[j];

// if xr of two numbers is present,

// then increase the count

if (s.find(xr) != s.end() && xr != a[i] &&

xr != a[j])

count++;

// returns answer

return count / 3;

// Driver code to test above function


int main()

int a[] = {1, 3, 5, 10, 14, 15};

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

cout << countTriplets(a, n);

return 0;

Learn Data Structures & Algorithms with GeeksforGeeks

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

# Add two numbers


sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Run Code

Output

The sum of 1.5 and 6.3 is 7.8

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

# Add two numbers


sum = float(num1) + float(num2)

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Run Code

Output

Enter first number: 1.5


Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8

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.

print('The sum is %.1f' %(float(input('Enter first number: ')) +


float(input('Enter second number: '))))
Run Code

Output

Enter first number: 1.5


Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
Python Program to Find the Square
Root
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

Example: For positive numbers


# Python Program to calculate the square root

# Note: change this value for a different result


num = 8

# To take the input from the user


#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5


print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Run Code

Output

The square root of 8.000 is 2.828

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

# To take input from the user


#num = eval(input('Enter a number: '))

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

The square root of (1+2j) is 1.272+0.786j

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.

Python Program to Calculate the


Area of a Triangle
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
If a , b and c are three sides of a triangle. Then,

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

# Uncomment below to take inputs from the user


# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Run Code

Output

The area of the triangle is 14.70

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

Python Program to Solve Quadratic


Equation
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Data Types
 Python Basic Input and Output
 Python Operators

The standard form of a quadratic equation is:

ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0

The solutions of this quadratic equation is given by:

(-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)

Source Code
# Solve the quadratic equation ax**2 + bx + c = 0

# import complex math module


import cmath

a = 1
b = 5
c = 6

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))


Run Code

Output

Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

Python Program to Generate a


Random Number
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Basic Input and Output
 Python Random Module
To generate random number in Python, randint() function is used. This
function is defined in random module.

Source Code
# Program to generate a random number between 0 and 9

# importing the random module


import random

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 ,

where the endpoints are included in the range.

Python Program to Convert


Kilometers to Miles
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Data Types
 Python Basic Input and Output
 Python Operators

Example: Kilometers to Miles


# Taking kilometers input from the user
kilometers = float(input("Enter value in kilometers: "))

# 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

Enter value in kilometers: 3.5


3.50 kilometers is equal to 2.17 miles

Here, the user is asked to enter kilometers. This value is stored in


the kilometers variable.
Since 1 kilometer is equal to 0.621371 miles, we can get the equivalent miles
by multiplying kilometers with this factor.

Your turn: Modify the above program to convert miles to kilometers using the
following formula and run it.

kilometers = miles / conv_fac


Python Program to Convert Celsius
To Fahrenheit
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Data Types
 Python Basic Input and Output
 Python Operators

In the program below, we take a temperature in degree Celsius and convert it


into degree Fahrenheit. They are related by the formula:

fahrenheit = celsius * 1.8 + 32

Source Code
# Python Program to convert temperature in celsius to fahrenheit

# change this value for a different result


celsius = 37.5

# 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

We encourage you to create a Python program to convert Fahrenheit to


Celsius on your own using the following formula

celsius = (fahrenheit - 32) / 1.8

Python Program to Check if a


Number is Positive, Negative or 0
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python Basic Input and Output

Source Code: Using if...elif...else


num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Run Code

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

The output of both programs will be the same.

Output 1

Enter a number: 2
Positive number

Output 2

Enter a number: 0
Zero

A number is positive if it is greater than zero. We check this in the expression


of if . If it is False , the number will either be zero or negative. This is also
tested in subsequent expression.

Python Program to Check if a


Number is Odd or Even
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Operators
 Python if...else Statement
A number is even if it is perfectly divisible by 2. When the number is divided
by 2, we use the remainder operator % to compute the remainder. If the
remainder is not zero, the number is odd.
Source Code
# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Run Code

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,

2017 is not a leap year

1900 is a not leap year

2012 is a leap year

2000 is a leap year

Source Code
# Python program to check if year is a leap year or not

year = 2000

# To get year (integer input) from the user


# year = int(input("Enter a year: "))

# divided by 100 means century year (ending with 00)


# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))

# not divided by 100 means not a century year


# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))

# 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

2000 is a leap year

You can change the value of year in the source code and run it again to test
this program.

Python Program to Find the Largest


Among Three Numbers
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python Basic Input and Output
In the program below, the three numbers are stored
in num1 , num2 and num3 respectively. We've used the if...elif...else ladder to
find the largest among the three and display it.
Source Code
# Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)


Run Code

Output

The largest number is 14.0

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.

Example 1: Using a flag variable


# Program to check if a number is prime or not

num = 29

# To take input from the user


#num = int(input("Enter a number: "))

# define a flag variable


flag = 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:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True


if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
Run Code

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 it is True , num is not a prime number.


 If it is False , num is a prime number.
Note: We can improve our program by decreasing the range of numbers
where we look for factors.
In the above program, our search range is from 2 to num - 1 .
We could have used the
range, range(2,num//2) or range(2,math.floor(math.sqrt(num)+1)) . The latter range
is based on the fact that a composite number must have a factor less than or
equal to the square root of that number. Otherwise, the number is prime.
You can change the value of variable num in the above source code to check
whether a number is prime or not for other integers.
In Python, we can also use the for...else statement to do this task without
using an additional flag variable.

Example 2: Using a for...else statement


num = 407

# To take input from the user


#num = int(input("Enter a number: "))

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

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
Run Code
Output

407 is not a prime number


11 times 37 is 407

Here, we have used a for..else statement to check if num is prime.


It works on the logic that the else clause of the for loop runs if and only if we
don't break out the for loop. That condition is met only when no factors are
found, which means that the given number is prime.
So, in the else clause, we print that the number is prime.

Python Program to Print all Prime


Numbers in an Interval
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.

Source Code
# Python program to display all the prime numbers within an interval
lower = 900
upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Run Code

Output

Prime numbers between 900 and 1000 are:


907
911
919
929
937
941
947
953
967
971
977
983
991
997

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 of a Number using Loop


# Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7

# To take input from the user


#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Run Code

Output

The factorial of 7 is 5040

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

i=6 120 * 6 = 720

i=7 720 * 7 = 5040


Factorial of a Number using Recursion
# Python program to find the factorial of a number provided by the user
# using recursion

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

# change the value for a different result


num = 7

# to take input from the user


# num = int(input("Enter a number: "))

# call the factorial function


result = factorial(num)
print("The factorial of", num, "is", result)
Run Code

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

# To take input from the user


# num = int(input("Display multiplication table of? "))

# Iterate 10 times from i = 1 to 10


for i in range(1, 11):
print(num, 'x', i, '=', num*i)
Run Code

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.

Python Program to Print the


Fibonacci sequence
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python while Loop

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

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

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Run Code

Output

How many terms? 7


Fibonacci sequence:
0
1
1
2
3
5
8
Here, we store the number of terms in nterms . We initialize the first term to 0
and the second term to 1.
If the number of terms is more than 2, we use a while loop to find the next
term in the sequence by adding the preceding two terms. We then
interchange the variables (update it) and continue on with the process.
You can also print the Fibonacci sequence using recursion.

Python Program to Check


Armstrong Number
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python while Loop

A positive integer is called an Armstrong number of order n if

abcd... = an + bn + cn + dn + ...

In case of an Armstrong number of 3 digits, the sum of cubes of each digit is


equal to the number itself. For example:

153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.


Source Code: Check Armstrong number (for 3 digits)
# Python program to check if the number is an Armstrong number or not

# take input from the user


num = int(input("Enter a number: "))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Run Code

Output 1

Enter a number: 663


663 is not an Armstrong number

Output 2

Enter a number: 407


407 is an Armstrong number

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.

Source Code: Check Armstrong number of n digits


num = 1634

# Changed num variable to string,


# and calculated the length (number of digits)
order = len(str(num))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Run Code

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

Python Program to Find the Sum of


Natural Numbers
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python while Loop

In the program below, we've used an if...else statement in combination with


a while loop to calculate the sum of natural numbers up to num .

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

The sum is 136

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

For example, if n = 16, the sum would be (16*17)/2 = 136.


Your turn: Modify the above program to find the sum of natural numbers
using the formula below
Python Program to Display Powers
of 2 Using Anonymous Function
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python Lambda/Anonymous Function

In the program below, we have used an anonymous (lambda) function inside


the map() built-in function to find the powers of 2.
Source Code
# Display the powers of 2 using anonymous function

terms = 10

# Uncomment code below to take input from the user


# terms = int(input("How many terms? "))

# use anonymous function


result = list(map(lambda x: 2 ** x, range(terms)))

print("The total terms are:",terms)


for i in range(terms):
print("2 raised to power",i,"is",result[i])
Run Code

Output

The total terms are: 10


2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512

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

In the program below, we have used anonymous (lambda) function inside


the filter() built-in function to find all the numbers divisible by 13 in the list.
Source Code
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]

# use anonymous function to filter


result = list(filter(lambda x: (x % 13 == 0), my_list))
# display the result
print("Numbers divisible by 13 are",result)
Run Code

Output

Numbers divisible by 13 are [65, 39, 221]

Python Program to Convert Decimal


to Binary, Octal and Hexadecimal
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Programming Built-in Functions

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.

A number with the prefix 0b is considered binary, 0o is considered octal


and 0x as hexadecimal. For example:

60 = 0b11100 = 0o74 = 0x3c


Source Code
# Python program to convert decimal into other number systems
dec = 344

print("The decimal value of", dec, "is:")


print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
Run Code

Output

The decimal value of 344 is:


0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

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.

A positive integer is called an Armstrong number of order n if

abcd... = an + bn + cn + dn + ...

For example,

153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.

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

for num in range(lower, upper + 1):

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

Python Program to Find the Sum of


Natural Numbers
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python while Loop

In the program below, we've used an if...else statement in combination with


a while loop to calculate the sum of natural numbers up to num .

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

The sum is 136

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

For example, if n = 16, the sum would be (16*17)/2 = 136.


Your turn: Modify the above program to find the sum of natural numbers
using the formula below.

Python Program to Display Powers


of 2 Using Anonymous Function
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python Lambda/Anonymous Function
In the program below, we have used an anonymous (lambda) function inside
the map() built-in function to find the powers of 2.
Source Code
# Display the powers of 2 using anonymous function

terms = 10

# Uncomment code below to take input from the user


# terms = int(input("How many terms? "))

# use anonymous function


result = list(map(lambda x: 2 ** x, range(terms)))

print("The total terms are:",terms)


for i in range(terms):
print("2 raised to power",i,"is",result[i])
Run Code

Output

The total terms are: 10


2 raised to power 0 is 1
2 raised to power 1 is 2
2 raised to power 2 is 4
2 raised to power 3 is 8
2 raised to power 4 is 16
2 raised to power 5 is 32
2 raised to power 6 is 64
2 raised to power 7 is 128
2 raised to power 8 is 256
2 raised to power 9 is 512

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

In the program below, we have used anonymous (lambda) function inside


the filter() built-in function to find all the numbers divisible by 13 in the list.
Source Code
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]

# use anonymous function to filter


result = list(filter(lambda x: (x % 13 == 0), my_list))

# display the result


print("Numbers divisible by 13 are",result)
Run Code

Output

Numbers divisible by 13 are [65, 39, 221]


Python Program to Convert Decimal
to Binary, Octal and Hexadecimal
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Programming Built-in Functions

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.

A number with the prefix 0b is considered binary, 0o is considered octal


and 0x as hexadecimal. For example:

60 = 0b11100 = 0o74 = 0x3c

Source Code
# Python program to convert decimal into other number systems
dec = 344

print("The decimal value of", dec, "is:")


print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
Run Code

Output

The decimal value of 344 is:


0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

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.

Python Program to Find ASCII Value


of Character
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Basic Input and Output
 Python Programming Built-in Functions

ASCII stands for American Standard Code for Information Interchange.

It is a numeric value given to different characters and symbols, for computers


to store and manipulate. For example, the ASCII value of the letter 'A' is 65.
Source Code
# Program to find the ASCII value of the given character

c = 'p'
print("The ASCII value of '" + c + "' is", ord(c))
Run Code

Output

The ASCII value of 'p' is 112

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'

Here, ord() and chr() are built-in functions.

Python Program to Find HCF or


GCD
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Functions
 Python Recursion
 Python Function Arguments
 Python if...else Statement

The highest common factor (H.C.F) or greatest common divisor (G.C.D) of


two numbers is the largest positive integer that perfectly divides the two given
numbers. For example, the H.C.F of 12 and 14 is 2.

Source Code: Using Loops


# Python program to find H.C.F of two numbers

# define a function
def compute_hcf(x, y):

# choose the smaller number


if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

num1 = 54
num2 = 24

print("The H.C.F. is", compute_hcf(num1, num2))


Run Code

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.

Source Code: Using the Euclidean Algorithm


# Function to find HCF the Using Euclidian algorithm
def compute_hcf(x, y):
while(y):
x, y = y, x % y
return x

hcf = compute_hcf(300, 400)


print("The HCF is", hcf)
Run Code

Here we loop until y becomes zero. The statement x, y = y, x % y does


swapping of values in Python. Click here to learn more about swapping
variables in Python.
In each iteration, we place the value of y in x and the remainder (x % y) in y ,
simultaneously. When y becomes zero, we have H.C.F. in x .

Python Program to Find LCM


To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python Functions
 Python Function Arguments
 Python User-defined Functions

The least common multiple (L.C.M.) of two numbers is the smallest positive
integer that is perfectly divisible by the two given numbers.

For example, the L.C.M. of 12 and 14 is 84.

Program to Compute LCM


# Python Program to find the L.C.M. of two input number
def compute_lcm(x, y):

# choose the greater number


if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm

num1 = 54
num2 = 24

print("The L.C.M. is", compute_lcm(num1, num2))


Run Code

Output

The L.C.M. is 216

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.

Number1 * Number2 = L.C.M. * G.C.D.

Here is a Python program to implement this.

Program to Compute LCM Using GCD


# Python program to find the L.C.M. of two input number

# This function computes GCD


def compute_gcd(x, y):

while(y):
x, y = y, x % y
return x

# This function computes LCM


def compute_lcm(x, y):
lcm = (x*y)//compute_gcd(x,y)
return lcm

num1 = 54
num2 = 24

print("The L.C.M. is", compute_lcm(num1, num2))


Run Code

The output of this program is the same as before. We have two


functions compute_gcd() and compute_lcm() . We require G.C.D. of the numbers
to calculate its L.C.M.
So, compute_lcm() calls the function compute_gcd() to accomplish this. G.C.D. of
two numbers can be calculated efficiently using the Euclidean algorithm.
Also Read:
 calculate G.C.D in Python

Python Program to Find HCF or


GCD
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Functions
 Python Recursion
 Python Function Arguments
 Python if...else Statement

The highest common factor (H.C.F) or greatest common divisor (G.C.D) of


two numbers is the largest positive integer that perfectly divides the two given
numbers. For example, the H.C.F of 12 and 14 is 2.

Source Code: Using Loops


# Python program to find H.C.F of two numbers

# define a function
def compute_hcf(x, y):

# choose the smaller number


if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf

num1 = 54
num2 = 24

print("The H.C.F. is", compute_hcf(num1, num2))


Run Code

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.

Source Code: Using the Euclidean Algorithm


# Function to find HCF the Using Euclidian algorithm
def compute_hcf(x, y):
while(y):
x, y = y, x % y
return x

hcf = compute_hcf(300, 400)


print("The HCF is", hcf)
Run Code

Here we loop until y becomes zero. The statement x, y = y, x % y does


swapping of values in Python. Click here to learn more about swapping
variables in Python.
In each iteration, we place the value of y in x and the remainder (x % y) in y ,
simultaneously. When y becomes zero, we have H.C.F. in x .

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

# This function computes the factor of the argument passed


def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)

num = 320

print_factors(num)
Run Code

Output

The factors of 320 are:


1
2
4
5
8
10
16
20
32
40
64
80
160
320

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

Python Program to Make a Simple


Calculator
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Operators
 Python Functions
 Python Function Arguments
 Python User-defined Functions

Example: Simple Calculator by Using Functions


# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

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

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
Run Code

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

Python Program to Shuffle Deck of


Cards
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python Modules
 Python Random Module
 Python Programming Built-in Functions
Source Code
# Python program to shuffle a deck of card

# importing modules
import itertools, random

# make a deck of cards


deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))

# shuffle the cards


random.shuffle(deck)

# draw five cards


print("You got:")
for i in range(5):
print(deck[i][0], "of", deck[i][1])
Run Code

Output

You got:
5 of Heart
1 of Heart
8 of Spade
12 of Spade
4 of Spade

Note: Run the program again to shuffle the cards.


In the program, we used the product() function in itertools module to create a
deck of cards. This function performs the Cartesian product of the two
sequences.
The two sequences are numbers from 1 to 13 and the four suits. So,
altogether we have 13 * 4 = 52 items in the deck with each card as a tuple.
For example,

deck[0] = (1, 'Spade')


Our deck is ordered, so we shuffle it using the
function shuffle() in random module.
Finally, we draw the first five cards and display it to the user. We will get
different output each time you run this program as shown in our two outputs.

Here we have used the standard modules itertools and random that comes
with Python.

Python Program to Display


Calendar
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Modules
 Python Programming Built-in Functions

In the program below, we import the calendar module. The built-in


function month() inside the module takes in the year and the month and
displays the calendar for that month of the year.
Source Code
# Program to display calendar of the given month and year

# importing calendar module


import calendar

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

# display the calendar


print(calendar.month(yy, mm))
Run Code

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.

Python Program to Display


Fibonacci Sequence Using
Recursion
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python Functions
 Python Recursion
 Python if...else Statement
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....

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

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Run Code

Output

Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34

Note: To test the program, change the value of nterms.


In this program, we store the number of terms to be displayed in nterms .

A recursive function recur_fibo() is used to calculate the nth term of the


sequence. We use a for loop to iterate and calculate each term recursively.

Python Program to Find Sum of


Natural Numbers Using Recursion
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python Functions
 Python Recursion

In the program below, we've used a recursive function recur_sum() to compute


the sum up to the given number.
Source Code
# Python program to find the sum of natural using recursive function

def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)

# change this value for a different result


num = 16

if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
Run Code

Output

The sum is 136

Note: To test the program for another number, change the value of num .

Python Program to Find Factorial of


Number Using Recursion
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python Functions
 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.
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

# check if the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Run Code

Output

The factorial of 7 is 5040

Note: To find the factorial of another number, change the value of num .

Here, the number is stored in num . The number is passed to


the recur_factorial() function to compute the factorial of the number.

Python Program to Convert Decimal


to Binary Using Recursion
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python Functions
 Python Recursion

Decimal number is converted into binary by dividing the number successively


by 2 and printing the remainder in reverse order.

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.

Python Program to Add Two


Matrices
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python List

In Python, we can implement a matrix as a nested list (list inside a list). We


can treat each element as a row of the matrix.
For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First
row can be selected as X[0] and the element in first row, first column can be
selected as X[0][0] .

We can perform matrix addition in various ways in Python. Here are a couple
of them.

Source code: Matrix Addition using Nested Loop


# Program to add two matrices using nested loop

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

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

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

result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]

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.

Python Program to Transpose a


Matrix
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python List

In Python, we can implement a matrix as a nested list (list inside a list). We


can treat each element as a row of the matrix.

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

Transpose of a matrix is the interchanging of rows and columns. It is denoted


as X' . The element at ith row and jth column in X will be placed at jth row
and ith column in X' . So if X is a 3x2 matrix, X' will be a 2x3 matrix.
Here are a couple of ways to accomplish this in Python.

Matrix Transpose using Nested Loop


# Program to transpose a matrix using a nested loop

X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

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

Matrix Transpose using Nested List Comprehension


''' Program to transpose a matrix using list comprehension'''

X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]

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

In Python, we can implement a matrix as nested list (list inside a list).

We can treat each element as a row of the matrix.

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

Multiplication of two matrices X and Y is defined only if the number of columns


in X is equal to the number of rows Y .
If X is a n x m matrix and Y is a m x l matrix then, XY is defined and has the
dimension n x l (but YX is not defined). Here are a couple of ways to
implement matrix multiplication in Python.
Source Code: Matrix Multiplication using Nested Loop
# Program to multiply two matrices using nested loops

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

# iterate through rows of X


for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)
Run Code

Output

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]

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.

For larger matrix operations we recommend optimized software packages


like NumPy which is several (in the order of 1000) times faster than the above
code.
Source Code: Matrix Multiplication Using Nested List
Comprehension
# Program to multiply two matrices using list comprehension

# 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

A palindrome is a string that is the same read forward or backward.

For example, "dad" is the same in forward or reverse direction. Another


example is "aibohphobia", which literally means, an irritable fear of
palindromes.
Source Code
# Program to check if a string is palindrome or not

my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Run Code

Output

The string is a palindrome.

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 .

Using the method casefold() we make it suitable for caseless comparisons.


Basically, this method returns a lowercased version of the string.
We reverse the string using the built-in function reversed(). Since this function
returns a reversed object, we use the list() function to convert them into a list
before comparing.

Python Program to Remove


Punctuations From a String
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python Strings
 Python if...else Statement

Sometimes, we may wish to break a sentence into a list of words.

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 = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user


# my_str = input("Enter a string: ")

# remove punctuation from the string


no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char

# display the unpunctuated string


print(no_punct)
Run Code

Output

Hello he said and went

In this program, we first define a string of punctuations. Then, we iterate over


the provided string using a for loop.
In each iteration, we check if the character is a punctuation mark or not using
the membership test. We have an empty string to which we add (concatenate)
the character if it is not punctuation. Finally, we display the cleaned up string.

Python Program to Sort Words in


Alphabetic Order
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python Strings
 String Methods

In this example, we illustrate how words can be sorted lexicographically


(alphabetic order).

Source Code
# Program to sort alphabetically the words form a string provided by the user

my_str = "Hello this Is an Example With cased letters"

# To take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = [word.lower() for word in my_str.split()]

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)
Run Code

Output

The sorted words are:


an
cased
example
hello
is
letters
this
with

Note: To test the program, change the value of my_str .

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 Program to Illustrate


Different Set Operations
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Sets
 Python Basic Input and Output

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

# define three sets


E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};

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

# set symmetric difference


print("Symmetric difference of E and N is",E ^ N)
Run Code

Output

Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}


Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}

In this program, we take two different sets and perform different set operations
on them. This can equivalently done by using set methods.

Python Program to Count the


Number of Each Vowel
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python Strings
 String Methods

Source Code: Using Dictionary


# Program to count the number of each vowels

# string of vowels
vowels = 'aeiou'

ip_str = 'Hello, have you tried our tutorial section yet?'

# make it suitable for caseless comparisions


ip_str = ip_str.casefold()

# make a dictionary with each vowel a key and value 0


count = {}.fromkeys(vowels,0)

# count the vowels


for char in ip_str:
if char in count:
count[char] += 1

print(count)
Run Code

Output

{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}

Here, we have taken a string stored in ip_str . Using the method casefold() ,

we make it suitable for caseless comparisons. Basically, this method returns a


lowercased version of the string.
We use the dictionary method fromkeys() to construct a new dictionary with
each vowel as its key and all values equal to 0. This is the initialization of the
count.
Next, we iterate over the input string using a for loop.

In each iteration, we check if the character is in the dictionary keys ( True if it is


a vowel) and increment the value by 1 if true.

Source Code: Using a list and a dictionary


comprehension
# Using dictionary and list comprehension

ip_str = 'Hello, have you tried our tutorial section yet?'

# make it suitable for caseless comparisions


ip_str = ip_str.casefold()

# count the vowels


count = {x:sum([1 for char in ip_str if char == x]) for x in 'aeiou'}

print(count)
Run Code

The output of this program is the same as above.


Here, we have nested a list comprehension inside a dictionary
comprehension to count the vowels in a single line.
The dictionary comprehension runs for all vowel characters and the list
comprehension inside the dictionary comprehension checks if any characters
in the string match that particular vowel.
At the end, a list with 1s is generated for the number of each vowel character.
The sum() method is used to calculate the sum of the elements for each list.
However, this program is slower as we iterate over the entire input string for
each vowel.

Python Program to Merge Mails


To understand this example, you should have the knowledge of the
following Python programming topics:
 String Methods
 Python File Operation

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.

Source Code to Merge Mails

# Python program to mail merger


# Names are in the file names.txt
# Body of the mail is in body.txt

# open names.txt for reading


with open("names.txt", 'r', encoding='utf-8') as names_file:

# open body.txt for reading


with open("body.txt", 'r', encoding='utf-8') as body_file:

# read entire content of the body


body = body_file.read()

# iterate over names


for name in names_file:
mail = "Hello " + name.strip() + "\n" + body

# write the mails to individual files


with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file:
mail_file.write(mail)

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.

Python Program to Find the Size


(Resolution) of an Image
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Functions
 Python User-defined Functions
 Python File Operation

JPEG (pronounced "jay-peg") stands for Joint Photographic Experts Group. It


is one of the most widely used compression techniques for image
compression.

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.

Source Code of Find Resolution of JPEG Image

def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into
it"""

# open image for reading in binary mode


with open(filename,'rb') as img_file:

# height of image (in 2 bytes) is at 164th position


img_file.seek(163)

# read the 2 bytes


a = img_file.read(2)

# calculate height
height = (a[0] << 8) + a[1]

# next 2 bytes is width


a = img_file.read(2)

# calculate width
width = (a[0] << 8) + a[1]

print("The resolution of the image is",width,"x",height)

jpeg_res("img1.jpg")

Output

The resolution of the image is 280 x 280

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.

Python Program to Find Hash of File


To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Functions
 Python User-defined Functions
 Python File Operation
Hash functions take an arbitrary amount of data and return a fixed-length
bit string. The output of the function is called the digest message.
They are widely used in cryptography for authentication purposes. There are
many hashing functions like MD5, SHA-1 etc. Refer this page to know more
about hash functions in cryptography.
In this example, we will illustrate how to hash a file. We will use the SHA-1
hashing algorithm. The digest of SHA-1 is 160 bits long.

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.

Source Code to Find Hash

# Python program to find the SHA-1 message digest of a file

# importing the hashlib module


import hashlib

def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""

# make a hash object


h = hashlib.sha1()

# open file for reading in binary mode


with open(filename,'rb') as file:

# loop till the end of the file


chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
chunk = file.read(1024)
h.update(chunk)
# return the hex representation of digest
return h.hexdigest()

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.

Finally, we return the digest message in hexadecimal representation using


the hexdigest() method.

Python Program to Create Pyramid


Patterns
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python if...else Statement
 Python for Loop
 Python while Loop
 Python break and continue
List of Source Code

Code to print triangles using *, numbers and characters

Code to print inverted triangles using * and digits

Code to print full pyramids

Code to print Pascal's triangle

Code to print Floyd's triangle

Programs to print triangles using *, numbers and


characters
Example 1: Program to print half pyramid using *

* *

* * *

* * * *

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

In the above program, let's see how the pattern is printed.

 First, we get the height of the pyramid rows from the user.
 In the first loop, we iterate from i = 0 to i = rows .

 The second loop runs from j = 0 to i + 1. In each iteration of this loop, we


print i + 1 number of * without a new line. Here, the row number gives the
number of * required to be printed on that row. For example, in the 2nd row,
we print two * . Similarly, in the 3rd row, we print three * .
 Once the inner loop ends, we print new line and start printing * in a new line.

Python Program to Merge Two


Dictionaries
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Dictionary
 Python *args and **kwargs
Example 1: Using the | Operator
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}

print(dict_1 | dict_2)
Run Code

Output

{1: 'a', 2: 'c', 4: 'd'}

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.

Example 2: Using the ** Operator


dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}

print({**dict_1, **dict_2})
Run Code

Output

{1: 'a', 2: 'c', 4: 'd'}


In the above program, we have used ** to unpack
dictionaries dict_1 and dict_2 . Then, the dictionaries are merged by placing
them inside {} .

To know more about **kwargs, visit Python *args and **kwargs.

Note: The above code works for Python 3.5 and above versions.

Example 3: Using copy() and update()


dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}

dict_3 = dict_2.copy()
dict_3.update(dict_1)

print(dict_3)
Run Code

Output

{2: 'b', 4: 'd', 1: 'a'}

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

There are different ways to create a nested directory depending on the


versions of python you are using. For this example, we will create directories
as shown in the image below.

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.

from pathlib import Path


Path("/root/dirA/dirB").mkdir(parents=True, exist_ok=True)

 Import class Path from pathlib library.


 Call the module mkdir() with two arguments parents and exist_ok .

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

 exist_ok is False by default. If the directory already exists, FileExistsError is


raised. Set it to True to prevent this error.

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.

Example 2: Using os.makedirs


For python 3.2 and above, you can use os.makedirs .

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.

Example 3: Using distutils.dir_util

import distutils.dir_util

distutils.dir_util.mkpath("/root/dirA/dirB")

This example is also similar to Example 2. Here mkpath() is used instead


of makedirs() .

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.

Example 4: Raising an exception if directory already


exists
import os

try:
os.makedirs("/dirA/dirB")
except FileExistsError:
print("File already exists")

This example is similar to Example 2.

 The statement is put inside the try block.

 If the directory is already present, FileExistsError is caught by the except


block and runs the statements inside the block.

Python Program to Access Index of


a List Using for Loop
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python List
 Python enumerate()

Example 1: Using enumerate


my_list = [21, 44, 35, 11]

for index, val in enumerate(my_list):


print(index, val)
Run Code
Output

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.

Example 2: Start the indexing with non zero value


my_list = [21, 44, 35, 11]

for index, val in enumerate(my_list, start=1):


print(index, val)
Run Code

Output

1 21
2 44
3 35
4 11

The value of the parameter start provides the starting index.


Example 3: Without using enumerate()
my_list = [21, 44, 35, 11]

for index in range(len(my_list)):


value = my_list[index]
print(index, value)
Run Code

Output

0 21
1 44
2 35
3 11

You can access the index even without using enumerate() .

 Using a for loop, iterate through the length of my_list . Loop


variable index starts from 0 in this case.
 In each iteration, get the value of the list at the current index using the
statement value = my_list[index] .

 Print the value and index .

Python Program to Flatten a Nested


List
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python List
Example 1: Using List Comprehension
my_list = [[1], [2, 3], [4, 5, 6, 7]]

flat_list = [num for sublist in my_list for num in sublist]


print(flat_list)
Run Code

Output

[1, 2, 3, 4, 5, 6, 7]

This is one of the simplest pythonic ways of flattening a list.

 Using list comprehension access the sublist from my_list , then access each
element of the sublist.
 Each element num is stored in flat_list .

To learn more about list comprehension, visit Python List Comprehension.

Example 2: Using Nested for Loops (non pythonic


way)
my_list = [[1], [2, 3], [4, 5, 6, 7]]

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]

 Create an empty list flat_list .

 Access each element of the sublist using a nested loop and append that
element to flat_list .

Example 3: Using itertools package


import itertools

my_list = [[1], [2, 3], [4, 5, 6, 7]]

flat_list = list(itertools.chain(*my_list))
print(flat_list)
Run Code

Output

[1, 2, 3, 4, 5, 6, 7]

Using itertools module, we can create a flattened list.

 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]]

flat_list = sum(my_list, [])


print(flat_list)
Run Code

Output

[1, 2, 3, 4, 5, 6, 7]

 Provide two arguments to the sum() method: my_list and an empty list
(i.e. [ ] ).

 sum() combines my_list and [ ] to produce a flattened list.

Example 5: Using lambda and reduce()


from functools import reduce

my_list = [[1], [2, 3], [4, 5, 6, 7]]


print(reduce(lambda x, y: x+y, my_list))
Run Code

Output

[1, 2, 3, 4, 5, 6, 7]

In the above example, reduce() applies the lambda function to all the elements
of my_list .

To learn more about lambda expressions, visit Python Anonymous/Lambda


Function.
Python Program to Slice Lists
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python List

The format for list slicing is [start:stop:step].


 start is the index of the list where slicing starts.
 stop is the index of the list where slicing ends.
 step allows you to select nth item within the range start to stop.
List slicing works similar to Python slice() function.

Get all the Items


my_list = [1, 2, 3, 4, 5]

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.

Note: Indexing starts from 0. Item on index 2 is also included.

Get all the Items Before a Specific Position


my_list = [1, 2, 3, 4, 5]

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.

Get all the Items from One Position to Another


Position
my_list = [1, 2, 3, 4, 5]

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.

Get the Items at Specified Intervals


my_list = [1, 2, 3, 4, 5]
print(my_list[::2])
Run Code

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]

The items from index 1 to 4 are sliced with intervals of 2.


Python Program to Iterate Over
Dictionaries Using for Loop
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python Dictionary

Example 1: Access both key and value using items()


dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

for key, value in dt.items():


print(key, value)
Run Code

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

for key in dt:


print(key, dt[key])
Run Code

Output

a juice
b grill
c corn

 Iterate through the dictionary using a for loop.

 Print the loop variable key and value at key (i.e. dt[key] ).

However, the more pythonic way is example 1.

Example 3: Access both key and value using


iteritems()
dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

for key, value in dt.iteritems():


print(key, value)
Run Code

Output

a juice
b grill
c corn

It works for python 2 versions.

As in Example 1, we can use iteritems() for python 2 versions.

Example 4: Return keys or values explicitly


dt = {'a': 'juice', 'b': 'grill', 'c': 'corn'}

for key in dt.keys():


print(key)

for value in dt.values():


print(value)
Run Code

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

Example 1: Sort the dictionary based on values


dt = {5:4, 1:6, 6:3}

sorted_dt = {key: value for key, value in sorted(dt.items(), key=lambda item:


item[1])}

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

Python Program to Check If a List is


Empty
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python List
 Python if...else Statement

Example 1: Using Boolean operation


my_list = []
if not my_list:
print("the list is empty")
Run Code

Output
the list is empty

If my_list is empty then not returns True.


It is the most pythonic way of testing emptiness. If you want to learn more
about boolean truth value, you can refer to Truth Value Testing.

Example 2: Using len()


my_list = []
if not len(my_list):
print("the list is empty")
Run Code

Output

the list is empty

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.

To learn more, visit Python len().

Example 3: Comparing with []


my_list = []
if my_list == []:
print("The list is empty")
Run Code
Output

The list is empty

[] is an empty list, therefore if my_list has no elements, then it should be


equal to [] .

Python Program to Catch Multiple


Exceptions in One Line
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Basic Input and Output
 Python Exceptions
 Python Exception Handling

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

can only concatenate str (not "int") to str

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

invalid literal for int() with base 10: 'b'

In the above example, the second input should have been an integer, but we
passed a string 'b' . Therefore, ValueError is raised.

Note: The error which comes first is caught as an exception in case of


multiple exceptions.

Python Program to Copy a File


To understand this example, you should have the knowledge of the
following Python programming topics:
 Python File Operation
Using shutil module

from shutil import copyfile


copyfile("/root/a.txt", "/root/b.txt")

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

copy() Yes Yes No No

copyfile() No No No No

copy2() Yes Yes Yes No

copyfileobj() No No No Yes

Python Program to Concatenate


Two Lists
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python List
 Python List extend()

Example 1: Using + operator


list_1 = [1, 'a']
list_2 = [3, 4, 5]

list_joined = list_1 + list_2


print(list_joined)
Run Code

Output

[1, 'a', 3, 4, 5]

In this example, + operator is used to concatenate two lists.

Example 2: Using iterable unpacking operator *


list_1 = [1, 'a']
list_2 = range(2, 4)

list_joined = [*list_1, *list_2]


print(list_joined)
Run Code

Output
[1, 'a', 2, 3]

* operator allows unpacking inside the list or tuple.

Example 3: With unique values


list_1 = [1, 'a']
list_2 = [1, 2, 3]

list_joined = list(set(list_1 + list_2))


print(list_joined)
Run Code

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.

Example 4: Using extend()


list_1 = [1, 'a']
list_2 = [1, 2, 3]

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.

Python Program to Check if a Key is


Already Present in a Dictionary
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Dictionary
 Python if...else Statement

Using in keyword
my_dict = {1: 'a', 2: 'b', 3: 'c'}

if 2 in my_dict:
print("present")
Run Code

Output

present

Using if statement and in keyword, you can check if a key is present in a


dictionary.
In the above example, 2 is present in the dictionary as a key; therefore, the
output is present .

You can use not in if you want to check if a key is not present in the
dictionary.

Python Program to Split a List Into


Evenly Sized Chunks
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python List
 Python Generators

Example 1: Using yield


def split(list_a, chunk_size):

for i in range(0, len(list_a), chunk_size):


yield list_a[i:i + chunk_size]

chunk_size = 2
my_list = [1,2,3,4,5,6,7,8,9]
print(list(split(my_list, chunk_size)))
Run Code

Output

[[1, 2], [3, 4], [5, 6], [7, 8], [9]]

In the above example, we have defined a function to split the list.


 Using a for loop and range() method, iterate from 0 to the length of the list with
the size of chunk as the step.
 Return the chunks using yield . list_a[i:i+chunk_size] gives each chunk. For
example, when i = 0, the items included in the chunk are i to i +

chunk_size which is 0 to (0 + 2)th index. In the next iteration, the items


included are 2 to 2 + 2 = 4.

Learn more about yield at Python Generators.


You can do the same thing using list compression as below.

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

[[1, 2], [3, 4], [5, 6], [7, 8], [9]]

Learn more about list comprehension at Python List Comprehension.

Example 2: Using numpy


import numpy as np

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.

Note: You need to install numpy on your system.

Python Program to Parse a String to


a Float or Int
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Data Types
 Python Strings

Example 1: Parse string into integer


balance_str = "1500"
balance_int = int(balance_str)

# print the type


print(type(balance_int))

# print the value


print(balance_int)
Run Code

Output
<class 'int'>
1500

int() can be used to parse a string to an integer. The argument


passed balance_int is the string. As shown in the above example, you can see
the type of the string changed to int .

Note: The string must be a numeral value.

Example 2: Parse string into float


balance_str = "1500.4"
balance_float = float(balance_str)

# print the type


print(type(balance_float))

# print the value


print(balance_float)
Run Code

Output

<class 'float'>
1500.4

float() can be used to parse a string to an integer. Similar to Example 1, the


string is passed as an argument to float() .
Example 3: A string float numeral into integer
balance_str = "1500.34"
balance_int = int(float(balance_str))

# print the type


print(type(balance_int))

# print the value


print(balance_int)
Run Code

Output

<class 'int'>
1500

If the string is a float numeral, you can convert it into a float type using float() ,

and then parse it to an integer using int() .

Python Program to Print Colored


Text to the Terminal
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Strings

Example 1: Using ANSI escape sequences


print('\x1b[38;2;5;86;243m' + 'Programiz' + '\x1b[0m')
Run Code
Output

Programiz

The working of the above line of code is shown in the figure below.

Code for colored terminal

Let's understand the escape code \x1b[38;2;5;86;243m .

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

Example 2: Using python module termcolor


from termcolor import colored

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.

Python Program to Convert String


to Datetime
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python datetime
 Python Strings

Example 1: Using datetime module


from datetime import datetime

my_date_string = "Mar 11 2011 11:31AM"

datetime_object = datetime.strptime(my_date_string, '%b %d %Y %I:%M%p')

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.

Example 2: Using dateutil module


from dateutil import parser

date_time = parser.parse("Mar 11 2011 11:31AM")

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

Using negative indexing


my_list = ['a', 'b', 'c', 'd', 'e']

# print the last element


print(my_list[-1])
Run Code

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

Python Program to Get a Substring


s

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

# prints "love python."


print(my_string[2:])

# prints "I love python"


print(my_string[:-1])
Run Code

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

All the text from index 2 to the end are selected.


 [:-1]

All the text before the last index is selected.

Python Program Read a File Line by


Line Into a List
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python File Operation

Example 1: Using readlines()


Let the content of the file data_file.txt be

honda 1948

mercedes 1926

ford 1903

Source Code
with open("data_file.txt") as f:
content_list = f.readlines()

# print the list


print(content_list)

# remove new line characters


content_list = [x.strip() for x in content_list]
print(content_list)
Run Code

Output

['honda 1948\n', 'mercedes 1926\n', 'ford 1903']


['honda 1948', 'mercedes 1926', 'ford 1903']

readlines() returns a list of lines from the file.


 First, open the file and read the file using readlines() .

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

# removing the characters


with open('data_file.txt') as f:
content_list = [line.rstrip() for line in f]

print(content_list)
Run Code

Output

['honda 1948\n', 'mercedes 1926\n', 'ford 1903']


['honda 1948', 'mercedes 1926', 'ford 1903']

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

Example 1: Using random module


import random

my_list = [1, 'a', 32, 'c', 'd', 31]


print(random.choice(my_list))
Run Code

Output

31

Using random module, we can generate a random element from a list. As


shown in the example above, the list my_list is passed as a parameter
to choice() method of random module.

Note: The output may vary.


Example 2: Using secrets module
import secrets

my_list = [1, 'a', 32, 'c', 'd', 31]


print(secrets.choice(my_list))
Run Code

Output

Using choice() method of secrets module, you can select a random element
from the list.
It is cryptographically safer than the random module.

Python Program to Check If a String


Is a Number (Float)
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Data Types

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 .

 Else, ValueError is raised and returns False .

For example, 's12' is alphanumeric, so it cannot be converted to float


and False is returned; whereas, '1.123' is a numeric, so it is successfully
converted to float.

Python Program to Count the


Occurrence of an Item in a List
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python List

Using count() method


freq = ['a', 1, 'a', 4, 3, 2, 'a'].count('a')
print(freq)
Run Code
Output

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

Python Program to Append to a File


To understand this example, you should have the knowledge of the
following Python programming topics:
 Python File Operation

Open file in append mode and write to it


The content of the file my_file.txt is

honda 1948

mercedes 1926

ford 1903

The source code to write to a file in append mode is:

with open("my_file.txt", "a") as f:


f.write("new text")
Run Code

The content of the file after appending a text to it is:


honda 1948

mercedes 1926

ford 1903new text

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.

Python Program to Delete an


Element From a Dictionary
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Dictionary
 Python del Statement
 Python Dictionary pop()

Example 1: Using del keyword


my_dict = {31: 'a', 21: 'b', 14: 'c'}

del my_dict[31]

print(my_dict)
Run Code
Output

{21: 'b', 14: 'c'}

In the code above, the key:value pair with key as 31 is deleted


using del keyword. del keyword gives a KeyError if the key is not present in the
dictionary.

Example 2: Using pop()


my_dict = {31: 'a', 21: 'b', 14: 'c'}

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.

Python Program to Create a Long


Multiline String
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Strings

Example 1: Using triple quotes


my_string = '''The only way to
learn to program is
by writing code.'''

print(my_string)
Run Code

Output

The only way to


learn to program is
by writing code.

You can use '''(multiline string)''' or """(multiline string)""" to print a


multiline string as shown above.

Example 2: Using parentheses and a single/double


quotes
my_string = ("The only way to \n"
"learn to program is \n"
"by writing code.")

print(my_string)
Run Code
Output

The only way to


learn to program is
by writing code.

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

The only way to


learn to program is
by writing code.

You can use \ as in the above example code to write a multiline string.

Python Program to Extract


Extension From the File Name
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Directory and Files Management
 Python File Operation
Example 1: Using splitext() method from os module
import os
file_details = os.path.splitext('/path/file.ext')
print(file_details)
print(file_details[1])
Run Code

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

Example 2: Using pathlib module


import pathlib
print(pathlib.Path('/path/file.ext').suffix)
Run Code

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.

Python Program to Measure the


Elapsed Time in Python
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python time Module

Example 1: Using time module


import time

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.

The execution time depends on the system.

Example 2: Using timeit module


from timeit import default_timer as timer

start = timer()

print(23*2.3)

end = timer()
print(end - start)
Run Code

Output

52.9
6.355400000000039e-05

Similar to Example 1, we use timer() method from timeit module.


timeit provides the most accurate results.

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

Example 1: Using __class__.__name__


class Vehicle:
def name(self, name):
return name

v = Vehicle()
print(v.__class__.__name__)
Run Code

Output

Vehicle

__class__ is the attribute of the class to which it is associated and __name__ is a


special variable in Python. Its functionality depends on where it is used.
 Create an object v of class Vehicle() .

 Print the name of the class using __class__.__name__ .


Example 2: Using type() and __name__ attribute
class Vehicle:
def name(self, name):
return name

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.

Python Program to Convert Two


Lists Into a Dictionary
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Dictionary
 Python zip()

Example 1: Using zip and dict methods


index = [1, 2, 3]
languages = ['python', 'c', 'c++']
dictionary = dict(zip(index, languages))
print(dictionary)
Run Code

Output

{1: 'python', 2: 'c', 3: 'c++'}

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.

Example 2: Using list comprehension


index = [1, 2, 3]
languages = ['python', 'c', 'c++']

dictionary = {k: v for k, v in zip(index, languages)}


print(dictionary)
Run Code

Output

{1: 'python', 2: 'c', 3: 'c++'}

This example is similar to Example 1; the only difference is that list


comprehension is being used for first zipping and then { } for converting into
a dictionary.
Python Program to Differentiate
Between type() and isinstance()
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Classes and Objects
 Python Object Oriented Programming

Difference between type() and isinstance()


Let's understand the difference between type() and isinstance() with the
example code below.
class Polygon:
def sides_no(self):
pass

class Triangle(Polygon):
def area(self):
pass

obj_polygon = Polygon()
obj_triangle = Triangle()

print(type(obj_triangle) == Triangle) # true


print(type(obj_triangle) == Polygon) # false

print(isinstance(obj_polygon, Polygon)) # true


print(isinstance(obj_triangle, Polygon)) # true
Run Code

Output
True
False
True
True

In the above example, we see that type() cannot distinguish whether an


instance of a class is somehow related to the base class. In our case,
although obj_triangle is an instance of child class Triangle , it is inherited from
the base class Polygon . If you want to relate the object of a child class with the
base class, you can achieve this with isinstance() .

Python Program to Trim Whitespace


From a String
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Strings

Example 1: Using strip()


my_string = " Python "

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

To learn more, visit Python String strip().

Example 2: Using regular expression


import re

my_string = " Hello Python "


output = re.sub(r'^\s+|\s+$', '', my_string)

print(output)
Run Code

Output

Hello python

In the regex expression, \s denotes the whitespace and \ is the or


operation. + one or more occurrences of the pattern left to it.
Python Program to Get the File
Name From the File Path
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python File Operation
 Python Strings

Example 1: Using os module


import os

# file name with extension


file_name = os.path.basename('/root/file.ext')

# file name without extension


print(os.path.splitext(file_name)[0])
Run Code

Output

file

basename() gives the name of the last file/folder of the path,


whereas splitext() splits the file name into filename and extension.
import os

print(os.path.splitext(file_name))
Run Code

Output
('file', '.ext')

Example 2: Using Path module


from pathlib import Path

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

Python Program to Represent enum


To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Object Oriented Programming

Using enum module


from enum import Enum

class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3

# print the enum member


print(Day.MONDAY)

# get the name of the enum member


print(Day.MONDAY.name)

# get the value of the enum member


print(Day.MONDAY.value)
Run Code

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

Example 1: Return values using comma


def name():
return "John","Armin"

# print the tuple with the returned values


print(name())

# get the individual items


name_1, name_2 = name()
print(name_1, name_2)
Run Code

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"

return {1:n1, 2:n2}

names = name()
print(names)
Run Code

Output

{1: 'John', 2: 'Armin'}

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.

Python Program to Get Line Count


of a File
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python enumerate()
 Python File Operation
 Python for Loop
Example 1: Using a for loop
The content of the file my_file.txt is

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

Using a for loop, the number of lines of a file can be counted.

 Open the file in read-only mode.

 Using a for loop, iterate through the object f .


 In each iteration, a line is read; therefore, increase the value of loop variable
after each iteration.

Example 2: Using list comprehension


num_of_lines = sum(1 for l in open('my_file.txt'))

print(num_of_lines)
Run Code

Output

 Open the file in read-only mode.

 Using a for loop, iterate through open('my_file.txt') .

 After each iteration, return 1.

 Find the sum of the returned values.

To learn more, visit Python List Comprehension.

Python Program to Find All File with


.txt Extension Present Inside a
Directory
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python File Operation
 Python Directory and Files Management
 Python for Loop
 Python if...else Statement
Example 1: Using glob
import glob, os

os.chdir("my_dir")

for file in glob.glob("*.txt"):


print(file)
Run Code

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

 * denotes all files with a given extension.

Example 2: Using os
import os

for file in os.listdir("my_dir"):


if file.endswith(".txt"):
print(file)
Run Code

Output

a.txt
b.txt
c.txt

In this example, we use endswith() method to check the .txt extension.


 Using a for loop, iterate through each file of directory /my_dir .

 Check if the file has extension .txt using endswith() .

Using os.walk
import os

for root, dirs, files in os.walk("my_dir"):


for file in files:
if file.endswith(".txt"):
print(file)
Run Code

Output

c.txt
b.txt
a.txt

This example uses the walk() method of the os module.


 Using a for loop, iterate through each files of my_dir .

 Check if the file has extension .txt using endswith() .


Python Program to Get File Creation
and Modification Date
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python File Operation
 Python datetime

Example 1: Using os module


import os.path, time

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

Last modification time: Mon Apr 12 10:43:24 2020


Last metadata change time or path creation time: Mon Apr 12 10:43:24 2020

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

Last modification time: 2021-04-12 10:43:24.234189


Last metadata change time or path creation time: 2021-04-12 10:43:24.234189

Similar to Example 1, st_mtime refers to the time of last modification;


whereas, st_ctime refers to the time of the last metadata change on Linux/Unix
and creation time on Windows.

Python Program to Get the Full Path


of the Current Working Directory
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python File Operation
 Python Directory and Files Management

Example 1: Using pathlib module


import pathlib

# path of the given file


print(pathlib.Path("my_file.txt").parent.absolute())

# current working directory


print(pathlib.Path().absolute())
Run Code

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.

Example 2: Using os module


import os

# path of the given file


print(os.path.dirname(os.path.abspath("my_file.txt")))

# current working directory


print(os.path.abspath(os.getcwd()))
Run Code

Output

/Users/username
/Users/username

You can do the same thing with the os module.


 Use abspath() method to get an absolute path.
 getcwd() gives the current working directory.

Python Program to Iterate Through


Two Lists in Parallel
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python List
 Python zip()
 Python for Loop

Example 1: Using zip (Python 3+)


list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']

for i, j in zip(list_1, list_2):


print(i, j)
Run Code

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

Example 2: Using itertools (Python 2+)


import itertools

list_1 = [1, 2, 3, 4]
list_2 = ['a', 'b', 'c']

# loop until the short loop stops


for i,j in zip(list_1,list_2):
print(i,j)

print("\n")

# loop until the longer list stops


for i,j in itertools.zip_longest(list_1,list_2):
print(i,j)
Run Code

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.

Python Program to Check the File


Size
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Directory and Files Management

Example 1: Using os module


import os

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 .

Python Program to Reverse a


Number
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python for Loop
 Python while Loop

Example 1: Reverse a Number using a while loop


num = 1234
reversed_num = 0

while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))
Run Code

Output

4321

In this program, while loop is used to reverse a number as given in the


following steps:

1. First, the remainder of the num divided by 10 is stored in the variable digit .

Now, the digit contains the last digit of num , i.e. 4.


digit is then added to the variable reversed after multiplying it by 10.
Multiplication by 10 adds a new place in the reversed number. One-th place
multiplied by 10 gives you tenth place, tenth gives you hundredth, and so on.
In this case, reversed_num contains 0 * 10 + 4 = 4 .

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.

4. After fourth iteration, digit equals 1, reversed equals 432 * 10 + 1 =

4321 and num = 0 .

5. Now num = 0 , so the test expression num != 0 fails and while loop exits.
reversed already contains the reversed number 4321.

Example 2: Using String slicing


num = 123456
print(str(num)[::-1])
Run Code

Output

654321

Using the string slicing concept, you can get reverse the string. ::-

1 corresponds to start:stop:step . When you pass -1 as step , the start point


goes to the end and stop at the front.

Python Program to Compute the


Power of a Number
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python pow()
 Python for Loop
 Python while Loop

Example 1: Calculate power of a number using a while


loop
base = 3
exponent = 4

result = 1

while exponent != 0:
result *= base
exponent-=1

print("Answer = " + str(result))


Run Code

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 .

Example 2: Calculate power of a number using a for


loop
base = 3
exponent = 4

result = 1

for exponent in range(exponent, 0, -1):


result *= base

print("Answer = " + str(result))


Run Code

Output

Answer = 81
Here, instead of using a while loop, we've used a for loop.

After each iteration, the exponent is decremented by 1, and the result is


multiplied by the base exponent number of times.

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

Example 3: Calculate the power of a number using


pow() function
base = 3
exponent = -4

result = pow(base, exponent)

print("Answer = " + str(result))


Run Code

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

Example 1: Count Number of Digits in an Integer using


while loop
num = 3452
count = 0

while num != 0:
num //= 10
count += 1

print("Number of digits: " + str(count))


Run Code

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.

Example 2: Using inbuilt methods


num = 123456
print(len(str(num)))
Run Code

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

Python Program to Check If Two


Strings are Anagram
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Strings
 Python if...else Statement

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.

Python program to check if two strings are anagrams


using sorted()
str1 = "Race"
str2 = "Care"

# convert both the strings into lowercase


str1 = str1.lower()
str2 = str2.lower()

# check if length is same


if(len(str1) == len(str2)):

# sort the strings


sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)

# if sorted char arrays are same


if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
Run Code

Output

race and care are anagram.

We first convert the strings to lowercase. It is because Python is case


sensitive (i.e. R and r are two different characters in Python).
Here,

 lower() - converts the characters into lower case


 sorted() - sorts both the strings
If sorted arrays are equal, then the strings are anagram.

Python Program to Capitalize the


First Character of a String
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Strings
 Python String upper()
 Python String capitalize()

Example 1: Using list slicing


my_string = "programiz is Lit"
print(my_string[0].upper() + my_string[1:])
Run Code

Output

Programiz is Lit

In the above example, my_string[0] selects the first character


and upper() converts it to uppercase. Likewise, my_string[1:] selects the
remaining characters as they are. Finally they are concatenated using + .

Example 2: Using inbuilt method capitalize()


my_string = "programiz is Lit"

cap_string = my_string.capitalize()

print(cap_string)
Run Code

Output

Programiz is lit

Note: capitalize() changes the first character to uppercase; however,


changes all other characters to lowercase.
Python Program to Compute all the
Permutation of the String
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Strings
 Python for Loop
 Python if...else Statement

Permutation is the method of selecting elements from a set in different ways.

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.

Example 1: Using recursion


def get_permutation(string, i=0):

if i == len(string):
print("".join(string))

for j in range(i, len(string)):


words = [c for c in 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 this example, recursion is used to find the permutations of a string yup .

 The if condition prints string passed as argument if it is equal to the length


of yub .

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

 This process continues until the maximum length is reached.

Example 2: Using itertools


from itertools import permutations

words = [''.join(p) for p in permutations('pro')]


print(words)
Run Code

Output

['pro', 'por', 'rpo', 'rop', 'opr', 'orp']

Using permutations from itertools module, we can find the permutations of a


string.

Python Program to Create a


Countdown Timer
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python while Loop
 Python divmod()
 Python time Module

Countdown time in Python


import time

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.

Python Program to Count the


Number of Occurrence of a
Character in String
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Strings
 Python if...else Statement

Example 1: Using a for loop


count = 0

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.

Example 2: Using method count()


my_string = "Programiz"
my_char = "r"

print(my_string.count(my_char))
Run Code

Output

count() counts the frequency of the character passed as parameter.

Python Program to Remove


Duplicate Element From a List
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Sets
 Python List

Example 1: Using set()


list_1 = [1, 2, 1, 4, 6]

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.

Example 2: Remove the items that are duplicated in


two lists
list_1 = [1, 2, 1, 4, 6]
list_2 = [7, 8, 2, 1]

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

Python Program to Convert Bytes to


a String
To understand this example, you should have the knowledge of the
following Python programming topics:
 Python Basic Input and Output

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

You might also like