30 OOPs Interview Questions and Answers
30 OOPs Interview Questions and Answers
Answers (2024)
Last Updated : 15 Jun, 2024
OOPs is also one of the most important topics for programming interviews.
This article contains some top interview questions on the OOPs concept.
// defining class
class Student {
public:
string name;
};
int main()
{
// creating object
Student student1;
// assigning member some value
student1.name = "Rahul";
return 0;
}
Output
student1.name: Rahul
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 code is easier to maintain and Proper planning is required because OOPs is a
update. little bit tricky.
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.
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
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.
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"; }
}
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
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++
// negative
#include <iostream>
int main()
int number;
number = -100;
if (number >= 0) {
cout << number << " is a positive number." << endl;
else {
return 0;
Output
-100 is a negative number.
#include <iostream>
int main()
{
int a = 10, b = 20, c = 30;
else {
return 0;
Output
The Greatest Among Three Numbers is : 30
3. C++ Program To Check Whether Number is Even Or Odd
C++
#include <iostream>
// Returns true if n is
// Driver code
int main()
int n = 247;
if (isEven(n) == true) {
}
else {
return 0;
Output
Odd
#include <iostream>
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
#include <cctype>
#include <iostream>
char ch = 'e';
if (isalpha(ch)) {
else {
else {
}
return 0;
Output
e is a vowel.
// or not
#include <cctype>
#include <iostream>
int main()
char ch;
ch = 'a';
if (isalpha(ch)) {
else {
return 0;
Output
a is an alphabet.
// strlen()
#include <cstring>
#include <iostream>
int main()
int length = 0;
length++;
cout << "The length of the string is: " << length
<< endl;
return 0;
}
Output
The length of the string is: 13
#include <cstring>
#include <iostream>
int main()
if (islower(str[i])) {
str[i] = toupper(str[i]);
}
else if (isupper(str[i])) {
str[i] = tolower(str[i]);
return 0;
Output
Toggled string: gEEKSFORgEEKS
#include <cstring>
#include <iostream>
int vowels = 0;
|| str[i] == 'U') {
vowels++;
<< endl;
return 0;
Output
Number of vowels in the string: 9
#include <cstring>
#include <iostream>
int main()
int j = 0;
str[j++] = str[i];
str[j] = '\0';
j++;
cout << "String without vowels: " << str << endl;
return 0;
Output
String without vowels: GksfrGks
// alphabets
#include <cctype>
#include <iostream>
#include <string>
if (isalpha(c)) {
result += c;
return result;
int main()
<< endl;
return 0;
Output
Alphabets only: Geeksforgeeks
#include <iostream>
#include <string>
if (c != ' ') {
result += c;
return result;
}
int main()
<< endl;
return 0;
Output
Without spaces: Gfgtothemoon
13. Write a Program to Find the Sum of the First N Natural Numbers
C++
// Sum of first
// n natural numbers.
#include <iostream>
int findSum(int n)
int sum = 0;
sum = sum + i;
return sum;
int main()
int n = 7;
return 0;
}
Output
28
#include <bits/stdc++.h>
int factorial(int n)
int fact = 1;
while (n > 1) {
fact *= n;
n--;
}
return fact;
// driver code
int main()
int num = 5;
return 0;
Output
120
// leap year
if (year % 400 == 0)
return true;
if (year % 100 == 0)
return false;
// leap year
if (year % 4 == 0)
return true;
// Not leap year
return false;
int main()
if (checkYear(year))
else
return 0;
Output
Leap Year
// Number is prime
#include <iostream>
bool isPrime(int n)
// base condition
if (n <= 1)
return false;
if (n % i == 0)
return false;
return true;
}
int main()
return 0;
Output
false
true
#include <iostream>
bool checkPalindrome(int n)
int ans = 0;
int temp = n;
while (temp != 0) {
int main()
int n = 12321;
if (checkPalindrome(n) == 1) {
else {
return 0;
Output
Yes
// 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
while (n > 0) {
n = n / 10;
}
// condition to check
if (temp == ans) {
else {
return 0;
Output
Yes, it is Armstrong Number
19. Write a Program to Find the Nth Term of the Fibonacci Series
C++
#include <iostream>
if (n == 0)
return first;
first = second;
second = ans;
return ans;
int main()
{
int n = 13;
return 0;
Output
233
#include <iostream>
break;
result--;
return result;
int main()
return 0;
Output
GCD: 3
// C++ program to
#include <iostream>
if (b == 0)
return a;
return gcd(b, a % b);
return result;
int main()
return 0;
Output
LCM : 312
22. Write a Program for Finding the Roots of a Quadratic Equation
C++
#include <iostream>
#include <math.h>
if (a == 0) {
return;
// Formulae to calculate D
int d = b * b - 4 * a * c;
// Formulae to calculate
// square root of D
if (d > 0) {
else if (d == 0) {
else {
cout << "Roots are complex \n";
int main()
int a = 1, b = 4, c = 4;
findRoots(a, b, c);
return 0;
Output
Roots are real and same
-2
#include <iostream>
maxi = arr[i];
int main()
int arr[] = { 1, 2, 3, 4, 5 };
findMinMax(arr, N);
return 0;
Output
Min: 1
Max: 5
#include <climits>
#include <iostream>
return;
second = first;
first = arr[i];
second = arr[i];
if (second == INT_MAX)
else
<< endl;
int main()
print2Smallest(arr, n);
return 0;
Output
Second smallest element is 10
#include <iostream>
int sum = 0;
sum += arr[i];
return sum;
int main()
return 0;
Output
Sum: 99
#include <iostream>
string isPalindrome(string S)
return "No";
return "Yes";
int main()
{
string S = "GeekeeG";
return 0;
Output
Yes
#include <iostream>
int count1[NO_OF_CHARS] = { 0 };
int count2[NO_OF_CHARS] = { 0 };
int i;
count1[str1[i]]++;
count2[str2[i]]++;
if (str1[i] || str2[i])
return false;
if (count1[i] != count2[i])
return false;
return true;
int main()
if (areAnagram(str1, str2))
else
cout << "The two strings are not anagram of each "
"other";
return 0;
Output
The two strings are not anagram of each other
C++
// Diamond shape
#include <iostream>
void printDiamond(int n)
{
int space = n - 1;
space--;
space = 0;
// Print i stars
space++;
int main()
printDiamond(5);
return 0;
}
Output
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
C++
// C++ Program to
#include <iostream>
int k = 2 * n - 2;
k = k - 1;
// Printing stars
}
}
int main()
int n = 5;
pattern(n);
return 0;
Output
*
* *
* * *
* * * *
* * * * *
C++
#include <iostream>
// assigning comparator
int comp;
if (i < rows) {
comp = 2 * i + 1;
}
else {
comp = 2 * (2 * rows - i) - 3;
}
int main()
hourglass(5);
return 0;
Output
* * * * * * * * *
* * * * * * *
* * * * *
* * *
* * *
* * * * *
* * * * * * *
* * * * * * * * *
C++
#include <iostream>
void pattern(int n)
}
int spaces = 2 * (n - i);
int main()
int n = 5;
pattern(n);
return 0;
Output
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * *
* * * *
* *
#include <iostream>
int rows = 5;
return 0;
Output
*
***
*****
*******
*********
#include <iostream>
int main()
int rows = 5;
}
for (int k = 1; k <= (2 * i - 1); k++) {
return 0;
Output
*********
*******
*****
***
#include <iostream>
int rows;
rows = 5;
return 0;
Output
*
**
***
****
*****
C++
#include <stdio.h>
int main()
int rows = 4;
int n = 1;
printf("\n");
return 0;
Output
1
2 3
4 5 6
7 8 9 10
C++
#include <iostream>
void printPascal(int n)
int arr[n][n];
if (line == i || i == 0)
arr[line][i] = 1;
else
+ arr[line - 1][i];
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
#include <cstring>
#include <iostream>
int main()
int len;
len = str.size();
cout << "Reverse of the string: ";
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
// recursion
#include <iostream>
if (n <= i) {
return;
swap(s[i], s[n]);
reverse_str(s, n - 1, i + 1);
int main()
Output
skeeGrofskeeG
// Is palindrome or not
#include <bits/stdc++.h>
if (s == n)
return true;
if (str[s] != str[n])
return false;
if (s < n + 1)
return true;
int n = strlen(str);
if (n == 0)
return true;
}
int main()
if (isPalindrome(str))
else
return 0;
Output
Yes
#include <iostream>
// base condition
if (*str == '\0')
return 0;
else
int main()
Output
13
#include <iostream>
if (n == 0 || n == 1)
return 1;
}
int main()
return 0;
Output
Factorial of 15 is 1307674368000
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int sum = 0;
if (isdigit(ch)) {
sum += ch - '0';
return sum;
int main()
string str;
str = "1234";
<< endl;
return 0;
Output
Sum of numbers: 10
#include <iostream>
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
#include <iostream>
int x = 3;
int y = 4;
x = x + y;
y = x - y;
x = x - y;
return 0;
Output
X : 3
Y : 4
After:
X : 4
Y : 3
// unsigned int.
#include <iostream>
max = 0;
max = ~max;
return 0;
Output
Max value possible : 4294967295
int main()
if (a ^ b)
else
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
#include <iostream>
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
#include <cmath>
#include <iostream>
int main()
oct = 67;
while (temp) {
int lastDigit = temp % 10;
temp /= 10;
++place;
cout << "Decimal equivalent is: " << dec << endl;
return 0;
Output
Decimal equivalent is: 55
#include <cmath>
#include <iostream>
using namespace std;
return -1;
int main()
{
string hex;
hex = "67";
int n = hex.length();
place++;
return 0;
Output
Decimal equivalent 103
#include <bitset>
#include <iostream>
int main()
int decimal = 7;
bitset<32> binary(decimal);
Output
Binary equivalent: 00000000000000000000000000000111
#include <cmath>
#include <iostream>
int main()
decimal = 55;
int temp = decimal;
while (temp) {
temp /= 8;
place *= 10;
return 0;
Output
Octal equivalent 67
#include <cmath>
#include <iostream>
#include <string>
char hexaDecimals[16]
decimal /= 16;
return hexadecimal;
}
int main()
return 0;
Output
Hexadecimal equivalent: 67
// to octal number
#include <bits/stdc++.h>
using namespace std;
(*um)["000"] = '0';
(*um)["001"] = '1';
(*um)["010"] = '2';
(*um)["011"] = '3';
(*um)["100"] = '4';
(*um)["101"] = '5';
(*um)["110"] = '6';
(*um)["111"] = '7';
int l = bin.size();
int t = bin.find_first_of('.');
int len_left = t != -1 ? t : l;
if (t != -1) {
createMap(&bin_oct_map);
int i = 0;
while (1) {
i += 3;
if (i == bin.size())
break;
if (bin.at(i) == '.') {
octal += '.';
i++;
return octal;
}
// Driver program to test above
int main()
return 0;
Output
Octal number = 1712241.26633
#include <iostream>
// Function to convert an
// Octal to Binary Number
long int i = 0;
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()
return 0;
Output
Equivalent Binary Value = 011100101
#include <iostream>
class Encapsulation {
private:
int x;
public:
// variable x
void setter(int a) { x = a; }
// variable x
};
int main()
Encapsulation obj;
obj.setter(13);
Output
13
// Working of Abstraction
#include <iostream>
class implementAbstraction {
private:
int p, q;
public:
p = x;
q = y;
void display()
};
int main()
implementAbstraction obj;
obj.setter(1, 2);
obj.display();
return 0;
Output
p = 1
q = 2
// Function overloading or
// Compile-time Polymorphism
#include <iostream>
public:
// Parameters
void func(int x)
void func(double x)
{
cout << "value of x and y is " << x << ", " << y
<< endl;
};
int main()
Geeks obj1;
obj1.func(10);
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
// Operator Overloading
#include <iostream>
class Complex {
private:
Complex(int r = 0, int i = 0)
real = r;
imag = i;
Complex res;
return res;
}
void print() { cout << real << " + " << imag << "i\n"; }
};
int main()
Complex c3 = c1 + c2;
c3.print();
Output
18 + 10i
// of Function Overloading or
class base {
public:
};
public:
};
int main()
base* bptr;
derived d;
bptr = &d;
bptr->print();
// at compile time
bptr->show();
return 0;
Output
print derived class
#include <iostream>
#include <string.h>
class Person {
int id;
char name[100];
public:
{
strcpy(this->name, name);
this->id = id;
void display_p()
cout << endl << id << "\t" << name << "\t";
};
char course[50];
int fee;
public:
{
set_p(id, name);
strcpy(this->course, course);
this->fee = fee;
void display_s()
display_p();
};
main()
{
Student s;
s.display_s();
return 0;
Output
132451 XYZ ABC 100000
#include <bits/stdc++.h>
struct c {
double real;
double img;
};
// complex clss
class Complex {
private:
struct c num;
public:
// constructors
Complex() {}
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;
// overloaded operators
{
Complex var;
return var;
Complex var;
return var;
{
Complex var;
- num.img * obj1.num.img;
+ num.img * obj1.num.real;
return var;
};
// driver code
int main()
Complex c;
c = a + b;
a.print();
b.print();
c.print();
return 0;
Output
11 + i12
5 + i8
16 + i20
#include <bits/stdc++.h>
struct c {
double feet;
double inch;
};
// inchFeet class
class inchFeet {
private:
struct c length;
public:
// constructors
inchFeet() {}
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
// overloaded operators
inchFeet operator+(inchFeet& obj1)
inchFeet var;
var.length.feet++;
var.length.inch - 12.0;
return var;
inchFeet var;
temp.feet--;
temp.inch += 12;
else {
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
// of Bubble sort
#include <iostream>
// Function to sort
int i, j;
// in place
int i;
int main()
int arr[] = { 3, 1, 4, 2, 5 };
bubbleSort(arr, N);
printArray(arr, N);
return 0;
Output
Sorted array: 1 2 3 4 5
// Insertion sort
#include <bits/stdc++.h>
// Insertion
int i, key, j;
key = arr[i];
j = i - 1;
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
// Print array
int main()
int arr[] = { 1, 4, 3, 2, 5 };
insertion_sort(arr, N);
print_array(arr, N);
return 0;
Output
Sorted array:1 2 3 4 5
// Selection sort
#include <iostream>
// Swap function
*p = *q;
*q = temp;
int min_index;
min_index = i;
for (int j = i + 1; j < n; j++)
min_index = j;
if (min_index != i)
swap(&arr[min_index], &arr[i]);
// Print Array
int i;
int main()
int arr[] = { 5, 4, 3, 2, 1 };
selectionSort(arr, n);
printArray(arr, n);
return 0;
Output
Sorted array: 1 2 3 4 5
// Merge Sort
#include <iostream>
if (leftArray[indexOfSubArrayOne]
<= rightArray[indexOfSubArrayTwo]) {
array[indexOfMergedArray]
= leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
else {
array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
array[indexOfMergedArray]
= leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
indexOfMergedArray++;
array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
delete[] leftArray;
delete[] rightArray;
// base condition
return;
// Print Array
int main()
print_array(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
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
// QuickSort
#include <iostream>
// Swap elements
void swap(int* a, int* b)
int t = *a;
*a = *b;
*b = t;
i++;
swap(&arr[i], &arr[j]);
return (i + 1);
// at right place
quickSort(arr, pi + 1, high);
// Print Array
int i;
int main()
int arr[] = { 2, 5, 6, 9, 1, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
quickSort(arr, 0, n - 1);
printArray(arr, n);
return 0;
Output
Array: 2 5 6 9 1 3 4
Sorted array: 1 2 3 4 5 6 9
// Linear Sort
#include <iostream>
int i;
if (arr[i] == x)
return i;
return -1;
int main()
int x = 9;
if (result == -1)
else
return 0;
Output
Element is present at index 5
C++
// Binary Search
#include <iostream>
if (r >= l) {
// Middle element
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > 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;
if (result == -1)
else
Output
Element is present at index 4
// of an element in a vector
#include <bits/stdc++.h>
if (it != v.end()) {
// of element
else {
int main()
vector<int> v = { 1, 2, 3, 4, 5, 6 };
int element = 5;
print_index(v, element);
return 0;
Output
4
#include <bits/stdc++.h>
int i;
set<int> s;
s.insert(arr[i]);
set<int>::iterator it;
int main()
int arr[] = { 1, 2, 2, 4, 3, 3, 2, 1 };
// Print array
return 0;
Output
Before removing duplicates:
1 2 2 4 3 3 2 1
1 2 3 4
// in descending order
#include <bits/stdc++.h>
int main()
{
// Get the array
int arr[] = { 1, 2, 3, 4, 5, 6 };
return 0;
Output
Array: 1 2 3 4 5 6
// in given string
#include <bits/stdc++.h>
map<string, int> M;
// if element is empty
if (M.find(word) == M.end()) {
M.insert(make_pair(word, 1));
word = "";
}
else {
M[word]++;
word = "";
else
word += str[i];
if (M.find(word) == M.end())
M.insert(make_pair(word, 1));
else
M[word]++;
// Traverse the map
for (auto& it : M) {
cout << it.first << " - " << it.second << endl;
int main()
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++
#include <bits/stdc++.h>
c[i] = arr[i];
result[i] = 0;
}
for (int i = 0; i < k; i++) {
int index;
maxi = arr[j];
index = j;
// Assigning 1 in order
result[index] = 1;
arr[index] = INT_MIN;
}
// Printing elements
if (result[i] == 1)
int main()
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++
#include <bits/stdc++.h>
vector<int> v, int i)
// Base Condition
if (i >= n) {
ans.insert(v);
return;
sort(arr.begin(), arr.end());
vector<int> v;
while (!ans.empty()) {
res.push_back(*ans.begin());
ans.erase(ans.begin());
return res;
// Print Function
if (j < result[i].size() - 1)
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),
#include <iostream>
#include <queue>
int main()
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
// Copy queue
queue<int> copy_queue = q;
while (!copy_queue.empty()) {
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++
#include <iostream>
class Stack {
private:
int top;
int arr[MAX];
public:
// Constructor to initialize top as -1
void push(int x)
if (top == MAX - 1) {
return;
arr[++top] = x;
int pop()
if (top == -1) {
cout << "Stack underflow" << endl;
return -1;
return arr[top--];
int peek()
if (top == -1) {
return -1;
return arr[top];
}
};
int main()
Stack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
return 0;
Output
Popped element: 5
Top element: 4
#include <iostream>
class Queue {
private:
int arr[MAX];
public:
// Constructor to initialize front and rear as -1
void enqueue(int x)
if (rear == MAX - 1) {
return;
arr[++rear] = x;
if (front == -1)
front = 0;
int dequeue()
{
if (front == -1) {
return -1;
int x = arr[front];
if (front == rear)
else
front++;
return x;
if (front == -1) {
return -1;
return arr[front];
};
int main()
Queue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(5);
return 0;
Output
Dequeued element: 1
Front element: 2
#include <bits/stdc++.h>
public:
void push(int x)
q2.push(x);
// elements in q1 to q2.
while (!q1.empty()) {
q2.push(q1.front());
q1.pop();
q1 = q2;
q2 = q;
void pop()
if (q1.empty())
return;
q1.pop();
int top()
if (q1.empty())
return -1;
return q1.front();
};
int main()
Stack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.pop();
s.pop();
return 0;
Output
Size: 4
Size: 2
// Template declared
public:
list<T> l;
int cs = 0;
void push(T d)
cs++;
l.push_front(d);
}
void pop()
if (cs <= 0) {
// elements
else {
cs--;
l.pop_front();
}
// if current size is 0 then stack is empty
int size()
return cs;
void print()
for (auto x : l) {
}
}
};
int main()
Stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.pop();
s.pop();
return 0;
Output
Size: 4
Top element:4
Top element:3
Top element:2
Size:2
#include <iostream>
int i = 0;
int j = 0;
if (arr2[i] == arr1[j])
break;
if (j == m)
return 0;
return 1;
int main()
{
else
return 0;
Output
arr2 is subset of arr1
// by K positions
#include <iostream>
// temp array
int temp[n];
// of temp[]
int t = 0;
temp[t] = arr[i];
t++;
// into temp
temp[t] = arr[i];
t++;
arr[i] = temp[i];
}
void print_array(int arr[], int n)
int main()
int arr[] = { 1, 2, 3, 4, 5 };
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++
#include <iostream>
int temp;
temp = a[j];
a[j + 1] = temp;
temp = a[j];
a[j + 1] = temp;
int main()
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
ascDecFunc(arr, len);
return 0;
Output
1 2 3 4 8 7 6 5
int main(void)
reverse(str);
return (0);
Output
skeeGrofskeeG
// Permutaions of string
#include <iostream>
#include <string>
if (s.length() == 0) {
return;
char ch = s[i];
int main()
string s = "ABC";
permute(s, answer);
return 0;
Output
ABC
ACB
BAC
BCA
CAB
CBA
#include <bits/stdc++.h>
char t = *a;
*a = *b;
*b = t;
int ceilIndex = l;
ceilIndex = i;
return ceilIndex;
while (!isFinished) {
int i;
break;
if (i == -1)
isFinished = true;
else {
int ceilIndex
compare);
int main()
Permutations(str);
return 0;
Output
XYZ
XZY
YXZ
YZX
ZXY
ZYX
87. Write a Program to Remove Brackets From an Algebraic
Expression
C++
#include <iostream>
#include <string>
result += c;
return result;
}
int main()
<< endl;
return 0;
// operations in LL
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
newNode->data = data;
newNode->next = head;
head = newNode;
}
head = temp->next;
delete temp;
return;
prev = temp;
temp = temp->next;
if (temp == nullptr)
return;
prev->next = temp->next;
delete temp;
// function to print LL
void printList()
temp = temp->next;
int main()
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
printList();
deleteNode(3);
printList();
return 0;
Output
Linked List is
5 4 3 2 1
#include <iostream>
struct Node {
int data;
Node* next;
Node* prev;
};
class DoublyLinkedList {
private:
Node* head;
public:
DoublyLinkedList()
: head(NULL)
newNode->data = data;
newNode->next = head;
newNode->prev = NULL;
if (head != NULL)
head->prev = newNode;
head = newNode;
}
void deleteNode(int 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()
temp = temp->next;
};
int main()
{
DoublyLinkedList dll;
dll.insertAtStart(1);
dll.insertAtStart(2);
dll.insertAtStart(3);
dll.insertAtStart(4);
dll.insertAtStart(5);
dll.printList();
dll.deleteNode(2);
dll.printList();
return 0;
}
Output
Original Doubly Linked List: 5 4 3 2 1
#include <iostream>
struct Node {
int data;
Node* next;
};
class CircularLinkedList {
private:
Node* head;
public:
CircularLinkedList()
: head(NULL)
newNode->data = data;
newNode->next = head;
if (head == NULL) {
head = newNode;
newNode->next = head;
}
else {
temp = temp->next;
temp->next = newNode;
head = newNode;
if (temp == NULL)
return;
if (temp->next == head) {
head = NULL;
delete temp;
return;
prev = temp;
temp = temp->next;
if (temp->data != data)
return;
prev->next = temp->next;
if (temp == head)
head = temp->next;
delete temp;
void printList()
temp = temp->next;
};
int main()
CircularLinkedList cll;
cll.insertAtStart(1);
cll.insertAtStart(2);
cll.insertAtStart(3);
cll.insertAtStart(4);
cll.insertAtStart(5);
cll.printList();
cll.deleteNode(2);
cll.printList();
return 0;
Output
Original Circular Linked list 5 4 3 2 1
#include <bits/stdc++.h>
struct Node {
int data;
};
temp->data = data;
return temp;
if (node == NULL)
return;
printInorder(node->left);
printInorder(node->right);
int main()
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
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++
// positive integers
#include <bits/stdc++.h>
ans.push_back(subset);
for (int i = index; i < A.size(); i++) {
subset.push_back(A[i]);
subset.pop_back();
return;
vector<int> subset;
int index = 0;
int main()
vector<int> array = { 1, 2, 3, 4, 5 };
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
#include <bits/stdc++.h>
struct Node {
int data;
};
// Utility function to create a new tree node
temp->data = data;
return temp;
if (node == NULL)
return;
printPreorder(node->left);
printPreorder(node->right);
int main()
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
printPreorder(root);
return 0;
Output
Preorder traversal of binary tree is
1 2 4 5 3
#include <bits/stdc++.h>
struct Node {
int data;
};
temp->data = data;
return temp;
{
if (node == NULL)
return;
printPostorder(node->left);
printPostorder(node->right);
int main()
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
printPostorder(root);
return 0;
Output
Postorder traversal of binary tree is
4 5 2 3 1
#include <bits/stdc++.h>
struct Node {
int data;
};
temp->data = data;
return temp;
}
/* Given a binary tree, print its nodes according to the
if (node == NULL)
return;
queue<struct Node*> q;
while (node) {
if (node->left) {
q.push(node->left);
if (node->right) {
q.push(node->right);
node = q.front();
q.pop();
}
int main()
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
printLevelOrder(root);
return 0;
Output
Levelorder traversal of binary tree is
1 2 3 4 5
#include <bits/stdc++.h>
struct Node {
Node* left;
Node* right;
int hd;
int data;
};
node->data = key;
return node;
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();
// Driver code
int main()
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
#include <bits/stdc++.h>
struct Node {
Node* left;
Node* right;
int data;
int hd;
};
node->data = key;
node->hd = 0;
return node;
{
if (root == NULL)
return;
queue<Node*> q;
map<int, int> m;
int hd = 0;
root->hd = hd;
q.push(root);
while (!q.empty()) {
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);
}
// Driver Code
int main()
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
// node datatype
struct Node {
Node* left;
Node* right;
int data;
};
node->data = key;
return node;
}
if (!root) {
return;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
if (i == 1)
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++
#include <bits/stdc++.h>
Node* left;
Node* right;
int data;
};
node->data = key;
return node;
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) {
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
// conversion
#include <bits/stdc++.h>
string postfix;
// operator stack
stack<char> ope_stack;
{ '-', 1 },
{ '*', 2 },
{ '/', 2 },
{ '(', 0 } };
char c = expression[i];
// checking operands
postfix.push_back(c);
// checking braces
else if (c == '(') {
ope_stack.push(c);
else if (c == ')') {
postfix.push_back(ope_stack.top());
ope_stack.pop();
ope_stack.pop();
}
// checking operators
else {
while (!ope_stack.empty()
postfix.push_back(ope_stack.top());
ope_stack.pop();
ope_stack.push(c);
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)";
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
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 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.
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.