Explore the latest coding questions for C++ interviews with our updated guide for 2024. This comprehensive guide is perfect for both novice and experienced developers. This curated list of top C++ coding interview questions and answers provides essential insights for mastering technical interviews. This guidance will you give deep knowledge of interview pattern questions and also help you in securing your dream job in the dynamic field of software development or as a c++ developer.
Understanding C++
C++ is an Object-oriented programming language , which belongs to the “C” family of languages, was created by prominent computer scientist Bjorne Stroustrop. To give programs more granular control across memory and system resources, it was created as a cross-platform enhancement to “C”.
The programming language that all coders must know and love is C++. It remains as current as it was during the middle of the 1980s. It is generally routinely utilized when coding because it is a general-purpose, goal-oriented programming language.
Top IT businesses like Evernote, LinkedIn, Microsoft, Opera, NASA, and Meta all use it due to its reliability, efficiency, and variety of possible configurations.
Advantages of using C++ Programming Language
- Object-Oriented: Since C++ Programming Language is an object-oriented programming language, entities and the changes that take place close to them are the central objective. Contrary to conventional or hierarchical programming, which calls for a number of operational steps to be completed, this allows it much simpler to alter code.
- Speed: The best choice is C programming language when efficiency is a top priority. Compared to other general-purpose programming languages, C++ programs generate and execute much faster.
- Rich Library Support: The C++ Standard Template Library (STL) has a number of features that can help you write code very quickly. For instance, STLs are available for a variety of categories, such as collections, hash tables, and maps.
Top C++ Questions and Answers for Beginners
1. Write a function to reverse a string in C++.
#include <iostream>
#include <string>
using namespace std;
string reverseString(string str) {
int n = str.length();
for (int i = 0; i < n / 2; i++) {
swap(str[i], str[n - i - 1]);
}
return str;
}
int main() {
string s = "hello";
cout << "Reversed String: " << reverseString(s) << endl;
return 0;
}
2. Write a function to check if a given string is a palindrome or not.
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str[left] != str[right])
return false;
left++;
right--;
}
return true;
}
int main() {
string s = "radar";
cout << "Is Palindrome: " << (isPalindrome(s) ? "Yes" : "No") << endl;
return 0;
}
3. Write a function to check if two strings are anagrams of each other.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isAnagram(string s1, string s2) {
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
return s1 == s2;
}
int main() {
string str1 = "listen";
string str2 = "silent";
cout << "Are Anagrams: " << (isAnagram(str1, str2) ? "Yes" : "No") << endl;
return 0;
}
4. Write a function to generate the Fibonacci series up to a certain number of terms.
#include <iostream>
using namespace std;
void fibonacci(int n) {
int a = 0, b = 1, c;
cout << "Fibonacci Series: ";
for (int i = 0; i < n; i++) {
cout << a << " ";
c = a + b;
a = b;
b = c;
}
}
int main() {
int terms = 10;
fibonacci(terms);
return 0;
}
5. Write a function to calculate the factorial of a number.
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
return n * factorial(n - 1);
}
int main() {
int num = 5;
cout << "Factorial of " << num << ": " << factorial(num) << endl;
return 0;
}
6. Implement the binary search algorithm to find an element in a sorted array.
#include <iostream>
using namespace std;
int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int index = binarySearch(arr, size, target);
if (index != -1)
cout << "Element found at index: " << index << endl;
else
cout << "Element not found" << endl;
return 0;
}
7. Implement the merge sort algorithm to sort an array of integers.
#include <iostream>
using namespace std;
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j])
arr[k++] = L[i++];
else
arr[k++] = R[j++];
}
while (i < n1)
arr[k++] = L[i++];
while (j < n2)
arr[k++] = R[j++];
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, size - 1);
cout << "Sorted array: ";
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
return 0;
}
8. Implement basic operations like insertion, deletion, and traversal in a linked list.
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val) {
data = val;
next = nullptr;
}
};
class LinkedList {
public:
Node* head;
LinkedList() {
head = nullptr;
}
void insert(int val) {
Node* newNode = new Node(val);
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next)
temp = temp->next;
temp->next = newNode;
}
void display() {
Node* temp = head;
while (temp) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void deleteNode(int val) {
if (!head)
return;
if (head->data == val) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* temp = head;
while (temp->next && temp->next->data != val)
temp = temp->next;
if (temp->next) {
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
}
}
};
int main() {
LinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.display(); // Output: 1 2 3
9. Implement tree traversal algorithms like inorder, preorder, and postorder traversal.
#include <iostream>
using namespace std;
class TreeNode {
public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int value) {
val = value;
left = nullptr;
right = nullptr;
}
};
void inorderTraversal(TreeNode* root) {
if (!root) return;
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
void preorderTraversal(TreeNode* root) {
if (!root) return;
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void postorderTraversal(TreeNode* root) {
if (!root) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
cout << "Inorder Traversal: ";
inorderTraversal(root);
cout << endl;
cout << "Preorder Traversal: ";
preorderTraversal(root);
cout << endl;
cout << "Postorder Traversal: ";
postorderTraversal(root);
cout << endl;
return 0;
}
10. Implement a stack data structure and its basic operations (push, pop, isEmpty, peek).
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
class Stack {
private:
int arr[MAX_SIZE];
int top;
public:
Stack() {
top = -1;
}
bool isEmpty() {
return top == -1;
}
void push(int value) {
if (top == MAX_SIZE - 1) {
cout << "Stack Overflow" << endl;
return;
}
arr[++top] = value;
}
void pop() {
if (isEmpty()) {
cout << "Stack Underflow" << endl;
return;
}
top--;
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty" << endl;
return -1;
}
return arr[top];
}
};
int main() {
Stack stack;
stack.push(1);
stack.push(2);
stack.push(3);
cout << "Top element: " << stack.peek() << endl;
stack.pop();
cout << "Top element after popping: " << stack.peek() << endl;
return 0;
}
11. Implement a queue data structure and its basic operations (enqueue, dequeue, isEmpty, peek).
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
class Queue {
private:
int arr[MAX_SIZE];
int front, rear;
public:
Queue() {
front = -1;
rear = -1;
}
bool isEmpty() {
return front == -1;
}
bool isFull() {
return (rear + 1) % MAX_SIZE == front;
}
void enqueue(int value) {
if (isFull()) {
cout << "Queue Overflow" << endl;
return;
}
if (isEmpty())
front = rear = 0;
else
rear = (rear + 1) % MAX_SIZE;
arr[rear] = value;
}
void dequeue() {
if (isEmpty()) {
cout << "Queue Underflow" << endl;
return;
}
if (front == rear)
front = rear = -1;
else
front = (front + 1) % MAX_SIZE;
}
int peek() {
if (isEmpty()) {
cout << "Queue is empty" << endl;
return -1;
}
return arr[front];
}
};
int main() {
Queue queue;
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
cout << "Front element: " << queue.peek() << endl;
queue.dequeue();
cout << "Front element after dequeue: " << queue.peek() << endl;
return 0;
}
12. Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
#include <iostream>
#include <vector>
using namespace std;
int findMissingNumber(vector<int>& nums) {
int n = nums.size();
int total = (n + 1) * (n + 2) / 2;
for (int num : nums)
total -= num;
return total;
}
int main() {
vector<int> nums = {3, 0, 1, 4, 6, 2};
cout << "Missing number: " << findMissingNumber(nums) << endl;
return 0;
}
13. Find the contiguous subarray with the largest sum in an array.
#include <iostream>
#include <vector>
using namespace std;
int maxSubArraySum(vector<int>& nums) {
int maxSum = INT_MIN, currentSum = 0;
for (int num : nums) {
currentSum = max(num, currentSum + num);
maxSum = max(maxSum, currentSum);
}
return maxSum;
}
int main() {
vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
cout << "Maximum Subarray Sum: " << maxSubArraySum(nums) << endl;
return 0;
}
14. Implement basic matrix operations like addition, multiplication, and transpose.
#include <iostream>
#include <vector>
using namespace std;
// Function to add two matrices
vector<vector<int>> matrixAddition(vector<vector<int>>& A, vector<vector<int>>& B) {
int m = A.size(), n = A[0].size();
vector<vector<int>> result(m, vector<int>(n));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
result[i][j] = A[i][j] + B[i][j];
return result;
}
// Function to multiply two matrices
vector<vector<int>> matrixMultiplication(vector<vector<int>>& A, vector<vector<int>>& B) {
int m1 = A.size(), n1 = A[0].size(), m2 = B.size(), n2 = B[0].size();
vector<vector<int>> result(m1, vector<int>(n2, 0));
for (int i = 0; i < m1; i++)
for (int j = 0; j < n2; j++)
for (int k = 0; k < n1; k++)
result[i][j] += A[i][k] * B[k][j];
return result;
}
// Function to transpose a matrix
vector<vector<int>> matrixTranspose(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> result(n, vector<int>(m));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
result[j][i] = matrix[i][j];
return result;
}
int main() {
vector<vector<int>> A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
vector<vector<int>> B = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
cout << "Matrix A:" << endl;
for (const auto& row : A) {
for (int val : row)
cout << val << " ";
cout << endl;
}
cout << "Matrix B:" << endl;
for (const auto& row : B) {
for (int val : row)
cout << val << " ";
cout << endl;
}
vector<vector<int>> sum = matrixAddition(A, B);
cout << "Matrix A + B:" << endl;
for (const auto& row : sum) {
for (int val : row)
cout << val << " ";
cout << endl;
}
vector<vector<int>> product = matrixMultiplication(A, B);
cout << "Matrix A * B:" << endl;
for (const auto& row : product) {
for (int val : row)
cout << val << " ";
cout << endl;
}
vector<vector<int>> transposeA = matrixTranspose(A);
cout << "Transpose of Matrix A:" << endl;
for (const auto& row : transposeA) {
for (int val : row)
cout << val << " ";
cout << endl;
}
return 0;
}
15. Implement DFS algorithm for graph traversal.
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Graph {
int V;
vector<unordered_set<int>> adj;
public:
Graph(int V) : V(V), adj(V) {}
void addEdge(int u, int v) {
adj[u].insert(v);
adj[v].insert(u); // For undirected graph
}
void DFSUtil(int v, vector<bool>& visited) {
visited[v] = true;
cout << v << " ";
for (int u : adj[v]) {
if (!visited[u])
DFSUtil(u, visited);
}
}
void DFS(int start) {
vector<bool> visited(V, false);
DFSUtil(start, visited);
}
};
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
cout << "Depth First Traversal starting from vertex 0: ";
g.DFS(0);
cout << endl;
return 0;
}
16. Implement BFS algorithm for graph traversal.
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
using namespace std;
class Graph {
int V;
vector<unordered_set<int>> adj;
public:
Graph(int V) : V(V), adj(V) {}
void addEdge(int u, int v) {
adj[u].insert(v);
adj[v].insert(u); // For undirected graph
}
void BFS(int start) {
vector<bool> visited(V, false);
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int v = q.front();
q.pop();
cout << v << " ";
for (int u : adj[v]) {
if (!visited[u]) {
visited[u] = true;
q.push(u);
}
}
}
}
};
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
cout << "Breadth First Traversal starting from vertex 0: ";
g.BFS(0);
cout << endl;
return 0;
}
17. Write a function to tokenize a string based on a delimiter.
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
vector<string> tokenizeString(const string& str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter))
tokens.push_back(token);
return tokens;
}
int main() {
string input = "hello,world,this,is,C++,programming";
char delimiter = ',';
vector<string> tokens = tokenizeString(input, delimiter);
cout << "Tokens:";
for (const string& token : tokens)
cout << " " << token;
cout << endl;
return 0;
}
18. Find the duplicate element in an array of integers where each element is between 1 and n, with n being the length of the array.
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int findDuplicate(vector<int>& nums) {
unordered_set<int> seen;
for (int num : nums) {
if (seen.find(num) != seen.end())
return num;
seen.insert(num);
}
return -1; // No duplicates found
}
int main() {
vector<int> nums = {1, 3, 4, 2, 2};
cout << "Duplicate element: " << findDuplicate(nums) << endl;
return 0;
}
19. Reverse a linked list iteratively and recursively.
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
Node* reverseIterative(Node* head) {
Node* prev = nullptr;
Node* current = head;
while (current != nullptr) {
Node* nextNode = current->next;
current->next = prev;
prev = current;
current = nextNode;
}
return prev;
}
Node* reverseRecursive(Node* head) {
if (!head || !head->next) return head;
Node* reversed = reverseRecursive(head->next);
head->next->next = head;
head->next = nullptr;
return reversed;
}
void display(Node* head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main() {
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
cout << "Original list: ";
display(head);
// Reversing iteratively
head = reverseIterative(head);
cout << "Reversed list (iterative): ";
display(head);
// Reversing recursively
head = reverseRecursive(head);
cout << "Reversed list (recursive): ";
display(head);
return 0;
}
20. Implement an LRU (Least Recently Used) cache using appropriate data structures.
#include <iostream>
#include <list>
#include <unordered_map>
using namespace std;
class LRUCache {
list<int> cache;
unordered_map<int, list<int>::iterator> mp;
int capacity;
public:
LRUCache(int capacity) : capacity(capacity) {}
void refer(int page) {
if (mp.find(page) == mp.end()) {
if (cache.size() == capacity) {
int last = cache.back();
cache.pop_back();
mp.erase(last);
}
}
else
cache.erase(mp[page]);
cache.push_front(page);
mp[page] = cache.begin();
}
void display() {
for (auto it = cache.begin(); it != cache.end(); it++)
cout << (*it) << " ";
cout << endl;
}
};
int main() {
LRUCache cache(4);
cache.refer(1);
cache.refer(2);
cache.refer(3);
cache.refer(1);
cache.refer(4);
cache.refer(5);
cout << "LRU Cache: ";
cache.display();
return 0;
}
Read our other Interview-related articles:
- iOS Interview Questions
- Angular Interview Questions
- Android Interview Questions
- Full Stack Interview Questions
- Python Interview Questions
Conclusion
After going through these C++ interviews and viva questions and answers, you must have gained some understanding of some crucial C++ Programming languages. These C++ programming questions are a few questions that can be very useful during the C++ interview process.
We would suggest you be prepared well before having your C++ interview rounds. An interview can only be done well when you have all the knowledge of a particular topic. C++ is a very wide field, so having a great knowledge of the field is very important.
FAQs
Ans. Yes. C++, one of the most popular languages, has great demand which will eventually increase, so you should definitely learn C++.
Ans. Diagnostics Library, General Utilities Library, Standard String Templates, Localization Classes and Templates, The Containers, Iterators, and Algorithms Libraries, The Standard Numerics Library, The Standard Input/Output Library.
Ans. Programmer, Software Developer, Quality Analyst, Software Developer, C++ Analyst, and Programming Architect are a few choices that you can opt for after learning C++.