Interview Questions

C++ Language Coding Questions and Answers

  1. Write a C++ program to find the factorial of a number using recursion.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    int factorial(int n) {
        if (n <= 1) return 1;
        return n * factorial(n - 1);
    }
    
    int main() {
        int number = 5;
        cout << "Factorial of " << number << " is " << factorial(number) << endl;
        return 0;
    }
            
  2. Write a C++ program to reverse a string.

    Use the following code:

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string str = "hello";
        reverse(str.begin(), str.end());
        cout << "Reversed string: " << str << endl;
        return 0;
    }
            
  3. Write a C++ program to check if a number is prime.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    bool isPrime(int num) {
        if (num <= 1) return false;
        for (int i = 2; i < num; ++i) {
            if (num % i == 0) return false;
        }
        return true;
    }
    
    int main() {
        int number = 29;
        cout << number << " is " << (isPrime(number) ? "prime" : "not prime") << endl;
        return 0;
    }
            
  4. Write a C++ program to find the largest element in an array.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    int main() {
        int arr[] = {1, 3, 7, 2, 5};
        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;
    }
            
  5. Write a C++ program to sort an array using bubble sort.

    Use the following code:

    #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[] = {64, 34, 25, 12, 22};
        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;
    }
            
  6. Write a C++ program to check if a string is a palindrome.

    Use the following code to check for palindrome:

                
    #include <iostream>
    #include <string>
    using namespace std;
    
    bool isPalindrome(string str) {
        int left = 0, right = str.length() - 1;
        while (left < right) {
            if (str[left++] != str[right--]) return false;
        }
        return true;
    }
    
    int main() {
        string str = "radar";
        cout << str << " is " << (isPalindrome(str) ? "a palindrome" : "not a palindrome") << endl;
        return 0;
    }
                
            
  7. Write a C++ program to count the number of vowels in a string.

    Use the following code to count vowels:

                
    #include <iostream>
    #include <string>
    using namespace std;
    
    int countVowels(string str) {
        int count = 0;
        for (char c : str) {
            if (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;
    }
                
            
  8. Write a C++ program to find the second largest element in an array.

    Use the following code to find the second largest element:

                
    #include <iostream>
    using namespace std;
    
    int findSecondLargest(int arr[], int size) {
        int largest = arr[0];
        int secondLargest = INT_MIN;
        
        for (int i = 1; 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[] = {10, 20, 4, 45, 99};
        int size = sizeof(arr) / sizeof(arr[0]);
        cout << "Second largest element: " << findSecondLargest(arr, size) << endl;
        return 0;
    }
                
            
  9. Write a C++ program to count the number of nodes in a linked list.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    struct Node {
        int data;
        Node *next;
    };
    
    class LinkedList {
        Node *head;
    public:
        LinkedList() { head = nullptr; }
        
        void append(int value) {
            Node *newNode = new Node();
            newNode->data = value;
            newNode->next = nullptr;
            
            if (head == nullptr) {
                head = newNode;
            } else {
                Node *temp = head;
                while (temp->next != nullptr) temp = temp->next;
                temp->next = newNode;
            }
        }
        
        int countNodes() {
            int count = 0;
            Node *temp = head;
            while (temp != nullptr) {
                count++;
                temp = temp->next;
            }
            return count;
        }
    };
    
    int main() {
        LinkedList list;
        list.append(1);
        list.append(2);
        list.append(3);
        cout << "Number of nodes: " << list.countNodes() << endl;
        return 0;
    }
            
  10. Write a C++ program to detect a loop in a linked list.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    struct Node {
        int data;
        Node *next;
    };
    
    class LinkedList {
        Node *head;
    public:
        LinkedList() { head = nullptr; }
        
        void append(int value) {
            Node *newNode = new Node();
            newNode->data = value;
            newNode->next = nullptr;
            
            if (head == nullptr) {
                head = newNode;
            } else {
                Node *temp = head;
                while (temp->next != nullptr) temp = temp->next;
                temp->next = newNode;
            }
        }
        
        bool detectLoop() {
            Node *slow = head;
            Node *fast = head;
            
            while (fast != nullptr && fast->next != nullptr) {
                slow = slow->next;
                fast = fast->next->next;
                
                if (slow == fast) return true;
            }
            return false;
        }
    };
    
    int main() {
        LinkedList list;
        list.append(1);
        list.append(2);
        list.append(3);
        // Creating a loop for testing
        list.head->next->next->next = list.head;
        
        cout << "Loop detected: " << (list.detectLoop() ? "Yes" : "No") << endl;
        return 0;
    }
            
  11. Write a C++ program to find the middle element of a linked list.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    struct Node {
        int data;
        Node *next;
    };
    
    class LinkedList {
        Node *head;
    public:
        LinkedList() { head = nullptr; }
        
        void append(int value) {
            Node *newNode = new Node();
            newNode->data = value;
            newNode->next = nullptr;
            
            if (head == nullptr) {
                head = newNode;
            } else {
                Node *temp = head;
                while (temp->next != nullptr) temp = temp->next;
                temp->next = newNode;
            }
        }
        
        void findMiddle() {
            Node *slow = head;
            Node *fast = head;
            
            while (fast != nullptr && fast->next != nullptr) {
                slow = slow->next;
                fast = fast->next->next;
            }
            
            cout << "Middle element: " << slow->data << endl;
        }
    };
    
    int main() {
        LinkedList list;
        list.append(1);
        list.append(2);
        list.append(3);
        list.append(4);
        list.append(5);
        list.findMiddle();
        return 0;
    }
            
  12. Write a C++ program to implement a queue using a linked list.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    struct Node {
        int data;
        Node *next;
    };
    
    class Queue {
        Node *front, *rear;
    public:
        Queue() { front = rear = nullptr; }
        
        void enqueue(int value) {
            Node *newNode = new Node();
            newNode->data = value;
            newNode->next = nullptr;
            
            if (rear == nullptr) {
                front = rear = newNode;
                return;
            }
            
            rear->next = newNode;
            rear = newNode;
        }
        
        int dequeue() {
            if (front == nullptr) {
                cout << "Queue is empty" << endl;
                return -1;
            }
            
            Node *temp = front;
            int value = temp->data;
            front = front->next;
            if (front == nullptr) rear = nullptr;
            delete temp;
            return value;
        }
        
        bool isEmpty() { return front == nullptr; }
    };
    
    int main() {
        Queue q;
        q.enqueue(10);
        q.enqueue(20);
        cout << "Dequeued element: " << q.dequeue() << endl;
        return 0;
    }
            
  13. Write a C++ program to implement a basic binary tree.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    struct Node {
        int data;
        Node *left, *right;
        
        Node(int value) : data(value), left(nullptr), right(nullptr) {}
    };
    
    class BinaryTree {
        Node *root;
    public:
        BinaryTree() { root = nullptr; }
        
        void insert(int value) {
            root = insertRec(root, value);
        }
        
        Node* insertRec(Node* node, int value) {
            if (node == nullptr) return new Node(value);
            
            if (value < node->data) node->left = insertRec(node->left, value);
            else if (value > node->data) node->right = insertRec(node->right, value);
            
            return node;
        }
        
        void inorder() {
            inorderRec(root);
            cout << endl;
        }
        
        void inorderRec(Node* node) {
            if (node == nullptr) return;
            inorderRec(node->left);
            cout << node->data << " ";
            inorderRec(node->right);
        }
    };
    
    int main() {
        BinaryTree tree;
        tree.insert(50);
        tree.insert(30);
        tree.insert(20);
        tree.insert(40);
        tree.insert(70);
        tree.insert(60);
        tree.insert(80);
        
        cout << "Inorder traversal: ";
        tree.inorder();
        
        return 0;
    }
            
  14. Write a C++ program to find the height of a binary tree.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    struct Node {
        int data;
        Node *left, *right;
        
        Node(int value) : data(value), left(nullptr), right(nullptr) {}
    };
    
    class BinaryTree {
        Node *root;
    public:
        BinaryTree() { root = nullptr; }
        
        void insert(int value) {
            root = insertRec(root, value);
        }
        
        Node* insertRec(Node* node, int value) {
            if (node == nullptr) return new Node(value);
            
            if (value < node->data) node->left = insertRec(node->left, value);
            else if (value > node->data) node->right = insertRec(node->right, value);
            
            return node;
        }
        
        int height() {
            return heightRec(root);
        }
        
        int heightRec(Node* node) {
            if (node == nullptr) return 0;
            int leftHeight = heightRec(node->left);
            int rightHeight = heightRec(node->right);
            return max(leftHeight, rightHeight) + 1;
        }
    };
    
    int main() {
        BinaryTree tree;
        tree.insert(50);
        tree.insert(30);
        tree.insert(20);
        tree.insert(40);
        tree.insert(70);
        tree.insert(60);
        tree.insert(80);
        
        cout << "Height of tree: " << tree.height() << endl;
        
        return 0;
    }
            
  15. Write a C++ program to traverse a binary tree in pre-order.

    Use the following code:

    #include <iostream>
    using namespace std;
    
    struct Node {
        int data;
        Node *left, *right;
        
        Node(int value) : data(value), left(nullptr), right(nullptr) {}
    };
    
    class BinaryTree {
        Node *root;
    public:
        BinaryTree() { root = nullptr; }
        
        void insert(int value) {
            root = insertRec(root, value);
        }
        
        Node* insertRec(Node* node, int value) {
            if (node == nullptr) return new Node(value);
            
            if (value < node->data) node->left = insertRec(node->left, value);
            else if (value > node->data) node->right = insertRec(node->right, value);
            
            return node;
        }
        
        void preorder() {
            preorderRec(root);
            cout << endl;
        }
        
        void preorderRec(Node* node) {
            if (node == nullptr) return;
            cout << node->data << " ";
            preorderRec(node->left);
            preorderRec(node->right);
        }
    };
    
    int main() {
        BinaryTree tree;
        tree.insert(50);
        tree.insert(30);
        tree.insert(20);
        tree.insert(40);
        tree.insert(70);
        tree.insert(60);
        tree.insert(80);
        
        cout << "Pre-order traversal: ";
        tree.preorder();
        
        return 0;
    }
            
  16. Write a C++ program to implement a basic queue using two stacks.

    Use the following C++ code:

    #include <iostream>
    #include <stack>
    
    using namespace std;
    
    class QueueUsingStacks {
        stack<int> stack1, stack2;
        
    public:
        void enqueue(int x) {
            stack1.push(x);
        }
        
        int dequeue() {
            if (stack2.empty()) {
                if (stack1.empty()) {
                    throw runtime_error("Queue is empty");
                }
                while (!stack1.empty()) {
                    stack2.push(stack1.top());
                    stack1.pop();
                }
            }
            int top = stack2.top();
            stack2.pop();
            return top;
        }
        
        bool isEmpty() {
            return stack1.empty() && stack2.empty();
        }
    };
    
    int main() {
        QueueUsingStacks q;
        q.enqueue(1);
        q.enqueue(2);
        cout << q.dequeue() << endl; // 1
        cout << q.dequeue() << endl; // 2
        return 0;
    }
            
  17. Write a C++ program to find the longest subsequence of a given string that is a palindrome.

    Use the following C++ code:

    #include <iostream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    string longestPalindromeSubseq(string s) {
        int n = s.length();
        vector<vector<int>> dp(n, vector<int>(n, 0));
        
        for (int i = 0; i < n; ++i) {
            dp[i][i] = 1;
        }
        
        for (int len = 2; len <= n; ++len) {
            for (int i = 0; i < n - len + 1; ++i) {
                int j = i + len - 1;
                if (s[i] == s[j] && len == 2) {
                    dp[i][j] = 2;
                } else if (s[i] == s[j]) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {
                    dp[i][j] = max(dp[i][j - 1], dp[i + 1][j]);
                }
            }
        }
        
        return to_string(dp[0][n - 1]);
    }
    
    int main() {
        string s = "bbabcbcab";
        cout << "Length of Longest Palindromic Subsequence: " << longestPalindromeSubseq(s) << endl;
        return 0;
    }
            
  18. Write a C++ program to implement the A* (A-star) algorithm for pathfinding.

    Use the following C++ code:

    #include <iostream>
    #include <queue>
    #include <vector>>
    #include <cmath>
    
    using namespace std;
    
    struct Node {
        int x, y;
        int g, h, f;
        Node* parent;
        
        Node(int x, int y, int g, int h, Node* parent = nullptr) : x(x), y(y), g(g), h(h), parent(parent) {
            f = g + h;
        }
        
        bool operator>(const Node& other) const {
            return f > other.f;
        }
    };
    
    int heuristic(int x1, int y1, int x2, int y2) {
        return abs(x1 - x2) + abs(y1 - y2);
    }
    
    vector<Node> aStar(int startX, int startY, int goalX, int goalY) {
        priority_queue<Node, vector<Node>, greater<Node>> openSet;
        vector<vector<bool>> closedSet(100, vector<bool>(100, false));
        
        openSet.emplace(startX, startY, 0, heuristic(startX, startY, goalX, goalY));
        
        while (!openSet.empty()) {
            Node current = openSet.top();
            openSet.pop();
            
            if (current.x == goalX && current.y == goalY) {
                vector<Node> path;
                Node* node = ¤t;
                while (node) {
                    path.push_back(*node);
                    node = node->parent;
                }
                reverse(path.begin(), path.end());
                return path;
            }
            
            closedSet[current.x][current.y] = true;
            
            vector<pair<int, int>> neighbors = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
            for (auto& neighbor : neighbors) {
                int newX = current.x + neighbor.first;
                int newY = current.y + neighbor.second;
                if (newX >= 0 && newX < 100 && newY >= 0 && newY < 100 && !closedSet[newX][newY]) {
                    int g = current.g + 1;
                    int h = heuristic(newX, newY, goalX, goalY);
                    openSet.emplace(newX, newY, g, h, new Node(current));
                }
            }
        }
        
        return {};
    }
    
    int main() {
        vector<Node> path = aStar(0, 0, 5, 5);
        cout << "Path found:" << endl;
        for (const Node& node : path) {
            cout << "(" << node.x << ", " << node.y << ") " << endl;
        }
        return 0;
    }
            
  19. Write a C++ program to perform in-order traversal of a binary tree.

    Use the following C++ code:

    #include <iostream>
    
    using namespace std;
    
    struct TreeNode {
        int value;
        TreeNode* left;
        TreeNode* right;
        
        TreeNode(int v) : value(v), left(nullptr), right(nullptr) {}
    };
    
    void inorderTraversal(TreeNode* root) {
        if (root == nullptr) return;
        inorderTraversal(root->left);
        cout << root->value << " ";
        inorderTraversal(root->right);
    }
    
    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 << "In-order Traversal: ";
        inorderTraversal(root);
        cout << endl;
        
        return 0;
    }
            
  20. Write a C++ program to find the maximum subarray sum using Kadane's algorithm.

    Use the following C++ code:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int maxSubarraySum(const vector<int>& nums) {
        int maxSoFar = nums[0];
        int maxEndingHere = nums[0];
        
        for (size_t i = 1; i < nums.size(); ++i) {
            maxEndingHere = max(nums[i], maxEndingHere + nums[i]);
            maxSoFar = max(maxSoFar, maxEndingHere);
        }
        
        return maxSoFar;
    }
    
    int main() {
        vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        cout << "Maximum Subarray Sum: " << maxSubarraySum(nums) << endl;
        return 0;
    }
            
Creative Footer for Interview Questions