0% found this document useful (0 votes)
34 views278 pages

30 OOPs Interview Questions and Answers

Uploaded by

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

30 OOPs Interview Questions and Answers

Uploaded by

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

30 OOPs Interview Questions and

Answers (2024)
Last Updated : 15 Jun, 2024



Object-Oriented Programming, or OOPs, is a programming paradigm that


implements the concept of objects in the program. It aims to provide an
easier solution to real-world problems by implementing real-world entities
such as inheritance, abstraction, polymorphism, etc. in programming. OOPs
concept is widely used in many popular languages like Java, Python, C++,
etc.

OOPs is also one of the most important topics for programming interviews.
This article contains some top interview questions on the OOPs concept.

OOPs Interview Questions


1. What is Object Oriented Programming (OOPs)?
Object Oriented Programming (also known as OOPs) is a programming
paradigm where the complete software operates as a bunch of objects
talking to each other. An object is a collection of data and the methods
which operate on that data.
2. Why OOPs?
The main advantage of OOP is better manageable code that covers the
following:
1. The overall understanding of the software is increased as the distance
between the language spoken by developers and that spoken by users.
2. Object orientation eases maintenance by the use of encapsulation. One
can easily change the underlying representation by keeping the methods
the same.
3. The OOPs paradigm is mainly useful for relatively big software.
3. What is a Class?
A class is a building block of Object Oriented Programs. It is a user-defined
data type that contains the data members and member functions that operate
on the data members. It is like a blueprint or template of objects having
common properties and methods.
4. What is an Object?
An object is an instance of a class. Data members and methods of a class
cannot be used directly. We need to create an object (or instance) of the
class to use them. In simple terms, they are the actual world entities that
have a state and behavior.
C++JavaPythonC#
#include <iostream>
using namespace std;

// defining class
class Student {
public:
string name;
};

int main()
{

// creating object
Student student1;
// assigning member some value
student1.name = "Rahul";

cout << "student1.name: " << student1.name;

return 0;
}

Output
student1.name: Rahul

5. What are the main features of OOPs?


The main feature of the OOPs, also known as 4 pillars or basic principles of
OOPs are as follows:
1. Encapsulation
2. Data Abstraction
3. Polymorphism
4. Inheritance

OOPs Main Features

6. What is Encapsulation?
Encapsulation is the binding of data and methods that manipulate them into
a single unit such that the sensitive data is hidden from the users
It is implemented as the processes mentioned below:
1. Data hiding: A language feature to restrict access to members of an
object. For example, private and protected members in C++.
2. Bundling of data and methods together: Data and methods that
operate on that data are bundled together. For example, the data members
and member methods that operate on them are wrapped into a single unit
known as a class.
7. What is Abstraction?
Abstraction is similar to data encapsulation and is very important in OOP. It
means showing only the necessary information and hiding the other
irrelevant information from the user. Abstraction is implemented using
classes and interfaces.

8. What is Polymorphism?
The word “Polymorphism” means having many forms. It is the property of
some code to behave differently for different contexts. For example, in C++
language, we can define multiple functions having the same name but
different working depending on the context.
Polymorphism can be classified into two types based on the time when the
call to the object or function is resolved. They are as follows:
 Compile Time Polymorphism
 Runtime Polymorphism
A) Compile-Time Polymorphism
Compile time polymorphism, also known as static polymorphism or early
binding is the type of polymorphism where the binding of the call to its code
is done at the compile time. Method overloading or operator overloading are
examples of compile-time polymorphism.
B) Runtime Polymorphism
Also known as dynamic polymorphism or late binding, runtime
polymorphism is the type of polymorphism where the actual implementation
of the function is determined during the runtime or execution. Method
overriding is an example of this method.
9. What is Inheritance? What is its purpose?
The idea of inheritance is simple, a class is derived from another class and
uses data and implementation of that other class. The class which is derived
is called child or derived or subclass and the class from which the child class
is derived is called parent or base or superclass.
The main purpose of Inheritance is to increase code reusability. It is also
used to achieve Runtime Polymorphism.
10. What are access specifiers? What is their significance in OOPs?
Access specifiers are special types of keywords that are used to specify or
control the accessibility of entities like classes, methods, and so
on. Private, Public, and Protected are examples of access specifiers or
access modifiers.
The key components of OOPs, encapsulation and data hiding, are largely
achieved because of these access specifiers.
11. What are the advantages and disadvantages of OOPs?
Advantages of OOPs Disadvantages of OOPs

The programmer should be well-skilled and


OOPs provides enhanced code should have excellent thinking in terms of
reusability. objects as everything is treated as an object in
OOPs.
Advantages of OOPs Disadvantages of OOPs

The code is easier to maintain and Proper planning is required because OOPs is a
update. little bit tricky.

It provides better data security by


OOPs concept is not suitable for all kinds of
restricting data access and
problems.
avoiding unnecessary exposure.

Fast to implement and easy to


redesign resulting in minimizing The length of the programs is much larger in
the complexity of an overall comparison to the procedural approach.
program.

12. What other paradigms of programming exist besides OOPs?


The programming paradigm is referred to the technique or approach of
writing a program. The programming paradigms can be classified into the
following types:

1. Imperative Programming Paradigm


It is a programming paradigm that works by changing the program state
through assignment statements. The main focus in this paradigm is on how
to achieve the goal. The following programming paradigms come under this
category:
1. Procedural Programming Paradigm: This programming paradigm is
based on the procedure call concept. Procedures, also known as routines
or functions are the basic building blocks of a program in this paradigm.
2. Object-Oriented Programming or OOP: In this paradigm, we
visualize every entity as an object and try to structure the program based
on the state and behavior of that object.
3. Parallel Programming: The parallel programming paradigm is the
processing of instructions by dividing them into multiple smaller parts
and executing them concurrently.
2. Declarative Programming Paradigm
Declarative programming focuses on what is to be executed rather than how
it should be executed. In this paradigm, we express the logic of a
computation without considering its control flow. The declarative paradigm
can be further classified into:
1. Logical Programming Paradigm: It is based on formal logic where the
program statements express the facts and rules about the problem in the
logical form.
2. Functional Programming Paradigm: Programs are created by applying
and composing functions in this paradigm.
3. Database Programming Paradigm: To manage data and information
organized as fields, records, and files, database programming models are
utilized.
13. What is the difference between Structured Programming and
Object Oriented Programming?
Structured Programming is a technique that is considered a precursor to
OOP and usually consists of well-structured and separated modules. It is a
subset of procedural programming. The difference between OOPs and
Structured Programming is as follows:
Object-Oriented Programming Structural Programming

Programming that is object-oriented A program’s logical structure is provided


is built on objects having a state by structural programming, which divides
and behavior. programs into their corresponding functions.

It follows a bottom-to-top approach. It follows a Top-to-Down approach.


Object-Oriented Programming Structural Programming

Restricts the open flow of data to


No restriction to the flow of data. Anyone
authorized parts only providing
can access the data.
better data security.

Enhanced code reusability due to


Code reusability is achieved by using
the concepts of polymorphism and
functions and loops.
inheritance.

In this, methods are written globally In this, the method works dynamically,
and code lines are processed one by making calls as per the need of code for a
one i.e., Run sequentially. certain time.

Modifying and updating the code is Modifying the code is difficult as compared
easier. to OOPs.

Data is given more importance in


Code is given more importance.
OOPs.

14. What are some commonly used Object Oriented Programming


Languages?
OOPs paradigm is one of the most popular programming paradigms. It is
widely used in many popular programming languages such as:
 C++
 Java
 Python
 Javascript
 C#
 Ruby
15. What are the different types of Polymorphism?
Polymorphism can be classified into two types based on the time when the
call to the object or function is resolved. They are as follows:
1. Compile Time Polymorphism
2. Runtime Polymorphism
Types of Polymorphism

A) Compile-Time Polymorphism
Compile time polymorphism, also known as static polymorphism or early
binding is the type of polymorphism where the binding of the call to its code
is done at the compile time. Method overloading or operator
overloading are examples of compile-time polymorphism.
B) Runtime Polymorphism
Also known as dynamic polymorphism or late binding, runtime
polymorphism is the type of polymorphism where the actual implementation
of the function is determined during the runtime or execution. Method
overriding is an example of this method.
16. What is the difference between overloading and overriding?
A compile-time polymorphism feature called overloading allows an entity
to have numerous implementations of the same name. Method overloading
and operator overloading are two examples.
Overriding is a form of runtime polymorphism where an entity with the
same name but a different implementation is executed. It is implemented
with the help of virtual functions.
17. Are there any limitations on Inheritance?
Yes, there are more challenges when you have more authority. Although
inheritance is a very strong OOPs feature, it also has significant drawbacks.
 As it must pass through several classes to be implemented, inheritance
takes longer to process.
 The base class and the child class, which are both engaged in inheritance,
are also closely related to one another (called tightly coupled). Therefore,
if changes need to be made, they may need to be made in both classes at
the same time.
 Implementing inheritance might be difficult as well. Therefore, if not
implemented correctly, this could result in unforeseen mistakes or
inaccurate outputs.
18. What different types of inheritance are there?
Inheritance can be classified into 5 types which are as follows:

1. Single Inheritance: Child class derived directly from the base class
2. Multiple Inheritance: Child class derived from multiple base classes.
3. Multilevel Inheritance: Child class derived from the class which is also
derived from another base class.
4. Hierarchical Inheritance: Multiple child classes derived from a single
base class.
5. Hybrid Inheritance: Inheritance consisting of multiple inheritance types
of the above specified.
Note: Type of inheritance supported is dependent on the language. For
example, Java does not support multiple inheritance.
19. What is an interface?
A unique class type known as an interface contains methods but not their
definitions. Inside an interface, only method declaration is permitted. You
cannot make objects using an interface. Instead, you must put that interface
into use and specify the procedures for doing so.
20. How is an abstract class different from an interface?
Both abstract classes and interfaces are special types of classes that just
include the declaration of the methods, not their implementation. An
abstract class is completely distinct from an interface, though. Following are
some major differences between an abstract class and an interface.
Abstract Class Interface

When an abstract class is inherited,


When an interface is implemented, the
however, the subclass is not required to
subclass is required to specify all of
supply the definition of the abstract
the interface’s methods as well as
method until and unless the subclass
their implementation.
actually uses it.

A class that is abstract can have both An interface can only have abstract
abstract and non-abstract methods. methods.

An abstract class can have final, non- The interface has only static and final
final, static and non-static variables. variables.

Abstract class doesn’t support multiple An interface supports multiple


inheritance. inheritance.

21. How much memory does a class occupy?


Classes do not use memory. They merely serve as a template from which
items are made. Now, objects actually initialize the class members and
methods when they are created, using memory in the process.
22. Is it always necessary to create objects from class?
No. If the base class includes non-static methods, an object must be
constructed. But no objects need to be generated if the class includes static
methods. In this instance, you can use the class name to directly call those
static methods.
23. What is the difference between a structure and a class in C++?
The structure is also a user-defined datatype in C++ similar to the class with
the following differences:
 The major difference between a structure and a class is that in a structure,
the members are set to public by default while in a class, members are
private by default.
 The other difference is that we use struct for declaring structure
and class for declaring a class in C++.
24. What is Constructor?
A constructor is a block of code that initializes the newly created object. A
constructor resembles an instance method but it’s not a method as it doesn’t
have a return type. It generally is the method having the same name as the
class but in some languages, it might differ. For example:
In python, a constructor is named __init__.
In C++ and Java, the constructor is named the same as the class name.
Example:
C++JavaPython
class base {
public:
base() { cout << "This is a constructor"; }
}
25. What are the various types of constructors in C++?
The most common classification of constructors includes:
1. Default Constructor
2. Non-Parameterized Constructor
3. Parameterized Constructor
4. Copy Constructor
1. Default Constructor
The default constructor is a constructor that doesn’t take any arguments. It is
a non-parameterized constructor that is automatically defined by the
compiler when no explicit constructor definition is provided.
It initializes the data members to their default values.
2. Non-Parameterized Constructor
It is a user-defined constructor having no arguments or parameters.
Example:
C++JavaPython
class base {
base()
{
cout << "This is a non-parameterized contructor";
}
}
3. Parameterized Constructor
The constructors that take some arguments are known as parameterized
constructors.
Example:

C++JavaPython
class base {
public:
int base;
base(int var)
{
cout << "Constructor with argument: " << var;
}
};
4. Copy Constructor
A copy constructor is a member function that initializes an object using
another object of the same class.
Example:
C++Java
class base {
int a, b;
base(base& obj) // copy constructor
{
a = obj.a;
b = obj.b;
}
}

In Python, we do not have built-in copy constructors like Java and C++ but
we can make a workaround using different methods.
26. What is a destructor?
A destructor is a method that is automatically called when the object is made
of scope or destroyed.
In C++, the destructor name is also the same as the class name but with the
(~) tilde symbol as the prefix.
In Python, the destructor is named __del__.
Example:
C++Python
class base {
public:
~base() { cout << "This is a destructor"; }
}

In Java, the garbage collector automatically deletes the useless objects so


there is no concept of destructor in Java. We could have used finalize()
method as a workaround for the java destructor but it is also deprecated
since Java 9.
27. Can we overload the constructor in a class?
Yes We can overload the constructor in a class in Java. Constructor
Overloading is done when we want constructor with different constructor
with different parameter(Number and Type).
28. Can we overload the destructor in a class?
No. A destructor cannot be overloaded in a class. The can only be one
destructor present in a class.
29. What is the virtual function?
A virtual function is a function that is used to override a method of the
parent class in the derived class. It is used to provide abstraction in a class.
In C++, a virtual function is declared using the virtual keyword,
In Java, every public, non-static, and non-final method is a virtual function.
Python methods are always virtual.
Example:
C++JavaPython
class base {
virtual void print()
{
cout << "This is a virtual function";
}
}
30. What is pure virtual function?
A pure virtual function, also known as an abstract function is a member
function that doesn’t contain any statements. This function is defined in the
derived class if needed.
Example:
C++Java
class base {
virtual void pureVirFunc() = 0;
}

In Python, we achieve this using @abstractmethod from the ABC (Abstract


Base Class) module.

Bonus Question
What is an abstract class?
In general terms, an abstract class is a class that is intended to be used for
inheritance. It cannot be instantiated. An abstract class can consist of both
abstract and non-abstract methods.
In C++, an abstract class is a class that contains at least one pure virtual
function.
In Java, an abstract class is declared with an abstract keyword.
Example:
C++Java
class absClass {
public:
virtual void pvFunc() = 0;
}
Top 100 C++ Coding Interview Questions
and Answers (2024)
Last Updated : 11 Jan, 2024



C++ is one of the most popular languages in the software industry for
developing software ranging from operating systems, and DBMS to games.
That is why it is also popular to be asked to write C++ Programs in live
coding sessions in job placement interviews.

This article provides a list of C++ coding interview questions for beginners
as well as experienced professionals. The questions are designed to test
candidates’ understanding of the following topics:
 C++ syntax and semantics
 Data structures and algorithms
 Object-oriented programming
 Memory management
 Pointers
 Templates

List of 100 C++ Coding Interview Questions and

Answers
Here is a list of 100 C++ coding interview questions and answers
1. Write a C++ Program to Check Whether a Number is a Positive or
Negative Number.
 C++

// C++ Program to check whether a number is positive or

// negative

#include <iostream>

using namespace std;

int main()

int number;

number = -100;

if (number >= 0) {
cout << number << " is a positive number." << endl;

else {

cout << number << " is a negative number." << endl;

return 0;

Output
-100 is a negative number.

2. Write a Program to Find the Greatest of the Three Numbers.


 C++

// C++ program to find greatest

// among three numbers using

#include <iostream>

using namespace std;

int main()

{
int a = 10, b = 20, c = 30;

cout << "The Greatest Among Three Numbers is : ";

if (a >= b && a >= c) {

cout << a << endl;

else if (b >= a && b >= c) {

cout << b << endl;

else {

cout << c << endl;

return 0;

Output
The Greatest Among Three Numbers is : 30
3. 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 = 247;

if (isEven(n) == true) {

cout << "Even" << endl;

}
else {

cout << "Odd";

return 0;

Output
Odd

For more information, refer to the article – C++ Program To Check


Whether Number is Even Or Odd
4. Write a Program to Find the ASCII Value of a Character
 C++

// C++ Program to find ASCII value of a character

#include <iostream>

using namespace std;

int main()

char ch;
ch = 'A';

cout << "The ASCII value of " << ch << " is " << int(ch)

<< endl;

return 0;

Output
The ASCII value of A is 65

5. Write a Program to Check Whether a Character is a Vowel or


Consonant
 C++

// C++ Program to print whether a character is vowel or not

#include <cctype>

#include <iostream>

using namespace std;


int main()

char ch = 'e';

if (isalpha(ch)) {

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o'

|| ch == 'u' || ch == 'A' || ch == 'E'

|| ch == 'I' || ch == 'O' || ch == 'U') {

cout << ch << " is a vowel." << endl;

else {

cout << ch << " is a consonant." << endl;

else {

cout << ch << " is not an alphabet." << endl;

}
return 0;

Output
e is a vowel.

6. Write a Program to Print Check Whether a Character is an


Alphabet or Not
 C++

// C++ program to print whether a character is an alphabet

// or not

#include <cctype>

#include <iostream>

using namespace std;

int main()

char ch;
ch = 'a';

if (isalpha(ch)) {

cout << ch << " is an alphabet." << endl;

else {

cout << ch << " is not an alphabet." << endl;

return 0;

Output
a is an alphabet.

7. Write a Program to Find the Length of the String Without using


strlen() Function
 C++

// C++ Program to find the length of a string without using

// strlen()
#include <cstring>

#include <iostream>

using namespace std;

int main()

string str = "GeeksforGeeks";

int length = 0;

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

length++;

cout << "The length of the string is: " << length

<< endl;

return 0;
}

Output
The length of the string is: 13

8. Write a Program to Toggle Each Character in a String


 C++

// C++ Program to toggle string

#include <cstring>

#include <iostream>

using namespace std;

int main()

string str = "GeeksforGeeks";

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

if (islower(str[i])) {

str[i] = toupper(str[i]);

}
else if (isupper(str[i])) {

str[i] = tolower(str[i]);

cout << "Toggled string: " << str << endl;

return 0;

Output
Toggled string: gEEKSFORgEEKS

9. Write a Program to Count the Number of Vowels


 C++

// C++ Program to count the number of vowels

#include <cstring>

#include <iostream>

using namespace std;


int main()

string str = "GeeksforGeeks to the moon";

int vowels = 0;

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

if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i'

|| str[i] == 'o' || str[i] == 'u'

|| str[i] == 'A' || str[i] == 'E'

|| str[i] == 'I' || str[i] == 'O'

|| str[i] == 'U') {

vowels++;

cout << "Number of vowels in the string: " << vowels

<< endl;
return 0;

Output
Number of vowels in the string: 9

10. Write a Program to Remove the Vowels from a String


 C++

// C++ Program to remove the vowels from a string

#include <cstring>

#include <iostream>

using namespace std;

int main()

int j = 0;

string str = "GeeksforGeeks";


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

if (str[i] != 'a' && str[i] != 'e' && str[i] != 'i'

&& str[i] != 'o' && str[i] != 'u'

&& str[i] != 'A' && str[i] != 'E'

&& str[i] != 'I' && str[i] != 'O'

&& str[i] != 'U') {

str[j++] = str[i];

while (j < str.size()) {

str[j] = '\0';

j++;

cout << "String without vowels: " << str << endl;
return 0;

Output
String without vowels: GksfrGks

11. Write a Program to Remove All Characters From a String Except


Alphabets
 C++

// C++ Programto remove all characters from a string except

// alphabets

#include <cctype>

#include <iostream>

#include <string>

using namespace std;

string remove_non_alphabets(string str)

string result = "";


for (char c : str) {

if (isalpha(c)) {

result += c;

return result;

int main()

string str = "Gee$ksfor$geeks";

cout << "Alphabets only: " << remove_non_alphabets(str)

<< endl;

return 0;

Output
Alphabets only: Geeksforgeeks

12. Write a Program to Remove Spaces From a String


 C++

// C++ Program to remove spaces from a string

#include <iostream>

#include <string>

using namespace std;

string remove_spaces(string str)

string result = "";

for (char c : str) {

if (c != ' ') {

result += c;

return result;
}

int main()

string str = "Gfg to the moon";

cout << "Without spaces: " << remove_spaces(str)

<< endl;

return 0;

Output
Without spaces: Gfgtothemoon

13. Write a Program to Find the Sum of the First N Natural Numbers
 C++

// C++ program to find

// Sum of first

// n natural numbers.
#include <iostream>

using namespace std;

// Function to find sum

int findSum(int n)

int sum = 0;

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

sum = sum + i;

return sum;

int main()

int n = 7;

cout << findSum(n);

return 0;
}

Output
28

14. Write a Program to Find the Factorial of a Number Using Loops


 C++

// C++ program to find factorial using loops

#include <bits/stdc++.h>

using namespace std;

// function to find factorial

int factorial(int n)

int fact = 1;

while (n > 1) {

fact *= n;

n--;

}
return fact;

// driver code

int main()

int num = 5;

cout << factorial(num);

return 0;

Output
120

15. Write a Program to Find a Leap Year or Not


 C++

// C++ program to check if a given

// year is leap year or not


#include <iostream>

using namespace std;

bool checkYear(int year)

// leap year

if (year % 400 == 0)

return true;

// Not leap year

if (year % 100 == 0)

return false;

// leap year

if (year % 4 == 0)

return true;
// Not leap year

return false;

int main()

int year = 2000;

if (checkYear(year))

cout << "Leap Year";

else

cout << "Not a Leap Year";

return 0;

Output
Leap Year

16. Write a Program to Check the Prime Number


 C++
// C++ program to check if a

// Number is prime

#include <iostream>

using namespace std;

bool isPrime(int n)

// base condition

if (n <= 1)

return false;

// Check from 2 to n-1

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

if (n % i == 0)

return false;

return true;
}

int main()

isPrime(21) ? cout << " true\n" : cout << " false\n";

isPrime(17) ? cout << " true\n" : cout << " false\n";

return 0;

Output
false

true

17. Write a Program to Check Palindrome


 C++

// C++ program to check if a

// number is Palindrome or not

#include <iostream>

using namespace std;


// Function to check Palindrome

bool checkPalindrome(int n)

int ans = 0;

int temp = n;

while (temp != 0) {

ans = (ans * 10) + (temp % 10);

temp = temp / 10;

return (ans == n);

int main()

int n = 12321;
if (checkPalindrome(n) == 1) {

cout << "Yes\n";

else {

cout << "No\n";

return 0;

Output
Yes

18. Write a Program to Check Whether a Number is an Armstrong


Number or Not
 C++

// C++ Program to check

// if number is Armstrong

// or not

#include <iostream>
using namespace std;

int main()

int n = 153;

int temp = n;

int ans = 0;

// function to calculate

// the sum of individual digits

while (n > 0) {

int rem = n % 10;

ans = (ans) + (rem * rem * rem);

n = n / 10;

}
// condition to check

if (temp == ans) {

cout << ("Yes, it is Armstrong Number");

else {

cout << ("No, it is not an Armstrong Number");

return 0;

Output
Yes, it is Armstrong Number

19. Write a Program to Find the Nth Term of the Fibonacci Series
 C++

// C++ Program to Find the

// Nth Term of the Fibonacci Series

#include <iostream>

using namespace std;


int fib(int n)

int first = 0, second = 1, ans;

if (n == 0)

return first;

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

ans = first + second;

first = second;

second = ans;

return ans;

int main()

{
int n = 13;

cout << fib(n);

return 0;

Output
233

20. Write a Program to Calculate the Greatest Common Divisor of


Two Numbers
 C++

// C++ program to find

// GCD of two numbers

#include <iostream>

using namespace std;

// Function to return gcd of a and b

int gcd(int a, int b)


{

int result = min(a, b);

while (result > 0) {

if (a % result == 0 && b % result == 0) {

break;

result--;

return result;

int main()

int a = 54, b = 33;


cout << "GCD: " << gcd(a, b);

return 0;

Output
GCD: 3

21. Write a Program to Calculate the Lowest Common Multiple


(LCM) of Two Numbers
 C++

// C++ program to

// Find LCM of two numbers

#include <iostream>

using namespace std;

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)

long long result = (a / gcd(a, b)) * b;

return result;

int main()

int a = 24, b = 13;

cout << "LCM : " << lcm(a, b);

return 0;

Output
LCM : 312
22. Write a Program for Finding the Roots of a Quadratic Equation
 C++

// C++ program to find

// Roots of a quadratic equation

#include <iostream>

#include <math.h>

using namespace std;

// Prints roots of quadratic equation ax*2 + bx + c

void findRoots(int a, int b, int c)

// If a is 0, then equation is not quadratic

if (a == 0) {

cout << "Invalid";

return;

// Formulae to calculate D
int d = b * b - 4 * a * c;

// Formulae to calculate

// square root of D

double sqrt_val = sqrt(abs(d));

// Conditons for checking root

if (d > 0) {

cout << "Roots are real and different \n";

cout << (double)(-b + sqrt_val) / (2 * a) << "\n"

<< (double)(-b - sqrt_val) / (2 * a);

else if (d == 0) {

cout << "Roots are real and same \n";

cout << -(double)b / (2 * a);

else {
cout << "Roots are complex \n";

cout << -(double)b / (2 * a) << " + i"

<< sqrt_val / (2 * a) << "\n"

<< -(double)b / (2 * a) << " - i"

<< sqrt_val / (2 * a);

int main()

int a = 1, b = 4, c = 4;

findRoots(a, b, c);

return 0;

Output
Roots are real and same
-2

23. Write a Program to Find the Smallest and Largest Element in an


Array
 C++

// C++ code to for

// Finding the minimum

// And maximum of the array

#include <iostream>

using namespace std;

// Function to find the minimum

// and maximum of the array

void findMinMax(int arr[], int n)

int mini = arr[0];

int maxi = arr[0];

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

if (arr[i] < mini) {


mini = arr[i];

else if (arr[i] > maxi) {

maxi = arr[i];

cout << "Min: " << mini << endl;

cout << "Max: " << maxi << endl;

int main()

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

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

findMinMax(arr, N);
return 0;

Output
Min: 1

Max: 5

24. Write a Program to Find the Second Smallest Element in an


Array
 C++

// C++ program to find

// Second smallest elements

#include <climits>

#include <iostream>

using namespace std;

void print2Smallest(int arr[], int n)

int first, second;


if (n < 2) {

cout << " Invalid Input ";

return;

first = second = INT_MAX;

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

// If current element is smaller than first

// Then update both first and second

if (arr[i] < first) {

second = first;

first = arr[i];

// If arr[i] is in between first and second

// Then update second


else if (arr[i] < second && arr[i] != first)

second = arr[i];

if (second == INT_MAX)

cout << "There is no second smallest element\n";

else

cout << " Second smallest element is " << second

<< endl;

int main()

int arr[] = { 21, 3, 15, 41, 34, 10 };

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

print2Smallest(arr, n);
return 0;

Output
Second smallest element is 10

25. Write a Program to Calculate the Sum of Elements in an Array


 C++

// C++ Program to calculate

// sum of elements in an array

#include <iostream>

using namespace std;

int sum(int arr[], int n)

int sum = 0;

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

sum += arr[i];
return sum;

int main()

int arr[] = { 1, 23, 54, 12, 9 };

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

cout << "Sum: " << sum(arr, n);

return 0;

Output
Sum: 99

26. Write a Program to Check if the Given String is Palindrome or


Not
 C++

// C++ program for checking


// if it is Palindrome or not

#include <iostream>

using namespace std;

string isPalindrome(string S)

for (int i = 0; i < S.length() / 2; i++) {

if (S[i] != S[S.length() - i - 1]) {

return "No";

return "Yes";

int main()

{
string S = "GeekeeG";

cout << isPalindrome(S);

return 0;

Output
Yes

27. Write a Program to Check if Two Strings are Anagram or Not


 C++

// C++ program to check if two strings

// Are anagrams of each other

#include <iostream>

using namespace std;

#define NO_OF_CHARS 256

bool areAnagram(char* str1, char* str2)


{

// Create 2 count arrays and initialize all values as 0

int count1[NO_OF_CHARS] = { 0 };

int count2[NO_OF_CHARS] = { 0 };

int i;

// For each character in input strings, increment count

// in the corresponding count array

for (i = 0; str1[i] && str2[i]; i++) {

count1[str1[i]]++;

count2[str2[i]]++;

if (str1[i] || str2[i])

return false;

// Compare count arrays


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

if (count1[i] != count2[i])

return false;

return true;

int main()

char str1[] = "Geek";

char str2[] = "for";

if (areAnagram(str1, str2))

cout << "The two strings are anagram of each other";

else

cout << "The two strings are not anagram of each "

"other";
return 0;

Output
The two strings are not anagram of each other

28. Write a Program to Print a Diamond Pattern


*
***
*****
*******
*****
***
*

 C++

// C++ program to print

// Diamond shape

#include <iostream>

using namespace std;

void printDiamond(int n)

{
int space = n - 1;

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

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

cout << " ";

// Print i+1 stars

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

cout << "* ";

cout << endl;

space--;

space = 0;

// run loop (parent loop)


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

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

cout << " ";

// Print i stars

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

cout << "* ";

cout << endl;

space++;

int main()

printDiamond(5);

return 0;
}

Output
*

* *

* * *

* * * *

* * * * *

* * * * *

* * * *

* * *

* *

29. Write a Program to Print a Pyramid Pattern


*
***
*****
*******

 C++

// C++ Program to

// Print Pyramid pattern

#include <iostream>

using namespace std;


void pattern(int n)

int k = 2 * n - 2;

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

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

cout << " ";

k = k - 1;

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

// Printing stars

cout << "* ";

cout << endl;

}
}

int main()

int n = 5;

pattern(n);

return 0;

Output
*

* *

* * *

* * * *

* * * * *

30. Write a Program to Print the Hourglass Pattern


* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *

 C++

// C Program to print hourglass pattern

#include <iostream>

using namespace std;

// function to print hourglass pattern

void hourglass(int rows)

// first outer loop to iterate each row

for (int i = 0; i < 2 * rows - 1; i++) {

// assigning comparator

int comp;

if (i < rows) {

comp = 2 * i + 1;
}

else {

comp = 2 * (2 * rows - i) - 3;

// first inner loop to print leading spaces

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

cout << ' ';

// second inner loop to print star *

for (int k = 0; k < 2 * rows - comp; k++) {

cout << "* ";

cout << '\n';

}
int main()

hourglass(5);

return 0;

Output
* * * * * * * * *

* * * * * * *

* * * * *

* * *

* * *

* * * * *

* * * * * * *

* * * * * * * * *

31. Write a Program to Print the Rotated Hourglass Pattern


* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * *
* * * *
* *

 C++

// C++ Program to print

// star pattern given

#include <iostream>

using namespace std;

void pattern(int n)

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

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

cout << "* ";

int spaces = 2 * (n - i);

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


cout << " ";

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

cout << "* ";

cout << endl;

// Printing bottom part.

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

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

cout << "* ";

}
int spaces = 2 * (n - i);

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

cout << " ";

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

cout << "* ";

cout << endl;

int main()

int n = 5;
pattern(n);

return 0;

Output
* *

* * * *

* * * * * *

* * * * * * * *

* * * * * * * * * *

* * * * * * * * * * * *

* * * * * * * * * *

* * * * * * * *

* * * * * *

* * * *

* *

32. Write a Program to Print a Simple Pyramid Pattern


 C++

// C++ Program to print a simple pyramid

#include <iostream>

using namespace std;


int main()

int rows = 5;

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

for (int j = rows; j >= i; j--) {

cout << " ";

for (int k = 1; k <= (2 * i - 1); k++) {

cout << "*";

cout << endl;

return 0;

Output
*

***

*****

*******

*********

33. Write a Program to print an Inverted Pyramid


 C++

// C++ Program to print inverted pyramid

#include <iostream>

using namespace std;

int main()

int rows = 5;

for (int i = rows; i >= 1; i--) {

for (int j = rows; j > i; j--) {

cout << " ";

}
for (int k = 1; k <= (2 * i - 1); k++) {

cout << "*";

cout << endl;

return 0;

Output
*********

*******

*****

***

34. Write a Program to Print a Triangle Star Pattern


 C++

// C++ Program to print a triangle star patter

#include <iostream>

using namespace std;


int main()

int rows;

rows = 5;

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

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

cout << "*";

cout << endl;

return 0;

Output
*
**

***

****

*****

35. Write a Program to Print Floyd’s Triangle


1
2 3
4 5 6
7 8 9 10

 C++

// C Program to print the Floyd's Triangle

#include <stdio.h>

int main()

int rows = 4;

int n = 1;

// outer loop to print all rows

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


// innter loop to print abphabet in each row

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

printf("%d ", n++);

printf("\n");

return 0;

Output
1

2 3

4 5 6

7 8 9 10

36. Write a Program to Print the Pascal Triangle


1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

 C++

// C++ program to print


// Pascal’s Triangle

#include <iostream>

using namespace std;

void printPascal(int n)

int arr[n][n];

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

arr[line][i] = arr[line - 1][i - 1]

+ arr[line - 1][i];

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

cout << "\n";

int main()

int n = 6;

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

37. Write a Program to Print the Given String in Reverse Order


 C++

// C++ Program to reversea string

#include <cstring>

#include <iostream>

using namespace std;

int main()

int len;

string str = "GeeksforGeeks";

len = str.size();
cout << "Reverse of the string: ";

for (int i = len - 1; i >= 0; i--) {

cout << str[i];

cout << endl;

return 0;

Output
Reverse of the string: skeeGrofskeeG

38. Write a C++ Program to Print the Given String in Reverse Order
Using Recursion
 C++

// C++ Program to

// Reverse string using

// recursion

#include <iostream>

using namespace std;


void reverse_str(string& s, int n, int i)

if (n <= i) {

return;

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

reverse_str(s, n - 1, i + 1);

int main()

string str = "GeeksforGeeks";

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

cout << str << endl;

Output
skeeGrofskeeG

39. Write a Program to Check if the Given String is Palindrome or


not Using Recursion
 C++

// C++ program to check

// Whether a given number

// Is palindrome or not

#include <bits/stdc++.h>

using namespace std;

bool isPalRec(char str[], int s, int n)

// If there is only one character

if (s == n)

return true;

// If first and last

// characters do not match

if (str[s] != str[n])
return false;

if (s < n + 1)

return isPalRec(str, s + 1, n - 1);

return true;

bool isPalindrome(char str[])

int n = strlen(str);

if (n == 0)

return true;

return isPalRec(str, 0, n - 1);

}
int main()

char str[] = "GeeKeeG";

if (isPalindrome(str))

cout << "Yes";

else

cout << "No";

return 0;

Output
Yes

40. Write a Program to Calculate the Length of the String Using


Recursion
 C++

// C++ Program for calculating


// the length of string

#include <iostream>

using namespace std;

int cal(char* str)

// base condition

if (*str == '\0')

return 0;

else

return 1 + cal(str + 1);

int main()

char str[] = "GeeksforGeeks";

cout << cal(str);


return 0;

Output
13

41. Write a Program to Calculate the Factorial of a Number Using


Recursion
 C++

// C++ program to calculate

// Factorial of given number

#include <iostream>

using namespace std;

unsigned long long factorial(unsigned long long n)

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

return 1;

return n * factorial(n - 1);

}
int main()

unsigned long long num = 15;

cout << "Factorial of " << num << " is "

<< factorial(num) << endl;

return 0;

Output
Factorial of 15 is 1307674368000

42. Write a Program to Count the Sum of Numbers in a String


 C++

// C++ Program to count the sume of numbers in a string

#include <iostream>

#include <sstream>

#include <string>
using namespace std;

int sum_of_numbers(string str)

int sum = 0;

for (char ch : str) {

if (isdigit(ch)) {

sum += ch - '0';

return sum;

int main()

string str;
str = "1234";

cout << "Sum of numbers: " << sum_of_numbers(str)

<< endl;

return 0;

Output
Sum of numbers: 10

43. Write a Program to Print All Natural Numbers up to N Without


Using a Semi-Colon
 C++

// C++ program to print all natural numbers upto

// N without using semi-colon

#include <iostream>

using namespace std;


#define N 10

int main()

static int x = 1;

if (cout << x << " " && x++ < N && main()) {

return 0;

Output
1 2 3 4 5 6 7 8 9 10

44. Write a Program to Swap the Values of Two Variables Without


Using any Extra Variable
 C++

// C++ program to check

// If two numbers are equal

#include <iostream>

using namespace std;


int main()

int x = 3;

int y = 4;

cout << "X : " << x << endl;

cout << "Y : " << y << endl;

x = x + y;

y = x - y;

x = x - y;

cout << endl;

cout << "After:" << endl;

cout << "X : " << x << endl;


cout << "Y : " << y << endl;

return 0;

Output
X : 3

Y : 4

After:

X : 4

Y : 3

45. Write a Program to Print the Maximum Value of an Unsigned int


Using One’s Complement (~) Operator
 C++

// C++ program to print maximum value of

// unsigned int.

#include <iostream>

using namespace std;


int main()

unsigned int max;

max = 0;

max = ~max;

cout << "Max value possible : " << max;

return 0;

Output
Max value possible : 4294967295

46. Write a Program to Check for the Equality of Two Numbers


Without Using Arithmetic or Comparison Operator
 C++

// C++ Program to equality of

// Two numbers without using

// Arithmetic or comparison operator


#include <iostream>

using namespace std;

int main()

int a = 10, b = 10;

if (a ^ b)

cout << "Not-Equal";

else

cout << "Equal";

return 0;

Output
Equal

47. Write a Program to Find the Maximum and Minimum of the Two
Numbers Without Using the Comparison Operator
 C++
// C++ program to find

// maximum and minimum of

// Two numbers without using

// loop and conditions

#include <iostream>

using namespace std;

int main()

int a = 5, b = 10;

cout << "max :" << (((a + b) + abs(a - b)) / 2) << endl;

cout << "min :" << (((a + b) - abs(a - b)) / 2) << endl;

return 0;

Output
max :10

min :5

48. Write a Program for Octal to Decimal Conversion


 C++

// C++ Program to convert ocatal to decimal

#include <cmath>

#include <iostream>

using namespace std;

int main()

int oct, dec = 0, place = 0;

// 67 is an octal number with binary equivalent 110000

oct = 67;

int temp = oct;

while (temp) {
int lastDigit = temp % 10;

temp /= 10;

dec += lastDigit * pow(8, place);

++place;

cout << "Decimal equivalent is: " << dec << endl;

return 0;

Output
Decimal equivalent is: 55

49. Write a Program for Hexadecimal to Decimal Conversion


 C++

// C++ Program to convert hexadecimal to decimal conversion

#include <cmath>

#include <iostream>
using namespace std;

int hexToDecimal(char hexDigit)

if (hexDigit >= '0' && hexDigit <= '9') {

return int(hexDigit - '0');

else if (hexDigit >= 'A' && hexDigit <= 'F') {

return int(hexDigit - 'A' + 10);

else if (hexDigit >= 'a' && hexDigit <= 'f') {

return int(hexDigit - 'a' + 10);

return -1;

int main()
{

string hex;

int decimal = 0, place = 0;

hex = "67";

int n = hex.length();

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

int digit = hexToDecimal(hex[i]);

decimal += digit * pow(16, place);

place++;

cout << "Decimal equivalent " << decimal << endl;

return 0;

Output
Decimal equivalent 103

50. Write a Program for Decimal to Binary Conversion


 C++

// c++ program to convert decimal to binary

#include <bitset>

#include <iostream>

using namespace std;

int main()

int decimal = 7;

// simplest method to convert decimal to binary

bitset<32> binary(decimal);

cout << "Binary equivalent: " << binary << endl;


return 0;

Output
Binary equivalent: 00000000000000000000000000000111

51. Write a Program for Decimal Octal Conversion


 C++

// C++ Program to convert decimal to octal equivalent

#include <cmath>

#include <iostream>

using namespace std;

int main()

int decimal, octal = 0, place = 1;

decimal = 55;
int temp = decimal;

while (temp) {

int lastDigit = temp % 8;

temp /= 8;

octal += lastDigit * place;

place *= 10;

cout << "Octal equivalent " << octal << endl;

return 0;

Output
Octal equivalent 67

52. Write a Program for Decimal to Hexadecimal Conversion


 C++

// C++ program to convert decimal to hexadecimal

#include <cmath>
#include <iostream>

#include <string>

using namespace std;

string decimalToHexa(int decimal)

string hexadecimal = "";

char hexaDecimals[16]

= { '0', '1', '2', '3', '4', '5', '6', '7',

'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

while (decimal > 0) {

int remainder = decimal % 16;

hexadecimal = hexaDecimals[remainder] + hexadecimal;

decimal /= 16;

return hexadecimal;
}

int main()

int decimal = 103;

cout << "Hexadecimal equivalent: "

<< decimalToHexa(decimal) << endl;

return 0;

Output
Hexadecimal equivalent: 67

53. Write a Program for Binary to Octal Conversion


 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 program to test above

int main()

string bin = "1111001010010100001.010110110011011";

cout << "Octal number = " << convertBinToOct(bin);

return 0;

Output
Octal number = 1712241.26633

54. Write a Program for Octal to Binary Conversion


 C++

// C++ program to convert

// Octal number to Binary

#include <iostream>

using namespace std;

// Function to convert an
// Octal to Binary Number

string OctToBin(string octnum)

long int i = 0;

string binary = "";

while (octnum[i]) {

switch (octnum[i]) {

case '0':

binary += "000";

break;

case '1':

binary += "001";

break;

case '2':

binary += "010";
break;

case '3':

binary += "011";

break;

case '4':

binary += "100";

break;

case '5':

binary += "101";

break;

case '6':

binary += "110";

break;

case '7':

binary += "111";

break;

default:
cout << "\nInvalid Octal Digit " << octnum[i];

break;

i++;

return binary;

// Driver code

int main()

// Get the Hexadecimal number

string octnum = "345";

// Convert Octal to Binary

cout << "Equivalent Binary Value = "


<< OctToBin(octnum);

return 0;

Output
Equivalent Binary Value = 011100101

55. Write a Program to Implement the Use of Encapsulation


 C++

// C++ Program to implement

// The concept of Encapsulation

#include <iostream>

using namespace std;

class Encapsulation {

private:

// data hidden from outer functions

int x;
public:

// function to set value of

// variable x

void setter(int a) { x = a; }

// function to return value of

// variable x

int getter() { return x; }

};

int main()

Encapsulation obj;

obj.setter(13);

cout << obj.getter();


return 0;

Output
13

56. Write a Program to Implement the Concept of Abstraction


 C++

// C++ Program to implement

// Working of Abstraction

#include <iostream>

using namespace std;

class implementAbstraction {

private:

int p, q;

public:

// method to set values of


// private members

void setter(int x, int y)

p = x;

q = y;

void display()

cout << "p = " << p << endl;

cout << "q = " << q << endl;

};

int main()

implementAbstraction obj;
obj.setter(1, 2);

obj.display();

return 0;

Output
p = 1

q = 2

57. Write a Program to Implement the Concept of Compile-Time


Polymorphism or Function Overloading
 C++

// C++ program to demonstrate

// Function overloading or

// Compile-time Polymorphism

#include <iostream>

using namespace std;


class Geeks {

public:

// Function same name different

// Parameters

void func(int x)

cout << "value of x is " << x << endl;

void func(double x)

cout << "value of x is " << x << endl;

void func(int x, int y)

{
cout << "value of x and y is " << x << ", " << y

<< endl;

};

int main()

Geeks obj1;

// Function being called depends

// on the parameters passed

// func() is called with int value

obj1.func(10);

// func() is called with double value

obj1.func(5.321);
// func() is called with 2 int values

obj1.func(94, 32);

return 0;

Output
value of x is 10

value of x is 5.321

value of x and y is 94, 32

58. Write a Program to Implement the Concept of Operator


Overloading
 C++

// C++ program to demonstrate

// Operator Overloading

#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

Complex operator+(Complex const& obj)

Complex res;

res.real = real + obj.real;

res.imag = imag + obj.imag;

return res;

}
void print() { cout << real << " + " << imag << "i\n"; }

};

int main()

Complex c1(15, 5), c2(3, 5);

Complex c3 = c1 + c2;

c3.print();

Output
18 + 10i

59. Write a Program to Implement the Concept of Function


Overriding or Runtime Polymorphism
 C++

// C++ program for implementation

// of Function Overloading or

// Compile time Polymorphism


#include <iostream>

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:

void print() { cout << "print derived class" << endl; }


void show() { cout << "show derived class" << endl; }

};

int main()

base* bptr;

derived d;

bptr = &d;

bptr->print();

// Non-virtual function, binded

// at compile time

bptr->show();

return 0;

Output
print derived class

show base class

60. Write a Program to Implement Single-Level Inheritance


 C++

// C++ Program to implement

// Single level inheritance

#include <iostream>

#include <string.h>

using namespace std;

class Person {

int id;

char name[100];

public:

void set_p(int id, char* name)

{
strcpy(this->name, name);

this->id = id;

void display_p()

cout << endl << id << "\t" << name << "\t";

};

class Student : private Person {

char course[50];

int fee;

public:

void set_s(int id, char* name, char* course, int fee)

{
set_p(id, name);

strcpy(this->course, course);

this->fee = fee;

void display_s()

display_p();

cout << course << "\t" << fee << endl;

};

main()

{
Student s;

char name[] = "XYZ";

char course[] = "ABC";

s.set_s(132451, name, course, 100000);

s.display_s();

return 0;

Output
132451 XYZ ABC 100000

61. Write a Program to Create a Class for Complex Numbers


 C++

// C++ Program to create a class of complex numbers

#include <bits/stdc++.h>

using namespace std;

// complex number datatype

struct c {

double real;
double img;

};

// complex clss

class Complex {

private:

struct c num;

public:

// constructors

Complex() {}

Complex(double real, double img)

num.img = img;

num.real = real;

Complex(Complex& var)
{

num.img = var.num.img;

num.real = var.num.real;

// utility functions

void print()

cout << num.real << " + i" << num.img << endl;

double imag() { return num.img; }

double real() { return num.real; }

// overloaded operators

Complex operator+(Complex& obj1)

{
Complex var;

var.num.real = num.real + obj1.num.real;

var.num.img = num.img + obj1.num.img;

return var;

Complex operator-(Complex& obj1)

Complex var;

var.num.real = num.real - obj1.num.real;

var.num.img = num.img - obj1.num.img;

return var;

Complex operator*(Complex& obj1)

{
Complex var;

var.num.real = num.real * obj1.num.real

- num.img * obj1.num.img;

var.num.img = num.real * obj1.num.img

+ num.img * obj1.num.real;

return var;

};

// driver code

int main()

Complex a(11, 12), b(5, 8);

Complex c;

c = a + b;
a.print();

b.print();

c.print();

return 0;

Output
11 + i12

5 + i8

16 + i20

62. Write a Program to Implement the Inch Feet System


 C++

// C++ Program to create a class of inchFeet length system

#include <bits/stdc++.h>

using namespace std;

// inch-feet length system datatype

struct c {
double feet;

double inch;

};

// inchFeet class

class inchFeet {

private:

struct c length;

public:

// constructors

inchFeet() {}

inchFeet(double feet, double inch)

length.inch = inch;

length.feet = feet;

}
inchFeet(inchFeet& var)

length.inch = var.length.inch;

length.feet = var.length.feet;

// utility functions

void print()

cout << length.feet << " feet and " << length.inch

<< " inches" << endl;

double inches() { return length.inch; }

double feet() { return length.feet; }

// overloaded operators
inchFeet operator+(inchFeet& obj1)

inchFeet var;

var.length.feet = length.feet + obj1.length.feet;

var.length.inch = length.inch + obj1.length.inch;

if (var.length.inch >= 12.0) {

var.length.feet++;

var.length.inch - 12.0;

return var;

inchFeet operator-(inchFeet& obj1)

inchFeet var;

struct c temp = length;

if (temp.feet > obj1.length.feet) {


if (temp.inch < obj1.length.inch) {

temp.feet--;

temp.inch += 12;

var.length.feet = temp.feet - obj1.length.feet;

var.length.inch = temp.inch - obj1.length.inch;

else {

cout << "Negative Length is not Possible\n";

return var;

};

// driver code

int main()

{
inchFeet a(11, 4), b(5, 8);

inchFeet c;

c = a - b;

a.print();

b.print();

c.print();

return 0;

Output
11 feet and 4 inches

5 feet and 8 inches

5 feet and 8 inches

63. Write a Program to Implement Bubble Sort


 C++

// C++ program to implement

// of Bubble sort
#include <iostream>

using namespace std;

// Function to 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], arr[j + 1]);

// Function to print an array


void printArray(int arr[], int size)

int i;

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

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

cout << endl;

int main()

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

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

bubbleSort(arr, N);

cout << "Sorted array: ";

printArray(arr, N);
return 0;

Output
Sorted array: 1 2 3 4 5

64. Write a Program to Implement Insertion Sort


 C++

// C++ program to implement

// Insertion sort

#include <bits/stdc++.h>

using namespace std;

// Function to sort using

// Insertion

void insertion_sort(int arr[], int n)

int i, key, j;

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

key = arr[i];
j = i - 1;

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

// Print array

void print_array(int arr[], int n)

cout << " Sorted array:";

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

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

cout << endl;


}

int main()

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

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

insertion_sort(arr, N);

print_array(arr, N);

return 0;

Output
Sorted array:1 2 3 4 5

65. Write a Program to Implement Selection Sort


 C++

// C++ program to implement

// Selection sort
#include <iostream>

using namespace std;

// Swap function

void swap(int* p, int* q)

int temp = *p;

*p = *q;

*q = temp;

void selectionSort(int arr[], int n)

int min_index;

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

min_index = i;
for (int j = i + 1; j < n; j++)

if (arr[j] < arr[min_index])

min_index = j;

// Swap the found minimum element

// with the first element

if (min_index != i)

swap(&arr[min_index], &arr[i]);

// Print Array

void printArray(int arr[], int size)

int i;

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

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


cout << endl;

int main()

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

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

selectionSort(arr, n);

cout << "Sorted array: ";

printArray(arr, n);

return 0;

Output
Sorted array: 1 2 3 4 5

66. Write a Program to Implement Merge Sort


 C++
// C++ program to implement

// Merge Sort

#include <iostream>

using namespace std;

// Merge Sorted arrays

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

auto indexOfSubArrayOne = 0, indexOfSubArrayTwo = 0;

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

// Copying remaing elements

while (indexOfSubArrayOne < subArrayOne) {

array[indexOfMergedArray]

= leftArray[indexOfSubArrayOne];

indexOfSubArrayOne++;

indexOfMergedArray++;

while (indexOfSubArrayTwo < subArrayTwo) {

array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];

indexOfSubArrayTwo++;

indexOfMergedArray++;

delete[] leftArray;

delete[] rightArray;

void mergeSort(int array[], int const begin, int const end)

// base condition

if (begin >= end)

return;

auto mid = begin + (end - begin) / 2;

mergeSort(array, begin, mid);

mergeSort(array, mid + 1, end);


merge(array, begin, mid, end);

// Print Array

void print_array(int A[], int size)

for (auto i = 0; i < size; i++)

cout << A[i] << " ";

int main()

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

auto arr_size = sizeof(arr) / sizeof(arr[0]);

cout << "Array: ";

print_array(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);

cout << "\nSorted array: ";

print_array(arr, arr_size);

return 0;

Output
Array: 5 6 3 10 1 4 9

Sorted array: 1 3 4 5 6 9 10

67. Write a Program to Implement Quick Sort


 C++

// C++ Program to implement

// QuickSort

#include <iostream>

using namespace std;

// Swap elements
void swap(int* a, int* b)

int t = *a;

*a = *b;

*b = t;

// Partition function to check pivot location

int partition(int arr[], int low, int high)

int pivot = arr[high]; // pivot

int i = (low - 1);

for (int j = low; j <= high - 1; j++) {

// If current element is smaller than the pivot

if (arr[j] < pivot) {

i++;
swap(&arr[i], &arr[j]);

swap(&arr[i + 1], &arr[high]);

return (i + 1);

// Quick Sort function

void quickSort(int arr[], int low, int high)

if (low < high) {

// pi is partitioning index, arr[p] is now

// at right place

int pi = partition(arr, low, high);

// Separately sort elements before

// partition and after partition


quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

// Print Array

void printArray(int arr[], int size)

int i;

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

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

cout << endl;

int main()

int arr[] = { 2, 5, 6, 9, 1, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Array: ";

printArray(arr, n);

quickSort(arr, 0, n - 1);

cout << "Sorted array: ";

printArray(arr, n);

return 0;

Output
Array: 2 5 6 9 1 3 4

Sorted array: 1 2 3 4 5 6 9

68. Write a Program to Implement Linear Search


 C++

// C++ Program to implement

// Linear Sort
#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;

int main()

int arr[] = { 5, 4, 1, 6, 10, 9, 23, 2 };

int x = 9;

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


int result = search(arr, N, x);

if (result == -1)

cout << "Element is not present in array";

else

cout << "Element is present at index " << result;

return 0;

Output
Element is present at index 5

69. Write a Program to Implement Binary Search

 C++

// C++ program to implement

// Binary Search

#include <iostream>

using namespace std;


// Binary Search Function

int binarySearch(int arr[], int l, int r, int x)

if (r >= l) {

// Middle element

int mid = l + (r - l) / 2;

if (arr[mid] == x)

return mid;

if (arr[mid] > x)

return binarySearch(arr, l, mid - 1, x);

return binarySearch(arr, mid + 1, r, x);

}
// We reach here when element is not

// present in array

return -1;

int main(void)

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

int x = 5;

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

int result = binarySearch(arr, 0, n - 1, x);

if (result == -1)

cout << "Element is not present in array";

else

cout << "Element is present at index " << result;


return 0;

Output
Element is present at index 4

70. Write a Program to Find the Index of a Given Element in a


Vector
 C++

// C++ program to find the index

// of an element in a vector

#include <bits/stdc++.h>

using namespace std;

// print index of element

void print_index(vector<int> v, int element)

auto it = find(v.begin(), v.end(), element);


// Condition if element found

if (it != v.end()) {

// Calculating the index

// of element

int index = it - v.begin();

cout << index << endl;

// No such element in vector

else {

cout << "-1" << endl;

int main()

vector<int> v = { 1, 2, 3, 4, 5, 6 };
int element = 5;

print_index(v, element);

return 0;

Output
4

71. Write a Program to Remove Duplicate Elements in an Array


Using STL
 C++

// C++ program to remove the

// duplicate elements from the array

// using STL in C++

#include <bits/stdc++.h>

using namespace std;


// Function to remove duplicate elements

void removeDuplicates(int arr[], int n)

int i;

set<int> s;

// Insert the array elements

// into the set

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

s.insert(arr[i]);

set<int>::iterator it;

// Print the array with duplicates removed


cout << "\nAfter removing duplicates:\n";

for (it = s.begin(); it != s.end(); ++it)

cout << *it << " ";

cout << '\n';

int main()

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

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

// Print array

cout << "\nBefore removing duplicates:\n";

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

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


removeDuplicates(arr, n);

return 0;

Output
Before removing duplicates:

1 2 2 4 3 3 2 1

After removing duplicates:

1 2 3 4

72. Write a Program to Sort an Array in Descending Order Using


STL
 C++

// C++ program to sort Array

// in descending order

#include <bits/stdc++.h>

using namespace std;

int main()

{
// Get the array

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

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

// Sort the array in descending order

sort(arr, arr + n, greater<int>());

// Print the array

cout << "\nDescending Sorted Array:";

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


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

return 0;

Output
Array: 1 2 3 4 5 6

Descending Sorted Array:6 5 4 3 2 1

73. Write a Program to Calculate the Frequency of Each Word in the


Given String
 C++

// C++ program to calculate

// frequency of each word

// in given string

#include <bits/stdc++.h>

using namespace std;

// Function to print frequency of each word

void printFrequency(string str)


{

map<string, int> M;

string word = "";

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

// if element is empty

if (str[i] == ' ') {

// If the current word

// is not found then insert

// current word with frequency 1

if (M.find(word) == M.end()) {

M.insert(make_pair(word, 1));

word = "";

}
else {

M[word]++;

word = "";

else

word += str[i];

// Storing the last word of the string

if (M.find(word) == M.end())

M.insert(make_pair(word, 1));

// Update the frequency

else

M[word]++;
// Traverse the map

for (auto& it : M) {

cout << it.first << " - " << it.second << endl;

int main()

string str = "Geeks For Geeks is for Geeks";

printFrequency(str);

return 0;

Output
For - 1

Geeks - 3

for - 1

is - 1
74. Write a Program to Find k Maximum Elements of an Array in
the Original Order
 C++

// C++ program to find k Maximum elements

#include <bits/stdc++.h>

using namespace std;

// Function to print k Maximum elements

void printMax(int arr[], int n, int k)

int result[n], c[n];

// Coping the array a

// into c and initialising

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

c[i] = arr[i];

result[i] = 0;

}
for (int i = 0; i < k; i++) {

int maxi = INT_MIN;

int index;

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

if (arr[j] > maxi) {

maxi = arr[j];

index = j;

// Assigning 1 in order

// to mark the position

// of all k maximum numbers

result[index] = 1;

arr[index] = INT_MIN;

}
// Printing elements

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

if (result[i] == 1)

cout << c[i] << " ";

int main()

int arr[] = { 50, 8, 45, 12, 25, 40, 84 };

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

int k = 3;

printMax(arr, n, k);

return 0;

Output
50 45 84
75. Write a Program to Find All Unique Subsets of a Given Set Using
STL
 C++

// C++ code for the above approach:

#include <bits/stdc++.h>

using namespace std;

void solve(vector<int>& arr, int n, set<vector<int> >& ans,

vector<int> v, int i)

// Base Condition

if (i >= n) {

ans.insert(v);

return;

solve(arr, n, ans, v, i + 1);


v.push_back(arr[i]);

solve(arr, n, ans, v, i + 1);

vector<vector<int> > AllSubsets(vector<int> arr, int n)

// Set of vectors to store

// required unique subsets

set<vector<int> > ans;

sort(arr.begin(), arr.end());

vector<int> v;

solve(arr, n, ans, v, 0);

// Vector of vectors to store final result


vector<vector<int> > res;

while (!ans.empty()) {

res.push_back(*ans.begin());

ans.erase(ans.begin());

return res;

// Print Function

void print(int N, vector<int>& A)

vector<vector<int> > result = AllSubsets(A, N);

// printing the output

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

cout << '(';

for (int j = 0; j < result[i].size(); j++) {


cout << result[i][j];

if (j < result[i].size() - 1)

cout << " ";

cout << "), ";

cout << "\n";

int main()

int N = 3;

vector<int> A = { 1, 2, 3 };

print(N, A);

return 0;

Output
(), (1), (1 2), (1 2 3), (1 3), (2), (2 3), (3),

76. Write a Program to Iterate Over a Queue Without Removing the


Element
 C++

// C++ program to iterate a

// STL Queue by Creating

// copy of given queue

#include <iostream>

#include <queue>

using namespace std;

int main()

queue<int> q;

// Inserting elements in queue

q.push(1);

q.push(2);

q.push(3);

q.push(4);
q.push(5);

// Copy queue

queue<int> copy_queue = q;

cout << "Queue elements :\n";

while (!copy_queue.empty()) {

cout << copy_queue.front() << " ";

copy_queue.pop();

return 0;

Output
Queue elements :

1 2 3 4 5
77. Write a Program for the Implementation of Stacks Using an
Array
 C++

// C++ Program to implement stacks using array

#include <iostream>

using namespace std;

// Maximum size of stack

#define MAX 100

class Stack {

private:

int top;

// Array to store stack elements

int arr[MAX];

public:
// Constructor to initialize top as -1

Stack() { top = -1; }

// Function to push an element to the stack

void push(int x)

if (top == MAX - 1) {

cout << "Stack overflow" << endl;

return;

arr[++top] = x;

// Function to pop an element from the stack

int pop()

if (top == -1) {
cout << "Stack underflow" << endl;

return -1;

return arr[top--];

// Function to check if stack is empty

bool isEmpty() { return (top == -1); }

// Function to return the top element of the stack

int peek()

if (top == -1) {

cout << "Stack is empty" << endl;

return -1;

return arr[top];
}

};

int main()

Stack s;

s.push(1);

s.push(2);

s.push(3);

s.push(4);

s.push(5);

cout << "Popped element: " << s.pop() << endl;

cout << "Top element: " << s.peek() << endl;

return 0;

Output
Popped element: 5

Top element: 4

78. Write a Program for the Implementation of a Queue Using an


Array
 C++

// C++ Program to implement queue using array

#include <iostream>

using namespace std;

// Maximum size of the queue

#define MAX 100

class Queue {

private:

int front, rear;

// Array to store queue elements

int arr[MAX];

public:
// Constructor to initialize front and rear as -1

Queue() { front = rear = -1; }

// Function to add an element to the queue

void enqueue(int x)

if (rear == MAX - 1) {

cout << "Error: Queue overflow" << endl;

return;

arr[++rear] = x;

if (front == -1)

front = 0;

// Function to remove an element from the queue

int dequeue()
{

if (front == -1) {

cout << "Queue underflow" << endl;

return -1;

int x = arr[front];

if (front == rear)

front = rear = -1;

else

front++;

return x;

// Function to check if queue is empty

bool isEmpty() { return (front == -1); }

// Function to return the front element of the queue


int peek()

if (front == -1) {

cout << "Queue is empty" << endl;

return -1;

return arr[front];

};

int main()

Queue q;

q.enqueue(1);

q.enqueue(2);

q.enqueue(3);

q.enqueue(4);
q.enqueue(5);

cout << "Dequeued element: " << q.dequeue() << endl;

cout << "Front element: " << q.peek() << endl;

return 0;

Output
Dequeued element: 1

Front element: 2

79. Write a Program Implementation of Stacks Using a Queue


 C++

// C++ Program to implement

// Stack using queue

#include <bits/stdc++.h>

using namespace std;


class Stack {

queue<int> q1, q2;

public:

void push(int x)

// Push x first in empty q2

q2.push(x);

// Push all the remaining

// elements in q1 to q2.

while (!q1.empty()) {

q2.push(q1.front());

q1.pop();

// swap the names of two queues


queue<int> q = q1;

q1 = q2;

q2 = q;

void pop()

// if no elements are there in q1

if (q1.empty())

return;

q1.pop();

int top()

if (q1.empty())

return -1;
return q1.front();

int size() { return q1.size(); }

};

int main()

Stack s;

// Inserting elements in Stack

s.push(1);

s.push(2);

s.push(3);

s.push(4);

cout << "Size: " << s.size() << endl;


cout << s.top() << endl;

s.pop();

cout << s.top() << endl;

s.pop();

cout << s.top() << endl;

cout << "Size: " << s.size() << endl;

return 0;

Output
Size: 4

Size: 2

80. Write a Program to Implement a Stack Using the List in STL


 C++

// C++ Program to implement

// stack using list


#include <bits/stdc++.h>

using namespace std;

// Template declared

template <typename T> class Stack {

public:

list<T> l;

int cs = 0;

// current size of the stack

// pushing an element into the stack

void push(T d)

cs++;

// increasing the current size of the stack

l.push_front(d);
}

// popping an element from the stack

void pop()

if (cs <= 0) {

// cannot pop us stack does not contain an

// elements

cout << "Stack empty" << endl;

else {

// decreasing the current size of the stack

cs--;

l.pop_front();

}
// if current size is 0 then stack is empty

bool empty() { return cs == 0; }

// getting the element present at the top of the stack

T top() { return l.front(); }

int size()

// getting the size of the stack

return cs;

// printing the elements of the stack

void print()

for (auto x : l) {

cout << x << endl;

}
}

};

int main()

// Inserting elements in stack

Stack<int> s;

s.push(1);

s.push(2);

s.push(3);

s.push(4);

cout << "Size: " << s.size() << endl;

cout << "Top element:" << s.top() << endl;

s.pop();

cout << "Top element:" << s.top() << endl;

s.pop();

cout << "Top element:" << s.top() << endl;


cout << "Size:" << s.size() << endl;

return 0;

Output
Size: 4

Top element:4

Top element:3

Top element:2

Size:2

81. Write a Program to Determine Array is a Subset of Another


Array or Not
 C++

// C++ Program to check if

// Array is a subset of another array or not

#include <iostream>

using namespace std;

bool isSubset(int arr1[], int arr2[], int m, int n)


{

int i = 0;

int j = 0;

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

for (j = 0; j < m; j++) {

if (arr2[i] == arr1[j])

break;

if (j == m)

return 0;

return 1;

int main()
{

int arr1[] = { 1, 11, 31, 21, 30, 17 };

int arr2[] = { 11, 30, 17, 1 };

int m = sizeof(arr1) / sizeof(arr1[0]);

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

if (isSubset(arr1, arr2, m, n))

cout << "arr2 is subset of arr1 ";

else

cout << "arr2 is not a subset of arr1";

return 0;

Output
arr2 is subset of arr1

82. Write a Program for Finding the Circular Rotation of an Array


by K Positions
 C++
// C++ Program for Finding

// Circular rotation of an array

// by K positions

#include <iostream>

using namespace std;

void Rotate(int arr[], int k, int n)

// temp array

int temp[n];

// Keepig track of the current index

// of temp[]

int t = 0;

// Storing the n - d elements of

// array arr[] to the front of temp[]


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

temp[t] = arr[i];

t++;

// Storing the first d elements of array arr[]

// into temp

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

temp[t] = arr[i];

t++;

// Copying the elements of temp[] in arr[]

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

arr[i] = temp[i];

}
void print_array(int arr[], int n)

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

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

int main()

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

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

int k = 2;

// Function calling

Rotate(arr, k, N);

print_array(arr, N);
return 0;

Output
3 4 5 1 2

83. Write a Program to Sort the First Half in Ascending Order and
the Second Half in Descending
 C++

// C++ Program to Sort first half

// in ascending order and second half in descending

#include <iostream>

using namespace std;

void ascDecFunc(int a[], int n)

int temp;

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

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


if (a[j] > a[j + 1]) {

temp = a[j];

a[j] = a[j + 1];

a[j + 1] = temp;

for (int j = n / 2; j < n - 1; j++) {

if (a[j] < a[j + 1]) {

temp = a[j];

a[j] = a[j + 1];

a[j + 1] = temp;

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


cout << a[i] << " ";

int main()

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

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

ascDecFunc(arr, len);

return 0;

Output
1 2 3 4 8 7 6 5

84. Write a Program to Print the Given String in Reverse Order


 C++

// C++ program to demonstrate reverse

// of a string using Last to First


#include <iostream>

using namespace std;

void reverse(string str)

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

cout << str[i];

int main(void)

string str = "GeeksforGeeks";

reverse(str);

return (0);

Output
skeeGrofskeeG

85. Write a Program to Print All Permutations of a String Using


Recursion
 C++

// C++ Program to Print

// Permutaions of string

#include <iostream>

#include <string>

using namespace std;

void permute(string s, string answer)

if (s.length() == 0) {

cout << answer << endl;

return;

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

char ch = s[i];

string left = s.substr(0, i);


string right = s.substr(i + 1);

string result = left + right;

permute(result, answer + ch);

int main()

string s = "ABC";

string answer = "";

permute(s, answer);

return 0;

Output
ABC

ACB

BAC

BCA
CAB

CBA

86. Write a Program to Print All Permutations of a Given String in


Lexicographically Sorted Order
 C++

// C++ Program to Print all permutations

// Of a given string in lexicographically sorted order

#include <bits/stdc++.h>

using namespace std;

int compare(const void* a, const void* b)

return (*(char*)a - *(char*)b);

void swap(char* a, char* b)

char t = *a;

*a = *b;
*b = t;

int findCeil(char str[], char first, int l, int h)

int ceilIndex = l;

for (int i = l + 1; i <= h; i++)

if (str[i] > first && str[i] < str[ceilIndex])

ceilIndex = i;

return ceilIndex;

void Permutations(char str[])

int size = strlen(str);


qsort(str, size, sizeof(str[0]), compare);

bool isFinished = false;

while (!isFinished) {

cout << str << endl;

int i;

for (i = size - 2; i >= 0; --i)

if (str[i] < str[i + 1])

break;

if (i == -1)

isFinished = true;

else {

int ceilIndex

= findCeil(str, str[i], i + 1, size - 1);


swap(&str[i], &str[ceilIndex]);

qsort(str + i + 1, size - i - 1, sizeof(str[0]),

compare);

int main()

char str[] = "XYZ";

Permutations(str);

return 0;

Output
XYZ

XZY

YXZ

YZX

ZXY

ZYX
87. Write a Program to Remove Brackets From an Algebraic
Expression
 C++

// C++ Program to remove brackets from an algebraic exp

#include <iostream>

#include <string>

using namespace std;

string remove_brackets(string str)

string result = "";

for (char c : str) {

if (c != '(' && c != ')') {

result += c;

return result;
}

int main()

string str = "Geeks)(for)(geeks";

cout << "Without brackets: " << remove_brackets(str)

<< endl;

return 0;

88. Program to Perform Insert, Delete, and Print Operations Singly


Linked List
 C++

// C++ Program to perform insertion, deletion, and print

// operations in LL

#include <iostream>
using namespace std;

struct Node {

int data;

Node* next;

};

Node* head = nullptr;

// Function to insert node in LL

void insert(int data)

Node* newNode = new Node();

newNode->data = data;

newNode->next = head;

head = newNode;
}

// function to delete node of LL

void deleteNode(int data)

Node *temp = head, *prev = nullptr;

if (temp != nullptr && temp->data == data) {

head = temp->next;

delete temp;

return;

while (temp != nullptr && temp->data != data) {

prev = temp;

temp = temp->next;

if (temp == nullptr)

return;

prev->next = temp->next;
delete temp;

// function to print LL

void printList()

Node* temp = head;

while (temp != nullptr) {

cout << temp->data << " ";

temp = temp->next;

cout << endl;

int main()

insert(1);
insert(2);

insert(3);

insert(4);

insert(5);

cout << "Linked List is \n";

printList();

deleteNode(3);

cout << "Linked List after deletion of 3: ";

printList();

return 0;

Output
Linked List is

5 4 3 2 1

Linked List after deletion of 3: 5 4 2 1

89. Program to Perform Insert, Delete, and Print Operations Doubly


Linked List
 C++
// C++ Program to implement insert, delete, and print

// operation in doubly linked list

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

Node* prev;

};

class DoublyLinkedList {

private:

Node* head;

public:
DoublyLinkedList()

: head(NULL)

void insertAtStart(int data)

Node* newNode = new Node;

newNode->data = data;

newNode->next = head;

newNode->prev = NULL;

if (head != NULL)

head->prev = newNode;

head = newNode;

}
void deleteNode(int data)

Node* temp = head;

while (temp != NULL && temp->data != data)

temp = temp->next;

if (temp == NULL)

return;

if (temp->prev != NULL)

temp->prev->next = temp->next;

else

head = temp->next;

if (temp->next != NULL)

temp->next->prev = temp->prev;
delete temp;

void printList()

Node* temp = head;

while (temp != NULL) {

std::cout << temp->data << " ";

temp = temp->next;

std::cout << std::endl;

};

int main()

{
DoublyLinkedList dll;

dll.insertAtStart(1);

dll.insertAtStart(2);

dll.insertAtStart(3);

dll.insertAtStart(4);

dll.insertAtStart(5);

std::cout << "Original Doubly Linked List: ";

dll.printList();

dll.deleteNode(2);

std::cout << "Doubly Linked List after deletion: ";

dll.printList();

return 0;
}

Output
Original Doubly Linked List: 5 4 3 2 1

Doubly Linked List after deletion: 5 4 3 1

90. Program to Perform Insert, Delete, and Print Operations


Circular Linked List
 C++

// C++ Program to implement insert, delete, and print in

// circular linked list

#include <iostream>

struct Node {

int data;

Node* next;

};

class CircularLinkedList {

private:
Node* head;

public:

CircularLinkedList()

: head(NULL)

void insertAtStart(int data)

Node* newNode = new Node;

newNode->data = data;

newNode->next = head;

if (head == NULL) {

head = newNode;

newNode->next = head;
}

else {

Node* temp = head;

while (temp->next != head)

temp = temp->next;

temp->next = newNode;

head = newNode;

void deleteNode(int data)

Node* temp = head;

if (temp == NULL)

return;

if (temp->next == head) {
head = NULL;

delete temp;

return;

Node* prev = NULL;

while (temp->next != head && temp->data != data) {

prev = temp;

temp = temp->next;

if (temp->data != data)

return;

prev->next = temp->next;

if (temp == head)

head = temp->next;
delete temp;

void printList()

Node* temp = head;

while (temp->next != head) {

std::cout << temp->data << " ";

temp = temp->next;

std::cout << temp->data << std::endl;

};

int main()

CircularLinkedList cll;
cll.insertAtStart(1);

cll.insertAtStart(2);

cll.insertAtStart(3);

cll.insertAtStart(4);

cll.insertAtStart(5);

std::cout << "Original Circular Linked list ";

cll.printList();

cll.deleteNode(2);

std::cout << "Circular Linked List after deletion ";

cll.printList();

return 0;

Output
Original Circular Linked list 5 4 3 2 1

Circular Linked List after deletion 5 4 3 1

91. Program for Inorder Traversal in a Binary Tree


 C++

// C++ program Inorder Traversal

#include <bits/stdc++.h>

using namespace std;

/* A binary tree node has data, pointer to left child

and a pointer to right child */

struct Node {

int data;

struct Node *left, *right;

};

// Utility function to create a new tree node

Node* newNode(int data)


{

Node* temp = new Node;

temp->data = data;

temp->left = temp->right = NULL;

return temp;

/* Given a binary tree, print its nodes in inorder*/

void printInorder(struct Node* node)

if (node == NULL)

return;

/* first recur on left child */

printInorder(node->left);

/* then print the data of node */


cout << node->data << " ";

/* now recur on right child */

printInorder(node->right);

int main()

struct Node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

// Function call

cout << "Inorder traversal of binary tree is \n";

printInorder(root);
return 0;

Output
Inorder traversal of binary tree is

4 2 5 1 3

92. Program to Find All its Subsets From a Set of Positive Integers
 C++

// C++ Program to find all subsets from the given set of

// positive integers

#include <bits/stdc++.h>

using namespace std;

void find_subset(vector<int>& A, vector<vector<int> >& ans,

vector<int>& subset, int index)

ans.push_back(subset);
for (int i = index; i < A.size(); i++) {

subset.push_back(A[i]);

find_subset(A, ans, subset, i + 1);

subset.pop_back();

return;

vector<vector<int> > subsets(vector<int>& A)

vector<int> subset;

vector<vector<int> > ans;

int index = 0;

find_subset(A, ans, subset, index);


return ans;

int main()

vector<int> array = { 1, 2, 3, 4, 5 };

vector<vector<int> > ans = subsets(array);

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

for (int j = 0; j < ans[i].size(); j++)

cout << ans[i][j] << " ";

cout << endl;

return 0;
}

Output
1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

1 2 3 5

1 2 4

1 2 4 5

1 2 5

1 3

1 3 4

1 3 4 5

1 3 5

1 4

1 4 5

1 5

2 3

2 3 4

2 3 4 5

2 3 5

2 4

2 4 5
2 5

3 4

3 4 5

3 5

4 5

93. Program for Preorder Traversal in a Binary Tree


 C++

// C++ program for preorder traversal

#include <bits/stdc++.h>

using namespace std;

/* A binary tree node has data, pointer to left child

and a pointer to right child */

struct Node {

int data;

struct Node *left, *right;

};
// Utility function to create a new tree node

Node* newNode(int data)

Node* temp = new Node;

temp->data = data;

temp->left = temp->right = NULL;

return temp;

/* Given a binary tree, print its nodes in preorder*/

void printPreorder(struct Node* node)

if (node == NULL)

return;

/* first print data of node */


cout << node->data << " ";

/* then recur on left subtree */

printPreorder(node->left);

/* now recur on right subtree */

printPreorder(node->right);

int main()

struct Node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);
// Function call

cout << "Preorder traversal of binary tree is \n";

printPreorder(root);

return 0;

Output
Preorder traversal of binary tree is

1 2 4 5 3

94. Program for Postorder Traversal in a Binary Tree


 C++

// C++ program for post order traversal

#include <bits/stdc++.h>

using namespace std;

/* A binary tree node has data, pointer to left child

and a pointer to right child */

struct Node {
int data;

struct Node *left, *right;

};

// Utility function to create a new tree node

Node* newNode(int data)

Node* temp = new Node;

temp->data = data;

temp->left = temp->right = NULL;

return temp;

/* Given a binary tree, print its nodes according to the

"bottom-up" postorder traversal. */

void printPostorder(struct Node* node)

{
if (node == NULL)

return;

// first recur on left subtree

printPostorder(node->left);

// then recur on right subtree

printPostorder(node->right);

// now deal with the node

cout << node->data << " ";

int main()

struct Node* root = newNode(1);

root->left = newNode(2);
root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

// Function call

cout << "Postorder traversal of binary tree is \n";

printPostorder(root);

return 0;

Output
Postorder traversal of binary tree is

4 5 2 3 1

95. Program for Level-Order Traversal in a Binary Tree


 C++

// C++ program for post order traversal

#include <bits/stdc++.h>

using namespace std;


/* A binary tree node has data, pointer to left child

and a pointer to right child */

struct Node {

int data;

struct Node *left, *right;

};

// Utility function to create a new tree node

Node* newNode(int data)

Node* temp = new Node;

temp->data = data;

temp->left = temp->right = NULL;

return temp;

}
/* Given a binary tree, print its nodes according to the

"bottom-up" postorder traversal. */

void printLevelOrder(struct Node* node)

if (node == NULL)

return;

queue<struct Node*> q;

while (node) {

if (node->left) {

q.push(node->left);

if (node->right) {

q.push(node->right);

cout << node->data << " ";

node = q.front();

q.pop();
}

int main()

struct Node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

// Function call

cout << "Levelorder traversal of binary tree is \n";

printLevelOrder(root);

return 0;

Output
Levelorder traversal of binary tree is

1 2 3 4 5

96. Write a Program for the Top View of a Binary Tree


 C++

// C++ program for top view of a binary tree

#include <bits/stdc++.h>

using namespace std;

// node data type

struct Node {

Node* left;

Node* right;

int hd;

int data;

};

// utility function to create new node

Node* newNode(int key)


{

Node* node = new Node();

node->left = node->right = NULL;

node->data = key;

return node;

// function to print top view of a binary tree

void topView(Node* root)

if (root == NULL) {

return;

queue<Node*> q;

map<int, int> m;

int hd = 0;

root->hd = hd;
q.push(root);

while (q.size()) {

hd = root->hd;

if (m.count(hd) == 0)

m[hd] = root->data;

if (root->left) {

root->left->hd = hd - 1;

q.push(root->left);

if (root->right) {

root->right->hd = hd + 1;

q.push(root->right);

q.pop();
root = q.front();

// printing top view

for (auto i = m.begin(); i != m.end(); i++) {

cout << i->second << " ";

// Driver code

int main()

// new binary tree

Node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);
root->right->right = newNode(5);

topView(root);

return 0;

Output
4 2 1 3 5

97. Write a Program to Print the Bottom View of a Binary Tree


 C++

// C++ program for bottom view of a binary tree

#include <bits/stdc++.h>

using namespace std;

// node data type

struct Node {

Node* left;

Node* right;

int data;
int hd;

};

// utility function for new node

Node* newNode(int key)

Node* node = new Node();

node->data = key;

node->left = node->right = NULL;

node->hd = 0;

return node;

// function to print bottom view

void bottomView(Node* root)

{
if (root == NULL)

return;

queue<Node*> q;

map<int, int> m;

int hd = 0;

root->hd = hd;

q.push(root);

while (!q.empty()) {

Node* temp = q.front();

q.pop();

hd = temp->hd;
m[hd] = temp->data;

if (temp->left != NULL) {

temp->left->hd = hd - 1;

q.push(temp->left);

if (temp->right != NULL) {

temp->right->hd = hd + 1;

q.push(temp->right);

// printing top view

for (auto i = m.begin(); i != m.end(); ++i)

cout << i->second << " ";

}
// Driver Code

int main()

Node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->right->right = newNode(5);

bottomView(root);

return 0;

Output
4 2 1 3 5

98. Write a Program to Print the Left View of a Binary Tree


 C++

// C++ program to print left view of a binary tree


#include <bits/stdc++.h>

using namespace std;

// node datatype

struct Node {

Node* left;

Node* right;

int data;

};

// utility function to create a new node

Node* newNode(int key)

Node* node = new Node;

node->data = key;

node->left = node->right = NULL;

return node;
}

// function to print left view

void leftView(Node* root)

if (!root) {

return;

queue<Node*> q;

q.push(root);

while (!q.empty()) {

int n = q.size();

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

Node* temp = q.front();


q.pop();

if (i == 1)

cout << temp->data << " ";

if (temp->left != NULL)

q.push(temp->left);

if (temp->right != NULL)

q.push(temp->right);

// Driver code

int main()

{
Node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->right->right = newNode(5);

leftView(root);

Output
1 2 4

99. Write a Program to Print the Right View of the Binary Tree
 C++

// C++ program to print the right view of a binary tree

#include <bits/stdc++.h>

using namespace std;

// node data type


struct Node {

Node* left;

Node* right;

int data;

};

// utility function to create new node

Node* newNode(int key)

Node* node = new Node;

node->data = key;

node->left = node->right = NULL;

return node;

// function to print right view of a binary tree

void rightView(Node* root)


{

if (root == NULL) {

return;

queue<Node*> q;

q.push(root);

while (!q.empty()) {

int n = q.size();

while (n--) {

Node* x = q.front();

q.pop();
if (n == 0) {

cout << x->data << " ";

if (x->left) {

q.push(x->left);

if (x->right) {

q.push(x->right);

// Driver code

int main()

{
Node* root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->right->right = newNode(5);

rightView(root);

Output
1 3 5

100. Write a Program for the Conversion of Infix Expression to


Postfix Expression
 C++

// C++ program for infix expression to postfix expression

// conversion

#include <bits/stdc++.h>

using namespace std;


// infix to postfix conversion

// supported operators => + - * /

string infixToPostfix(string& expression)

// string to store postfix expression

string postfix;

// operator stack

stack<char> ope_stack;

// operator precedence map

unordered_map<char, int> pre = { { '+', 1 },

{ '-', 1 },

{ '*', 2 },

{ '/', 2 },

{ '(', 0 } };

int length = expression.length();


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

char c = expression[i];

// checking operands

if ((c >= 92 && c <= 122) || (c >= 48 && c <= 57)) {

postfix.push_back(c);

// checking braces

else if (c == '(') {

ope_stack.push(c);

else if (c == ')') {

while (ope_stack.top() != '(') {

postfix.push_back(ope_stack.top());

ope_stack.pop();

ope_stack.pop();

}
// checking operators

else {

while (!ope_stack.empty()

&& pre.at(c) < pre.at(ope_stack.top())) {

postfix.push_back(ope_stack.top());

ope_stack.pop();

ope_stack.push(c);

// popping whole stack at the end

while (!ope_stack.empty()) {

postfix.push_back(ope_stack.top());

ope_stack.pop();

}
return postfix;

// driver code

int main()

string s = "a*b+(c-d)";

cout << infixToPostfix(s);

return 0;

Output
ab*cd-+

Conclusion
Coding interviews can be challenging task, but they are also a great
opportunity to test your skills and knowledge. By practicing with commonly
ask C++ coding interview questions, you can increase your chances of
success.
Remember to stay calm, communicate your thought process clearly, and
don’t be afraid to ask for clarification if needed. With hard work and
preparation, you can ace your interview and land your dream job!
C++ Coding Interview Questions – FAQs

Q: What are the most common C++ coding interview questions?

The most common C++ coding interview questions are designed to test your
knowledge of the following topics:
 C++ syntax and semantics
 Data structures and algorithms
 Object-oriented programming
 Memory management
 Pointers
 Templates & More.

Q: What should I do during a C++ coding interview?

When you are asked a coding question in an interview, take a moment to


think about the problem before you start coding. Explain your thought
process to the interviewer as you are coding. This will help them to
understand your approach to solving problems.

Q: What are some tips for writing clean and efficient code?

Here are some tips for writing clean and efficient code:
 Use meaningful variable names.
 Use whitespace to make your code readable.
 Break down complex problems into smaller, more manageable problems.
 Use comments to explain your code.
 Test your code thoroughly.
 Use appropriate data structures and algorithms.
 Avoid unnecessary duplication of code.

Q: How can I improve my communication skills during C++ coding


interviews?

Here are some tips for improving your communication skills during C++
coding interviews:
 Speak clearly and concisely.
 Explain your thought process to the interviewer.
 Ask clarifying questions if needed.
 Be prepared to answer questions about your code.
 Be open to feedback.

You might also like