Top 30 C++ Coding Interview Questions and Answers
C++ is one of the most widely used object-oriented programming languages. Developed by Bjarne Stroustrup at Bell Labs, it is a powerful and versatile tool for various applications, from game development to system programming. Major companies like Microsoft, LinkedIn, Amazon, and PayPal use C++, and often prioritize C++ questions in their coding interviews. This means that modern developers must master this programming language, especially those who are interested in working with big companies. This guide outlines the C++ coding interview questions and answers. Use the questions from the guide to practice C++ coding for the interview.
C++ Coding Interview Questions and Answers For Freshers
For entry-level candidates, C++ coding interview questions usually focus on fundamental concepts such as loops, arrays, pointers, and memory management. By practicing these topics, you will improve your C++ skills and also show your proficiency in C++ to potential employers. Here are some basic C++ coding interview questions and answers for freshers:
Q1. Find the largest element in an array.
Sample Answer: To find the largest element in an array, you need to iterate through the array and compare its elements. This task helps assess your understanding of basic loops and conditionals.
Here’s an example:
#include <iostream>
using namespace std;
int main() {
int arr[] = {3, 5, 7, 2, 8};
int size = sizeof(arr) / sizeof(arr[0]);
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
cout << "Largest element: " << max << endl;
return 0;
}
Q2. What is the method to reverse a string?
Sample Answer: Reversing a string involves swapping characters from the beginning with those at the end until you reach the middle of the string. This exercise tests your understanding of string manipulation and the use of loops in C++.
Here’s how you can reverse a string:
#include <iostream>
using namespace std;
void reverseString(string& str) {
int n = str.length();
for (int i = 0; i < n / 2; i++) {
swap(str[i], str[n - i - 1]);
}
}
int main() {
string str = "Hello, World!";
reverseString(str);
cout << "Reversed string: " << str << endl;
return 0;
}
Q3. How can you determine if a number is prime?
Sample Answer: To check if a number is prime, you look for factors other than 1 and itself. This classic algorithmic problem helps you practice conditional logic and loops.
Here’s how you can check if a number is prime:
#include <iostream>
#include <cmath> // Include cmath for sqrt function
using namespace std;
bool isPrime(int n) {
if (n <= 1) return false; // Numbers less than 2 are not prime
for (int i = 2; i <= sqrt(n); i++) { // Check up to the square root of n
if (n % i == 0) return false; // If n is divisible by i, it's not prime
}
return true; // If no divisors were found, it's prime
}
int main() {
int num = 29;
cout << num << " is " << (isPrime(num) ? "prime" : "not prime") << endl;
return 0;
}
Q4. What is linear search in an array and how is it implemented?
Sample Answer: Linear search is a straightforward algorithm that allows you to locate a specific element within an array. This simple coding interview question demonstrates your ability to iterate through data structures and implement search algorithms, providing a foundation for more complex searching techniques.
Here’s how you can implement linear search in an array:
#include <iostream>
using namespace std;
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) return i;
}
return -1; // Not found
}
int main() {
int arr[] = {4, 2, 3, 1, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3;
int index = linearSearch(arr, size, target);
cout << "Element found at index: " << index << endl;
return 0;
}
Q5. How do you count the number of vowels in a string?
Sample Answer: Counting vowels in a string is a practical exercise that showcases your understanding of character manipulation and loops in C++. To count vowels, iterate through the string and check each character.
Here is the code to count the number of vowels in a string:
#include <iostream>
using namespace std;
int countVowels(const string& str) {
int count = 0;
for (char c : str) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
count++;
}
}
return count;
}
int main() {
string str = "Hello, World!";
cout << "Number of vowels: " << countVowels(str) << endl;
return 0;
}
Pro Tip: Excel in C++ coding with the help of a short-term training course. Enroll in Internshala’s C++ course to develop a strong foundation in coding. The course will help you prepare for the C++ coding job interview questions and answer them confidently.
Q6. What is a bubble sort algorithm and why is it important?
Sample Answer: Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. Implementing a sorting algorithm is essential for understanding how data can be organized. Bubble sort, while not the most efficient, is one of the simplest sorting algorithms to understand.
Here’s how you can implement a bubble sort algorithm:
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
int arr[] = {5, 1, 4, 2, 8};
int size = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, size);
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Q7. How do you merge two sorted arrays?
Sample Answer: Merging involves combining two sorted arrays into a single sorted array.
Here’s how you can merge two sorted arrays:
#include <iostream>
using namespace std;
void mergeArrays(int arr1[], int size1, int arr2[], int size2) {
int mergedSize = size1 + size2;
int* merged = new int[mergedSize];
int i = 0, j = 0, k = 0;
while (i < size1 && j < size2) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < size1) merged[k++] = arr1[i++];
while (j < size2) merged[k++] = arr2[j++];
cout << "Merged array: ";
for (int m = 0; m < mergedSize; m++) {
cout << merged[m] << " ";
}
cout << endl;
delete[] merged; // Free allocated memory
}
int main() {
int arr1[] = {1, 3, 5};
int arr2[] = {2, 4, 6};
mergeArrays(arr1, 3, arr2, 3);
return 0;
}
Q8. How to find the second-largest element in an array?
Sample Answer: To find the second largest element, traverse the array while maintaining the largest and second largest values.
Here’s how you can find the second-largest element in an array:
#include <iostream>
using namespace std;
int findSecondLargest(int arr[], int size) {
int largest = INT_MIN, secondLargest = INT_MIN;
for (int i = 0; i < size; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] < largest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
int main() {
int arr[] = {3, 5, 7, 2, 8};
cout << "Second largest element: " << findSecondLargest(arr, 5) << endl;
return 0;
}
Q9. What is the method to remove duplicates from an array?
Sample Answer: Removing duplicates from an array can be achieved by using a set to store unique elements. This exercise shows your understanding of data structure and their usage.
Here is how you can remove duplicates from an array:
#include <iostream>
#include <set>
using namespace std;
void removeDuplicates(int arr[], int size) {
set<int> uniqueElements;
for (int i = 0; i < size; i++) {
uniqueElements.insert(arr[i]);
}
cout << "Array after removing duplicates: ";
for (const int& elem : uniqueElements) {
cout << elem << " ";
}
cout << endl;
}
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5};
removeDuplicates(arr, 7);
return 0;
}
Q10. How do you calculate the Fibonacci series using recursion?
Sample Answer: The Fibonacci series can be computed by defining a recursive function that calls itself for the two preceding numbers.
Here is how you can calculate the Fibonacci series using a recursion:
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int terms = 10;
cout << "Fibonacci series: ";
for (int i = 0; i < terms; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;
return 0;
}
C++ Coding Interview Questions and Answers For Mid-level Candidates
Mid-level candidates can expect questions that delve deeper into advanced topics. These questions are designed to evaluate your ability to write efficient code and solve complex problems. Here’s a list of C++ coding interview questions and answers for mid-level candidates:
Q11. Explain how to count the number of words in a string.
Sample Answer: Counting the number of words in a string means finding how many individual words are present, usually separated by spaces or punctuation. We can do this by splitting the string into words and counting them. Here’s how you can count the number of words in a string:
#include <iostream>
#include <sstream>
using namespace std;
int countWords(const string& str) {
stringstream ss(str);
string word;
int count = 0;
while (ss >> word) {
count++;
}
return count;
}
int main() {
string str = "Hello, world! Welcome to C++ programming.";
cout << "Number of words: " << countWords(str) << endl;
return 0;
}
Q12. How do you create a simple calculator?
Sample Answer: Creating a simple calculator involves basic arithmetic operations and control flow in C++. This also includes the implementation of functions such as addition, subtraction, multiplication, and division, as well as managing user input and operator selection.
Here’s an example of how you can create a simple calculator:
#include <iostream>
using namespace std;
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
if (b == 0) {
cout << "Error! Division by zero." << endl;
return 0; // Handle division by zero
}
return a / b;
}
int main() {
double num1, num2;
char operation;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
double result;
switch (operation) {
case '+': result = add(num1, num2); break;
case '-': result = subtract(num1, num2); break;
case '*': result = multiply(num1, num2); break;
case '/': result = divide(num1, num2); break;
default: cout << "Invalid operation!" << endl; return 1;
}
cout << "Result: " << result << endl;
return 0;
}
Q13. How do you find the greatest common divisor (GCD) of two numbers?
Sample Answer: Finding the greatest common divisor (GCD) of two numbers is a classic problem in number theory that can be solved using the Euclidean algorithm.
Here’s how to find the greatest common divisor (GCD) of two numbers:
#include <iostream>
using namespace std;
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1 = 56, num2 = 98;
cout << "GCD of " << num1 << " and " << num2 << " is " << gcd(num1, num2) << endl;
return 0;
}
Q14. How can you check if a string is a palindrome?
Sample Answer: To check if a string reads the same forwards and backward, we need to use loops to compare characters from both ends.
Here’s how we can check if a string is a palindrome:
#include <iostream>
using namespace std;
bool isPalindrome(const string& str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str[left] != str[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
string str = "racecar";
cout << str << (isPalindrome(str) ? " is a palindrome." : " is not a palindrome.") << endl;
return 0;
}
Q15. How do you print the factors of a number?
Sample Answer: To print factors, iterate through potential divisors and check for divisibility.
Here is how you can print the factors of a number:
#include <iostream>
using namespace std;
void printFactors(int n) {
cout << "Factors of " << n << ": ";
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
cout << i << " ";
}
}
cout << endl;
}
int main() {
int num = 28;
printFactors(num);
return 0;
}
Pro Tip: Enhance your preparation for the C++ coding job interview questions with the help of a course. Check out our how to ace coding interview course to get yourself ready for the job interview.
Q16. What is inheritance in object-oriented programming? Write a class hierarchy for different types of animals.
Sample Answer: Inheritance is a mechanism in object-oriented programming that allows a class to inherit properties and behavior from another class.
Here’s an example of class hierarchy for different types of animals:
class Animal {
public:
virtual void speak() = 0;
};
class Mammal : public Animal {
public:
virtual void giveBirth() = 0;
};
class Dog : public Mammal {
public:
void speak() override { cout << "Woof!" << endl; }
void giveBirth() override { cout << "Giving birth to puppies." << endl; }
};
class Bird : public Animal {
public:
void speak() override { cout << "Chirp!" << endl; }
};
Q17. What is a template in C++? Write a function template that returns the maximum value in an array of any type.
Sample Answer: A template is a mechanism in C++ that allows for generic programming. It enables writing functions and classes that can work with any type, without having to write separate versions for each type.
Here’s an example function template:
template <typename T>
T maxElement(T arr[], int size) {
T max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arrInt[] = {1, 2, 3, 4, 5};
double arrDouble[] = {1.1, 2.2, 3.3, 4.4, 5.5};
cout << maxElement(arrInt, 5) << endl; // Output: 5
cout << maxElement(arrDouble, 5) << endl; // Output: 5.5
return 0;
}
Q18. What is the difference between a pointer and a reference in C++? Write a function that takes a pointer to an integer and doubles its value.
Sample Answer: A pointer is a variable that stores the memory address of another variable, while a reference is an alias for an existing variable.
Here’s an example function that takes a pointer to an integer and doubles its value:
void doubleValue(int* numPtr) {
*numPtr *= 2;
}
int main() {
int x = 5;
int* xPtr = &x;
doubleValue(xPtr);
cout << x << endl; // Output: 10
return 0;
}
Q19. What is a linked list data structure? Write a function that inserts a new node at the end of a linked list.
Sample Answer: A linked list is a data structure that consists of a sequence of nodes, where each node stores a value and a pointer to the next node in the list.
Here’s an example function that inserts a new node at the end of a linked list:
struct Node {
int data;
Node* next;
};
void insertEnd(Node** head, int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
int main() {
Node* head = NULL;
insertEnd(&head, 1);
insertEnd(&head, 2);
insertEnd(&head, 3);
Node* current = head;
while (current != NULL) {
cout << current->data << " ";
current = current->next;
}
return 0;
}
Q20. How can you sort an array in ascending order in C++?
Sample Answer: Sorting an array in ascending order can be done using the built-in sort function from the C++ Standard Library or by implementing a sorting algorithm like Bubble Sort, Selection Sort, or Quick Sort.
Here’s an example using the sort function:
#include <iostream>
#include <algorithm> // For std::sort
using namespace std;
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);
// Sorting the array in ascending order
sort(arr, arr + size);
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
C++ Coding Interview Questions and Answers For Experienced Candidates
Below are the C++ coding interview questions with answers for experienced candidates. These C++ interview questions assess your ability to apply C++ and look at real-world issues that could come up during an interview.
Q21. What is the purpose of std::weak_ptr in C++? When would you use it?
Sample Answer: std::weak_ptr is a smart pointer with a non-owning reference to an object managed by std::shared_ptr. It is used to avoid circular dependencies that can lead to memory leaks. Unlike std::shared_ptr, it does not increment the reference count of the managed object.
For example:
#include <iostream>
#include <memory>
class Node {
public:
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev;
};
int main() {
auto node1 = std::make_shared<Node>();
auto node2 = std::make_shared<Node>();
node1->next = node2;
node2->prev = node1; // Use std::weak_ptr to prevent circular dependency.
return 0;
}
Here, node2->prev uses std::weak_ptr to reference node1. This breaks the circular reference and ensures proper cleanup when node1 and node2 go out of scope.
Q22. What is the difference between std::vector and std::array in C++?
Sample Answer: In C++, std::vector, and std::array are both sequence containers, but they have the following key differences:
- Dynamic vs Static Size
- std::vector is a dynamically resizable container, allowing the size to grow or shrink.
- std::array is a fixed-size container defined at compile time.
- Memory Allocation
- std::vector allocates memory dynamically on the heap.
- std::array allocates memory on the stack (if small enough).
- Performance
- std::array is faster due to static size.
- std::vector has overhead due to dynamic resizing.
Here’s an example:
#include <iostream>
#include <vector>
#include <array>
int main() {
std::vector<int> vec = {1, 2, 3};
vec.push_back(4); // Allowed
std::array<int, 3> arr = {1, 2, 3};
// arr.push_back(4); // Not allowed, fixed size
return 0;
}
Q23. How does constexpr differ from const in C++?
Sample Answer: In C++, both const and constexpr are used to define constants, but they serve different purposes.
- const: Defines a variable whose value cannot be changed after initialization, but its value can be determined at runtime.
- constexpr: Ensures that the value is evaluated at compile-time, making it usable in contexts that require constant expressions, like array sizes or template parameters.
Here’s an example to differentiate between them:
#include <iostream>
constexpr int square(int x) {
return x * x;
}
int main() {
const int runtimeConst = 5; // Determined at runtime.
constexpr int compileTimeConst = square(5); // Evaluated at compile time.
std::cout << compileTimeConst << std::endl; // Output: 25
return 0;
}
Q24. What is a lambda expression in C++? Provide an example of its use.
Sample Answer: A lambda expression in C++ is a way to define a small, anonymous function inline. It allows you to write code that is more concise and easier to read, especially when dealing with algorithms that take functions as parameters.
Here is an example of its use:
std::vector<int> numbers = { 1, 2, 3, 4, 5 };
int sum = 0;
std::for_each(numbers.begin(), numbers.end(), [&sum](int n) {
sum += n;
});
std::cout << "Sum of numbers: " << sum << std::endl;
In this example, we use a lambda expression with the std::for_each algorithm to calculate the sum of a vector of integers. The lambda expression takes an integer as input and adds it to a variable called sum, which is captured by reference. The result is printed to the console.
Q25. What is RAI in C++? Explain how it can be used to improve memory safety.
Sample Answer: RAI stands for Resource Acquisition Is Initialization, which is a design pattern in C++ that helps ensure proper resource management. The basic idea is to allocate and deallocate resources in the constructor and destructor of a class, respectively. This guarantees that the resource will be properly released, even if an exception is thrown during the lifetime of the object.
For example:
class MyFile {
public:
MyFile(const std::string& filename)
: m_file(fopen(filename.c_str(), "r"))
{
if (!m_file) {
throw std::runtime_error("Unable to open file");
}
}
~MyFile() {
if (m_file) {
fclose(m_file);
}
}
// Other methods...
private:
FILE* m_file;
};
In this example, the MyFile class uses RAI to ensure the file resource is properly released when the object goes out of scope. The file is opened in the constructor and closed in the destructor, which guarantees that it will be released even if an exception is thrown.
Pro Tip: Explore our basic coding interview questions guide to enhance your preparation.
Q26. What is the difference between std::shared_ptr and std::unique_ptr in C++? Provide an example of when you would use each.
Sample Answer: std::shared_ptr and std::unique_ptr are smart pointers in C++ that help manage dynamic memory. The main difference is that std::shared_ptr uses reference counting to keep track of how many pointers are pointing to the same object, while std::unique_ptr does not allow multiple pointers to the same object.
Here is an example of using these smart pointers in C++:
// Using std::unique_ptr
std::unique_ptr<MyClass> p1(new MyClass());
std::unique_ptr<MyClass> p2 = std::move(p1);
// Using std::shared_ptr
std::shared_ptr<MyClass> p3(new MyClass());
std::shared_ptr<MyClass> p4 = p3;
In this example, we demonstrate the use of std::unique_ptr and std::shared_ptr to manage instances of MyClass. With std::unique_ptr, ownership of the object can be transferred from p1 to p2 using std::move, ensuring that only one pointer holds ownership at a time. In contrast, std::shared_ptr enables multiple pointers to share ownership of the same object, making it ideal for situations where different parts of the program need to access and control the object.
Q27. What is an explicit constructor in C++? Provide an example.
Sample Answer: An explicit constructor prevents implicit conversions or copy-initialization. It is used to avoid unintended type conversions. The explicit keyword ensures that the constructor cannot be used for implicit type conversions, making the code more predictable. Here’s a C++ code example:
#include <iostream>
class MyClass {
public:
explicit MyClass(int x) : value(x) {}
int value;
};
int main() {
MyClass obj1(10); // Allowed
// MyClass obj2 = 20; // Error: Explicit constructor prevents implicit conversion.
return 0;
}
Q28. Describe the ‘diamond problem’ in C++ when multiple inheritance is used.
Sample Answer: The ‘diamond problem’ occurs in C++ when a derived class inherits from two base classes inherited from the same grandparent class. This creates a diamond-shaped inheritance structure. This can lead to ambiguity at compile time because the compiler may not know which path to follow to access the members of the grandparent.
For example:
Grandparent
/ \
Parent1 Parent2
\ /
Derived
To resolve the diamond problem, C++ provides virtual inheritance. By declaring the inheritance from the grandparent class as virtual in the parent classes, Derived will only have a single instance of Grandparent. This way, any ambiguity is avoided.
Q29. What distinguishes variable declaration from variable definition in C++?
Sample Answer: In C++, variable declaration and variable definition serve different purposes. Here’s a table outline the difference between variable declaration and variable definition:
Variable Declaration | Variable Definition |
Provides the compiler with the variable’s name and type. | Supplies the compiler with all necessary information, including the variable’s storage location and initialization. |
No memory is allocated. | Memory is allocated for the variable. |
Can be declared multiple times. | Can only be defined once. |
Does not include initialization or methods. | Includes initialization, fields, and methods (if applicable). |
Q30. Can you explain what a variadic template is in C++ and give an example of its use?
Sample Answer: A variadic template in C++ is a template that can accept any number of template arguments of any type. It’s defined using an ellipsis (…) and allows you to create functions or classes that can work with an arbitrary number of arguments.
A common use case for variadic templates is implementing functions like printf or std::make_shared. For example, a simple variadic function to sum any number of arguments might look like this:
template<typename T>
T sum(T t) {
return t;
}
template<typename T, typename... Args>
T sum(T first, Args... args) {
return first + sum(args...);
}
31. Fix the following code to properly swap the values of the two integer variables x and y:
int x = 5;
int y = 10;
int temp;
temp = x;
x = y;
y = temp;
cout << x << " " << y << endl;
Sample Answer: The temporary variable temp is used to swap the values. Here’s the fixed code:
int x = 5;
int y = 10;
int temp = x;
x = y;
y = temp;
cout << x << " " << y << endl;
Conclusion
Mastering C++ coding job interview questions is necessary for candidates at all experience levels. This guide provides a comprehensive overview of essential questions and answers that cover C++ concepts and coding skills. The range of questions includes fundamental concepts for entry-level candidates and advanced topics for mid-level candidates. By familiarizing yourself with the interview questions, you can improve your chances of acing the C++ coding test interview. If you want to work at a multinational company like Amazon and are curious to learn about the interview questions, check out our blog on Amazon coding interview questions. This guide will help you get an understanding of the coding problems asked in the interview.
FAQs
Answer: C++ interviews typically emphasize fundamental concepts such as object-oriented programming (OOP), memory management, and more advanced subjects like the Standard Template Library (STL). The frequently asked questions include:
1. What distinguishes C++ from Java?
2. Can you explain constructors and destructors?
3. How does polymorphism function in C++?
4. What are the different types of inheritance in C++?
5. Explain the concept of copy constructors and assignment operators.
To prepare effectively for a C++ interview, here is what you need to do:
1. Review essential concepts like data types, loops, and functions
2. Deepen your understanding of OOP principles (inheritance, polymorphism, encapsulation)
3. Work on coding challenges that involve arrays, pointers, and STL containers
4. Understand memory management topics, particularly dynamic allocation, and pointers
5. Solve C++ coding problems
Answer: Generally, advanced topics are discussed in senior-level interviews. If you are preparing for a senior-level role, here are a few advanced topics that you must focus on in C++ interviews:
1. Multithreading and concurrency using C++ threads
2. Template programming and metaprogramming
3. Mechanisms for exception handling
4. Creating custom data structures with STL
5. Techniques for optimizing performance in C++