Coding Questions Questions

Question Bank › Technical › C++ › Coding Questions

12

Other questions

Q101.Easy
Write a C++ function named `shortenName` that takes a string and returns it trimmed to at most 12 characters. If the string is longer than 12 characters, return only the first 12 characters; otherwise return the string unchanged.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

string shortenName(const string& s) {
    if (s.length() > 12)
        return s.substr(0, 12);
    return s;
}

int main() {
    cout << shortenName("Rajarajeswari") << endl;  // Rajarajeswar
    cout << shortenName("Amit") << endl;            // Amit
    return 0;
}
Explanation: 1. The function `shortenName` accepts a string by const reference. 2. It checks `s.length() > 12`. 3. If true, `s.substr(0, 12)` returns the first 12 characters. 4. Otherwise the original string is returned unchanged. 5. In `main`, "Rajarajeswari" (13 chars) becomes "Rajarajeswar", while "Amit" stays "Amit".
Q102.Easy
Write a C++ program that reads an array of integers and counts how many entries appear more than once (duplicate entries). For example, for the array {4, 7, 4, 9, 7, 4, 2}, the values 4 and 7 are duplicated, so the count of duplicate values is 2.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int main() {
    vector<int> arr = {4, 7, 4, 9, 7, 4, 2};
    unordered_map<int, int> freq;
    for (int x : arr) freq[x]++;
    int dupCount = 0;
    for (auto &p : freq) {
        if (p.second > 1) dupCount++;
    }
    cout << dupCount << endl;
    return 0;
}
Explanation: 1) Traverse the array and store the frequency of each value in an unordered_map. 2) Iterate over the map entries; every value whose frequency is greater than 1 is a duplicate value. 3) Count such values and print the count. 4) For {4,7,4,9,7,4,2}: 4 appears 3 times and 7 appears 2 times, so the duplicate-value count is 2.
Q103.Easy
Write a C++ program to move all zeros in an array to the beginning while maintaining the relative order of the non-zero elements. For example, if the input array is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, the output should be {0, 0, 0, 0, 1, 9, 8, 4, 2, 7, 6}.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
using namespace std;

void moveZerosToFront(vector<int>& arr) {
    int n = arr.size();
    int index = n - 1;
    // Copy non-zero elements to the back, preserving order
    for (int i = n - 1; i >= 0; i--)
        if (arr[i] != 0)
            arr[index--] = arr[i];
    // Fill the rest with zeros
    while (index >= 0)
        arr[index--] = 0;
}

int main() {
    vector<int> arr = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0};
    moveZerosToFront(arr);
    cout << "Array after moving zeros to front: ";
    for (int num : arr)
        cout << num << " ";
    cout << endl;
    return 0;
}
Explanation: 1. Count the number of zeros in the array. 2. Overwrite the first 'count' positions with 0. 3. Traverse the original array (but we need to be careful: after overwriting, the original non-zero values might be lost if we overwrite in place without storing. Actually, the code above overwrites the first 'count' positions with 0, which may destroy some non-zero elements if they were in those positions. To avoid this, we should first copy non-zero elements to a temporary array or use a two-pointer approach. However, the provided code is incorrect because it overwrites the array before reading non-zero elements. Let's correct the approach: Instead, we can create a new array or use a stable partition. A correct method: create a new vector, first push all zeros, then push all non-zeros. Or, count zeros, then fill from the end. But the simplest is to use a new array. Since the answer must be a complete correct program, I'll provide a correct version using a new vector. Corrected program: #include <iostream> #include <vector> using namespace std; void moveZerosToFront(vector<int>& arr) { int n = arr.size(); vector<int> result; // First add all zeros for (int i = 0; i < n; i++) if (arr[i] == 0) result.push_back(0); // Then add all non-zeros for (int i = 0; i < n; i++) if (arr[i] != 0) result.push_back(arr[i]); arr = result; } int main() { vector<int> arr = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}; moveZerosToFront(arr); cout << "Array after moving zeros to front: "; for (int num : arr) cout << num << " "; cout << endl; return 0; } This correctly outputs: 0 0 0 0 1 9 8 4 2 7 6
Q104.Easy
Write a C++ program that dynamically allocates memory for a single integer using the new operator, stores the value 45 in it, prints the value, then releases the memory using the delete operator.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main()
{
    int *ptr;
    ptr = new int;
    *ptr = 45;
    cout << "The value of p is : " << *ptr << endl;
    delete ptr;
    return 0;
}
Explanation: 1. Include <iostream> and use namespace std. 2. Declare an integer pointer ptr. 3. ptr = new int allocates memory for one integer on the heap. 4. *ptr = 45 stores 45 in that memory location. 5. cout prints "The value of p is : 45". 6. delete ptr de-allocates the heap memory (it frees the block, not the pointer variable itself). 7. return 0 ends the program.
Q105.Easy
Write a C++ program that stores the integer 27 in a variable and uses an if statement to check whether it is an odd number. If it is odd, print the message "It is odd number".
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    int num = 27;
    if (num % 2 != 0)
    {
        cout << "It is odd number";
    }
    return 0;
}
Explanation: 1. Include <iostream> and use namespace std so cout works. 2. In main, declare int num = 27. 3. The if condition (num % 2 != 0) checks the remainder when 27 is divided by 2; 27 % 2 = 1, so the condition is true. 4. Since the condition is true, the block runs and prints "It is odd number". 5. return 0 ends the program.
Q106.Easy
Write a C++ program that stores the integer 17 in a variable and uses an if-else statement to print "17 is even" if the number is even, otherwise print "17 is odd".
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int num = 17;
    if (num % 2 == 0) {
        cout << "17 is even";
    } else {
        cout << "17 is odd";
    }
    return 0;
}
Explanation: 1) Include <iostream> and use namespace std. 2) Declare int num = 17. 3) The if condition checks num % 2 == 0. Since 17 % 2 = 1, the condition is false. 4) So the else block runs and prints "17 is odd". 5) return 0 ends the program.
Q107.Easy
Write a C++ program that asks the user to enter an integer (for example, a student's roll number) and then uses an if-else statement to print "Roll number is even" if the number is even, otherwise print "Roll number is odd".
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main() {
    int roll;
    cout << "Enter roll number: ";
    cin >> roll;
    if (roll % 2 == 0) {
        cout << "Roll number is even" << endl;
    } else {
        cout << "Roll number is odd" << endl;
    }
    return 0;
}
Explanation: 1) Include <iostream> and use namespace std for cin/cout. 2) Declare an int variable roll. 3) Prompt the user with cout and read the value using cin. 4) Check roll % 2 == 0: if true, print "Roll number is even". 5) Otherwise (else), print "Roll number is odd". 6) return 0 ends the program.
Q108.Easy
Write a C++ program that reads a student's marks (an integer) and prints the grade using an if-else-if ladder according to these rules: marks below 0 or above 100 -> print "invalid marks"; 0 to 39 -> "Fail"; 40 to 54 -> "D Grade"; 55 to 69 -> "C Grade"; 70 to 84 -> "B Grade"; 85 to 94 -> "A Grade"; 95 to 100 -> "A+ Grade".
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int marks;
    cout << "Enter marks to check grade: ";
    cin >> marks;
    if (marks < 0 || marks > 100)
    {
        cout << "invalid marks";
    }
    else if (marks >= 0 && marks < 40)
    {
        cout << "Fail";
    }
    else if (marks >= 40 && marks < 55)
    {
        cout << "D Grade";
    }
    else if (marks >= 55 && marks < 70)
    {
        cout << "C Grade";
    }
    else if (marks >= 70 && marks < 85)
    {
        cout << "B Grade";
    }
    else if (marks >= 85 && marks < 95)
    {
        cout << "A Grade";
    }
    else if (marks >= 95 && marks <= 100)
    {
        cout << "A+ Grade";
    }
    return 0;
}
Explanation: 1. Read the integer 'marks' from the user. 2. First check if marks is outside 0-100; if so print "invalid marks". 3. Otherwise the if-else-if ladder checks each range in order: 0-39 Fail, 40-54 D Grade, 55-69 C Grade, 70-84 B Grade, 85-94 A Grade, 95-100 A+ Grade. 4. Because the conditions are mutually exclusive and checked top to bottom, exactly one branch executes and prints the correct grade.
Q109.Easy
Write a C++ program that declares an integer pointer, allocates memory for one integer at runtime using the new operator, asks the user to enter a number, stores it in that heap memory, and then prints the entered number. Finally, release the allocated memory using delete.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
int main()
{
    int *marks;          // integer pointer variable declaration
    marks = new int;     // allocating memory on the heap for one integer
    cout << "Enter the marks : " << endl;
    cin >> *marks;
    cout << "Marks entered are " << *marks << endl;
    delete marks;        // releasing the allocated memory
    marks = NULL;
    return 0;
}
Explanation: 1. Declare an integer pointer 'marks' that will hold the address of heap memory. 2. Use 'new int' to allocate memory for one integer on the heap; the operator returns the starting address, which is stored in 'marks'. 3. Read a value from the user directly into the allocated memory using cin >> *marks. 4. Print the stored value using cout << *marks. 5. Free the heap memory with 'delete marks' to avoid a memory leak, then set the pointer to NULL.
Q110.Easy
Write a C++ program that defines a namespace called 'MathOps' containing a variable 'pi' (value 3.14159) and a function 'areaOfCircle' that takes a double radius and returns the area (pi * radius * radius). In the main function, read a radius from the user, then using the 'using' directive for the MathOps namespace, print the area of the circle. Also, demonstrate accessing the variable 'pi' directly after the using directive.
Show answer & explanation
Answer:
#include <iostream>
namespace MathOps {
    double pi = 3.14159;
    double areaOfCircle(double r) {
        return pi * r * r;
    }
}
int main() {
    double radius;
    std::cout << "Enter radius: ";
    std::cin >> radius;
    using namespace MathOps;
    std::cout << "Area of circle: " << areaOfCircle(radius) << std::endl;
    std::cout << "Value of pi: " << pi << std::endl;
    return 0;
}
Explanation: 1. Define a namespace MathOps containing a variable pi and a function areaOfCircle. 2. In main, declare a double variable radius and read input from the user. 3. Use 'using namespace MathOps;' to bring all members of MathOps into the current scope. 4. Call areaOfCircle(radius) to compute and print the area. 5. Also print the value of pi directly, demonstrating that the using directive allows access without the MathOps:: prefix.
Q111.Easy
Write a C++ program that uses the sizeof operator to display the size in bytes of the following data types: int, float, double, and char. Print each size with a descriptive message.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    cout << "Size of int: " << sizeof(int) << " bytes" << endl;
    cout << "Size of float: " << sizeof(float) << " bytes" << endl;
    cout << "Size of double: " << sizeof(double) << " bytes" << endl;
    cout << "Size of char: " << sizeof(char) << " bytes" << endl;
    return 0;
}
Explanation: 1. Include the iostream library and use the std namespace. 2. In main, use cout to print the size of int using sizeof(int). 3. Similarly, print the size of float using sizeof(float). 4. Print the size of double using sizeof(double). 5. Print the size of char using sizeof(char). 6. Each output includes a descriptive message and the unit 'bytes'. 7. Return 0 to end the program.
Q112.Easy
Write a C++ program that asks the user to enter a number and then uses a switch statement to print a message based on the number. If the number is 5, print "It is 5"; if 15, print "It is 15"; if 25, print "It is 25"; otherwise, print "Not 5, 15 or 25".
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    switch (num) {
        case 5:
            cout << "It is 5";
            break;
        case 15:
            cout << "It is 15";
            break;
        case 25:
            cout << "It is 25";
            break;
        default:
            cout << "Not 5, 15 or 25";
            break;
    }
    return 0;
}
Explanation: 1. Include the iostream library and use the std namespace. 2. Declare an integer variable num. 3. Prompt the user to enter a number and read it into num. 4. Use a switch statement on num. 5. For case 5, print "It is 5" and break. 6. For case 15, print "It is 15" and break. 7. For case 25, print "It is 25" and break. 8. For any other value, the default case prints "Not 5, 15 or 25" and breaks. 9. Return 0 to end the program.
Q113.Easy
Write a C++ program that demonstrates a virtual function: define a base class Shape with a virtual function show(), and a derived class Circle that overrides show(). In main(), create a Circle object, store its address in a Shape pointer, and call show() through the pointer so that the derived version is invoked at runtime.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Shape {
public:
    virtual void show() {
        cout << "Shape class is invoked" << endl;
    }
};

class Circle : public Shape {
public:
    void show() override {
        cout << "Circle class is invoked" << endl;
    }
};

int main() {
    Shape* s;      // pointer of base class
    Circle c;      // object of derived class
    s = &c;
    s->show();     // late binding occurs
    return 0;
}
Explanation: 1) Shape declares show() as virtual, so calls through a Shape pointer are resolved at runtime. 2) Circle inherits from Shape and overrides show() with its own message. 3) In main, a Shape pointer s is assigned the address of a Circle object c. 4) Calling s->show() uses dynamic (late) binding and picks Circle::show(), printing 'Circle class is invoked'. 5) Without the virtual keyword, the base version would be called instead.
Q114.Medium
Write a C++ program that stores the integers 10, 20, 30, 40, 50 in a vector. Using a normal iterator, print all elements in forward order separated by spaces. Then, using a reverse_iterator, print all elements in reverse order separated by spaces. Each list should be on its own line.
Show answer & explanation
Answer:
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
   vector<int> v{10,20,30,40,50};
   vector<int>::iterator itr;
   vector<int>::reverse_iterator ritr;
   for(itr = v.begin(); itr != v.end(); itr++)
   {
       cout<<*itr<<" ";
   }
   cout<<'\n';
   for(ritr = v.rbegin(); ritr != v.rend(); ritr++)
   {
       cout<<*ritr<<" ";
   }
   cout<<'\n';
   return 0;
}
Explanation: 1. Create vector<int> v with values 10,20,30,40,50. 2. Declare a normal iterator itr and loop from v.begin() to v.end(), dereferencing with *itr to print each value: 10 20 30 40 50. 3. Print a newline. 4. Declare a reverse_iterator ritr and loop from v.rbegin() to v.rend(); dereferencing gives elements from the back: 50 40 30 20 10. 5. Note: the second loop must print *ritr (not *itr) to output the reversed values correctly.
Q115.Medium
Write a C++ program that defines a class named 'Student' with a user-defined copy constructor. The class should have a data member 'roll' (integer). Include a parameterized constructor to initialize 'roll', and a copy constructor that copies the roll number from another Student object. In main(), create a Student object s1 with roll number 101, then create a copy s2 using the copy constructor, and display the roll numbers of both objects.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Student {
    int roll;
public:
    Student(int r) {
        roll = r;
    }
    Student(const Student &s) {
        roll = s.roll;
    }
    void display() {
        cout << "Roll number: " << roll << endl;
    }
};

int main() {
    Student s1(101);
    Student s2(s1);
    cout << "s1: ";
    s1.display();
    cout << "s2: ";
    s2.display();
    return 0;
}
Explanation: 1. Define class Student with private integer roll. 2. Parameterized constructor Student(int r) sets roll = r. 3. Copy constructor Student(const Student &s) sets roll = s.roll. 4. display() prints the roll number. 5. In main(), create s1 with roll 101 using parameterized constructor. 6. Create s2 as a copy of s1 using the copy constructor. 7. Call display() for both objects to show that s2 has the same roll number as s1.
Q116.Medium
Write a C++ program to demonstrate shallow copy. The default copy constructor produces a shallow copy, which copies all member variables as they are, including pointers, so the source and copy share the same memory. Use a class named 'Employee' with integer members 'id' and 'salary', and an integer pointer 'bonus'. In main, create an object e1, set its data to id=101, salary=50000, and *bonus=5000. Then create a copy e2 using the default copy constructor, and display the values of e2.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Employee {
    int id;
    int salary;
    int *bonus;
public:
    Employee() {
        bonus = new int;
    }

    void setData(int i, int s, int b) {
        id = i;
        salary = s;
        *bonus = b;
    }

    void showData() {
        cout << "ID: " << id << endl;
        cout << "Salary: " << salary << endl;
        cout << "Bonus: " << *bonus << endl;
    }
};

int main() {
    Employee e1;
    e1.setData(101, 50000, 5000);
    Employee e2 = e1;
    e2.showData();
    return 0;
}
Explanation: 1. Define class Employee with private members id, salary, and int pointer bonus. 2. Default constructor allocates memory for bonus. 3. setData assigns values to id, salary, and *bonus. 4. showData prints the values. 5. In main, create e1, set its data, and create e2 as a copy of e1 using the default copy constructor. 6. The default copy constructor performs a shallow copy: it copies the pointer bonus as is, so e1.bonus and e2.bonus point to the same memory location. 7. e2.showData() prints the values, which are the same as e1's because they share the same memory.
Q117.Medium
Write a C++ program to demonstrate deep copy. Deep copy dynamically allocates memory for the copy and copies the actual value, so the source and copy have distinct memory locations. This requires a user-defined copy constructor. Use a class named 'Student' with integer members 'roll' and 'marks', and an integer pointer 'ptr'. In main, create an object s1, set its data to roll=10, marks=85, and *ptr=95. Then create a copy s2 using the copy constructor, and display the values of s2.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Student {
public:
    int roll;
    int marks;
    int *ptr;

    Student() {
        ptr = new int;
    }

    Student(const Student &s) {
        roll = s.roll;
        marks = s.marks;
        ptr = new int;
        *ptr = *(s.ptr);
    }

    void setData(int r, int m, int p) {
        roll = r;
        marks = m;
        *ptr = p;
    }

    void showData() {
        cout << "Roll: " << roll << endl;
        cout << "Marks: " << marks << endl;
        cout << "Pointer value: " << *ptr << endl;
    }
};

int main() {
    Student s1;
    s1.setData(10, 85, 95);
    Student s2 = s1;
    s2.showData();
    return 0;
}
Explanation: 1. Define class Student with members roll, marks, and int pointer ptr. 2. Default constructor allocates memory for ptr. 3. Copy constructor takes a const reference, copies roll and marks, allocates new memory for ptr, and copies the value pointed to by s.ptr. 4. setData assigns values to roll, marks, and *ptr. 5. showData prints the values. 6. In main, create s1, set its data, create s2 as a copy of s1 using the copy constructor, and call s2.showData(). 7. Because the copy constructor allocates new memory, s2.ptr points to a different location than s1.ptr, demonstrating deep copy.
Q118.Medium
Write a C++ program that creates two vectors v1 = {1,2,3,4,5} and v2 = {3,4,5,6,7}. Using an insert_iterator (inserter) positioned at the 4th element of v1 (i.e., after advancing the iterator by 3 from v1.begin()), copy all elements of v2 into v1. Then print all elements of v1 separated by spaces.
Show answer & explanation
Answer:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v1, v2;
    for (int i = 1; i <= 5; i++) {
        v1.push_back(i);
        v2.push_back(i + 2);
    }
    vector<int>::iterator it = v1.begin();
    advance(it, 3);
    copy(v2.begin(), v2.end(), inserter(v1, it));
    cout << "Elements of v1 are :";
    for (it = v1.begin(); it != v1.end(); ++it)
        cout << ' ' << *it;
    cout << '\n';
    return 0;
}
Explanation: 1. Fill v1 with 1..5 and v2 with 3..7 (i+2). 2. it = v1.begin(); advance(it,3) moves it to point at the 4th element (value 4). 3. inserter(v1, it) creates an insert_iterator that inserts before position it and keeps the iterator valid as v1 grows. 4. copy inserts v2's elements (3,4,5,6,7) before the 4th element, so v1 becomes 1 2 3 3 4 5 6 7 4 5. 5. The loop prints: Elements of v1 are : 1 2 3 3 4 5 6 7 4 5
Q119.Medium
Write a C++ program that uses an ostream_iterator to print the elements of a vector of integers separated by a comma and a space, using the standard output stream (cout). The vector should contain the values 10, 20, 30, 40, 50. Use the copy algorithm together with ostream_iterator so that the output is: 10, 20, 30, 40, 50
Show answer & explanation
Answer:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> nums;
    for (int i = 1; i <= 5; i++)
        nums.push_back(i * 10);

    ostream_iterator<int> out(cout, ", ");
    copy(nums.begin(), nums.end() - 1, out);
    cout << nums.back() << endl;
    return 0;
}
Explanation: 1. Include <iterator> for ostream_iterator and <algorithm> for copy. 2. Build a vector nums containing 10,20,30,40,50 using a loop. 3. Create ostream_iterator<int> out(cout, ", ") which writes each assigned value to cout followed by the delimiter ", ". 4. copy(nums.begin(), nums.end(), out) assigns each element to the iterator, which prints it. 5. Output: 10, 20, 30, 40, 50 (the trailing delimiter is harmless).
Q120.Medium
Write a C++ program that demonstrates aggregation. Create a class `Home` with data members `line`, `area`, `city` and a constructor. Create a class `Student` that HAS-A `Home` (stores a pointer to a `Home` object) along with its own `rollNo` and `name`. The `Student` constructor should take the roll number, name and a `Home*`. Add a `show()` method that prints the roll number, name, home line, area and city separated by spaces. In `main`, create a `Home` object with line "12, MG Road", area "Pune", city "MH", then a `Student` with roll 205 and name "Rohan" using that home, and call `show()`.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
class Home {
    public:
    string line, area, city;
    Home(string line, string area, string city)
    {
        this->line = line;
        this->area = area;
        this->city = city;
    }
};
class Student
{
    private:
    Home* home;  // Student HAS-A Home
    public:
    int rollNo;
    string name;
    Student(int rollNo, string name, Home* home)
    {
        this->rollNo = rollNo;
        this->name = name;
        this->home = home;
    }
    void show()
    {
        cout << rollNo << " " << name << " " <<
            home->line << " " << home->area << " " << home->city << endl;
    }
};
int main(void) {
    Home h1 = Home("12, MG Road", "Pune", "MH");
    Student s1 = Student(205, "Rohan", &h1);
    s1.show();
    return 0;
}
Explanation: 1. `Home` holds the address details and initialises them through its constructor. 2. `Student` stores a `Home*` (a reference to an existing Home object) — this is aggregation, the HAS-A relationship. 3. The `Student` constructor copies rollNo, name and the pointer into its members. 4. `show()` dereferences the stored pointer to print the Home details along with the student details. 5. In `main`, a `Home` is created first, then a `Student` is given its address with `&h1`, and `show()` prints: 205 Rohan 12, MG Road Pune MH.
Q121.Medium
Write a C++ program that demonstrates how the break statement inside an inner loop only exits the inner loop. Use nested for loops: the outer loop runs for i from 1 to 3, and the inner loop runs for j from 1 to 3. Inside the inner loop, if i equals 2 and j equals 2, execute a break statement. Otherwise, print the values of i and j separated by a space, followed by a newline. What is the output of the program?
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (i == 2 && j == 2) {
                break;
            }
            cout << i << " " << j << "\n";
        }
    }
    return 0;
}
Explanation: 1. The outer loop runs for i = 1, 2, 3. 2. For each i, the inner loop runs for j = 1, 2, 3. 3. When i=1: j=1 prints "1 1", j=2 prints "1 2", j=3 prints "1 3". 4. When i=2: j=1 prints "2 1"; at j=2, the condition i==2 && j==2 is true, so break exits the inner loop. Thus j=3 is not executed for i=2. 5. When i=3: j=1 prints "3 1", j=2 prints "3 2", j=3 prints "3 3". 6. The output is: 1 1 1 2 1 3 2 1 3 1 3 2 3 3
Q122.Medium
Write a C++ program that demonstrates call by reference by swapping two integers. Declare two integer variables a = 15 and b = 8 in main. Write a function swapRef that takes two integer pointers and swaps the values they point to. Call swapRef with the addresses of a and b. After the call, print the values of a and b each on a new line.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

void swapRef(int *p, int *q) {
    int temp = *p;
    *p = *q;
    *q = temp;
}

int main() {
    int a = 15, b = 8;
    swapRef(&a, &b);
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    return 0;
}
Explanation: 1. Define swapRef that takes two int pointers. 2. Inside swapRef, use a temporary variable to swap the values pointed to by p and q. 3. In main, declare a=15 and b=8. 4. Call swapRef with &a and &b, passing addresses. 5. The function modifies the original variables because it receives their addresses. 6. Print the new values: a becomes 8 and b becomes 15.
Q123.Medium
Write a C++ program that demonstrates data abstraction: create a class 'WaterPump' with private data members (speed level and mode) and public member functions to switch the pump ON/OFF, set the speed, set the mode, and display the current status. The private members must not be accessible directly from main(). Use the class in main() to switch the pump on, set speed to 2, set mode to 1, and print the status.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class WaterPump {
private:
    bool isOn;
    int speed;
    int mode;
public:
    WaterPump() {
        isOn = false;
        speed = 0;
        mode = 0;
    }
    void switchOn() { isOn = true; }
    void switchOff() { isOn = false; }
    void setSpeed(int s) { if (isOn) speed = s; }
    void setMode(int m) { if (isOn) mode = m; }
    void showStatus() {
        cout << "Pump is " << (isOn ? "ON" : "OFF") << endl;
        cout << "Speed level: " << speed << endl;
        cout << "Mode: " << mode << endl;
    }
};

int main() {
    WaterPump p;
    p.switchOn();
    p.setSpeed(2);
    p.setMode(1);
    p.showStatus();
    return 0;
}
Explanation: 1) The class WaterPump keeps isOn, speed and mode as private members, so main() cannot touch them directly — this is data abstraction. 2) Public functions switchOn(), setSpeed(), setMode() and showStatus() form the interface. 3) In main() we create an object p, switch it on, set speed 2 and mode 1. 4) showStatus() prints: Pump is ON, Speed level: 2, Mode: 1.
Q124.Medium
Write a C++ program that demonstrates passing a function pointer as a parameter to another function. Define two functions: 'greet' that prints "Hello from greet" and 'execute' that takes a function pointer as a parameter and calls the function it points to. In main, call 'execute' with 'greet' as the argument.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

void greet() {
    cout << "Hello from greet" << endl;
}

void execute(void (*funcPtr)()) {
    funcPtr();
}

int main() {
    execute(greet);
    return 0;
}
Explanation: 1. The function greet is defined to print a message. 2. The function execute takes a parameter funcPtr which is a pointer to a function taking no arguments and returning void. 3. Inside execute, funcPtr() calls the function pointed to. 4. In main, execute(greet) passes the address of greet to execute. 5. execute calls greet via the pointer, printing the message.
Q125.Medium
Write a C++ program that demonstrates ambiguity resolution in multiple inheritance. Create a base class 'X' with a public method 'show()' that prints "Class X". Create another base class 'Y' with a public method 'show()' that prints "Class Y". Derive a class 'Z' from both 'X' and 'Y' using multiple inheritance. In 'Z', define a method 'display()' that calls 'show()' from both base classes explicitly using the scope resolution operator. In the main function, create an object of 'Z' and call 'display()'.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class X {
public:
    void show() {
        cout << "Class X" << endl;
    }
};

class Y {
public:
    void show() {
        cout << "Class Y" << endl;
    }
};

class Z : public X, public Y {
public:
    void display() {
        X::show();
        Y::show();
    }
};

int main() {
    Z z;
    z.display();
    return 0;
}
Explanation: 1. Define class X with a public method show() that prints "Class X". 2. Define class Y with a public method show() that prints "Class Y". 3. Define class Z inheriting from both X and Y. This creates ambiguity because both base classes have a method named show(). 4. In Z, define display() that explicitly calls X::show() and Y::show() using the scope resolution operator to resolve the ambiguity. 5. In main(), create a Z object and call display(), which will output both messages.
Q126.Medium
Write a C++ program that demonstrates hybrid inheritance. Create a base class 'Person' with a protected integer 'age' and a public method 'getAge()' to input the age. Derive a class 'Student' from 'Person' that adds a protected integer 'rollNo' and a public method 'getRollNo()' to input the roll number. Derive another class 'Employee' from 'Person' that adds a protected integer 'empId' and a public method 'getEmpId()' to input the employee ID. Finally, create a class 'Intern' that inherits from both 'Student' and 'Employee', and has a public method 'display()' that prints the age, roll number, and employee ID. In the main function, create an object of 'Intern', call the input methods, and then call 'display()'.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Person {
protected:
    int age;
public:
    void getAge() {
        cout << "Enter age: ";
        cin >> age;
    }
};

class Student : virtual public Person {
protected:
    int rollNo;
public:
    void getRollNo() {
        cout << "Enter roll number: ";
        cin >> rollNo;
    }
};

class Employee : virtual public Person {
protected:
    int empId;
public:
    void getEmpId() {
        cout << "Enter employee ID: ";
        cin >> empId;
    }
};

class Intern : public Student, public Employee {
public:
    void display() {
        cout << "Age: " << age << endl;
        cout << "Roll No: " << rollNo << endl;
        cout << "Employee ID: " << empId << endl;
    }
};

int main() {
    Intern intern;
    intern.getAge();
    intern.getRollNo();
    intern.getEmpId();
    intern.display();
    return 0;
}
Explanation: 1. Define base class Person with protected data member age and public method getAge() to read age. 2. Define class Student inheriting publicly from Person, adding protected rollNo and public getRollNo(). 3. Define class Employee inheriting publicly from Person, adding protected empId and public getEmpId(). 4. Define class Intern inheriting from both Student and Employee (hybrid inheritance). It can access age, rollNo, and empId because they are protected in the base classes. 5. In Intern's display(), output the three values. 6. In main(), create an Intern object, call getAge(), getRollNo(), getEmpId(), then display().
Q127.Medium
Write a C++ program that demonstrates an abstract class. Create an abstract base class named Vehicle that has a pure virtual function called start(). Derive two classes from it: Bike and Truck. Each derived class must provide its own implementation of start() that prints "bike starts with kick..." and "truck starts with ignition..." respectively. In main(), create one object of each derived class and call start() on both.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Vehicle
{
    public:
    virtual void start() = 0;
};

class Bike : public Vehicle
{
    public:
    void start()
    {
        cout << "bike starts with kick..." << endl;
    }
};

class Truck : public Vehicle
{
    public:
    void start()
    {
        cout << "truck starts with ignition..." << endl;
    }
};

int main()
{
    Bike b;
    Truck t;
    b.start();
    t.start();
    return 0;
}
Explanation: 1. Vehicle declares 'virtual void start() = 0;' which makes it a pure virtual function, so Vehicle becomes an abstract class and cannot be instantiated. 2. Bike publicly inherits Vehicle and overrides start() to print the bike message. 3. Truck publicly inherits Vehicle and overrides start() to print the truck message. 4. In main(), objects of Bike and Truck are created (allowed because both provide start()). 5. Calling b.start() and t.start() runs each class's own implementation, giving the two different outputs.
Q128.Medium
Write a C++ program that defines a class Counter with a private integer member count initialised to 5. Overload the unary prefix ++ operator so that it increases count by 3, and provide a member function show() that prints the count. In main, create a Counter object, apply ++ to it, and display the result.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Counter
{
private:
    int count;
public:
    Counter() : count(5) {}
    void operator++()
    {
        count = count + 3;
    }
    void show()
    {
        cout << "The Count is: " << count;
    }
};

int main()
{
    Counter c;
    ++c;
    c.show();
    return 0;
}
Explanation: 1. The class Counter has a private int count, initialised to 5 in the constructor. 2. The member function void operator++() overloads the prefix ++ operator and adds 3 to count. 3. In main, a Counter object c is created with count = 5. 4. ++c calls the overloaded operator, so count becomes 5 + 3 = 8. 5. c.show() prints 'The Count is: 8'.
Q129.Medium
Write a C++ program that demonstrates call-by-value, call-by-reference with a pointer argument, and call-by-reference with a reference argument. The program should define three functions: one that takes an int by value and returns its square, one that takes an int* and squares the pointed-to value in place, and one that takes an int& and squares the referenced value in place. In main, declare three integer variables initialized to 5, call each function appropriately, and print the results to show that call-by-value does not modify the original variable while the other two do.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int squareByValue(int n) {
    n *= n;
    return n;
}

void squareByPointer(int* n) {
    *n *= *n;
}

void squareByReference(int& n) {
    n *= n;
}

int main() {
    int a = 5, b = 5, c = 5;

    cout << "Call-by-Value:" << endl;
    cout << "Before: a = " << a << endl;
    int result = squareByValue(a);
    cout << "Square returned: " << result << endl;
    cout << "After: a = " << a << " (unchanged)" << endl;

    cout << "\nCall-by-Reference with Pointer:" << endl;
    cout << "Before: b = " << b << endl;
    squareByPointer(&b);
    cout << "After: b = " << b << " (changed)" << endl;

    cout << "\nCall-by-Reference with Reference:" << endl;
    cout << "Before: c = " << c << endl;
    squareByReference(c);
    cout << "After: c = " << c << " (changed)" << endl;

    return 0;
}
Explanation: 1. squareByValue receives a copy of the argument; modifying n inside the function does not affect the original variable. It returns the squared value. 2. squareByPointer receives a pointer to an int; dereferencing and modifying *n changes the original variable. 3. squareByReference receives a reference to an int; modifying n directly changes the original variable. 4. In main, three variables a, b, c are initialized to 5. After calling squareByValue(a), a remains 5, but the returned square (25) is printed. 5. After calling squareByPointer(&b), b becomes 25. After calling squareByReference(c), c becomes 25. 6. The output demonstrates that only pointer and reference parameters allow modification of the caller's variable.
Q130.Medium
Write a C++ program that demonstrates run-time polymorphism using a base class 'Vehicle' with a virtual function 'move()', and two derived classes 'Car' and 'Bike' that each override 'move()'. In main, create objects of both derived classes and call 'move()' through a base-class pointer to show which version runs.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Vehicle {                 // base class
public:
    virtual void move() {       // virtual function
        cout << "Vehicle is moving..." << endl;
    }
};

class Car : public Vehicle {
public:
    void move() override {
        cout << "Car is driving on the road..." << endl;
    }
};

class Bike : public Vehicle {
public:
    void move() override {
        cout << "Bike is riding on the street..." << endl;
    }
};

int main() {
    Vehicle* v;
    Car c;
    Bike b;

    v = &c;
    v->move();   // calls Car::move()

    v = &b;
    v->move();   // calls Bike::move()

    return 0;
}
Explanation: 1) 'Vehicle' declares 'move()' as virtual, so the call is resolved at run time based on the actual object. 2) 'Car' and 'Bike' each override 'move()' with their own message. 3) In main, a base pointer 'v' first points to a Car object; v->move() calls Car::move(). 4) Then 'v' points to a Bike object; v->move() calls Bike::move(). 5) Because of the virtual keyword, the derived versions run even though the pointer type is Vehicle*.
Q131.Medium
Write a C++ program that demonstrates runtime polymorphism with data members. Create a base class 'Shape' with a data member 'color' initialized to "Red". Derive a class 'Circle' from 'Shape' that hides the 'color' member with its own 'color' initialized to "Blue". In the main function, create an object of 'Circle' and use a 'Shape' reference to it. Print the 'color' using the reference and also print the 'color' using the 'Circle' object directly. Explain why the outputs differ.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

class Shape {
public:
    string color = "Red";
};

class Circle : public Shape {
public:
    string color = "Blue";
};

int main() {
    Circle c;
    Shape &ref = c;  // reference to base class
    cout << "Color via Shape reference: " << ref.color << endl;
    cout << "Color via Circle object: " << c.color << endl;
    return 0;
}
Explanation: 1. Define a base class 'Shape' with a public data member 'color' set to "Red". 2. Define a derived class 'Circle' that inherits from 'Shape' and declares its own 'color' member set to "Blue". This hides the base class member. 3. In main, create a 'Circle' object 'c'. 4. Create a reference 'ref' of type 'Shape&' and bind it to 'c'. This is allowed because 'Circle' is a 'Shape'. 5. Access 'ref.color'. Since 'ref' is a reference to 'Shape', it accesses the 'color' member of the 'Shape' part of the object, which is "Red". Data members are not polymorphic; they are resolved at compile time based on the static type of the reference. 6. Access 'c.color' directly. This accesses the 'color' member of 'Circle', which is "Blue". 7. Therefore, the outputs are "Red" and "Blue", demonstrating that data members do not exhibit runtime polymorphism.
Q132.Medium
Write a C++ program that demonstrates pass-by-reference. In main, declare an integer variable 'total' with value 40 and print it. Then call a function 'update' that takes an int reference parameter and sets it to 15. After the call, print the value of 'total' again to show that the original variable was modified.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;
void update(int &);
int main()
{
    int total = 40;
    std::cout << "Value of 'total' is :" << total << std::endl;
    update(total);
    std::cout << "Now value of 'total' is :" << total << std::endl;
    return 0;
}
void update(int &m)
{
    m = 15;
}
Explanation: Step 1: Declare the function prototype void update(int &); so the compiler knows it takes a reference. Step 2: In main, set int total = 40 and print it, giving "Value of 'total' is :40". Step 3: Call update(total); because the parameter is a reference, 'm' becomes another name for 'total' (no copy is made). Step 4: Inside update, m = 15 changes the original 'total' to 15. Step 5: Back in main, printing total now shows 15, proving the original variable was modified through the reference.
Q133.Medium
Write a C++ program that demonstrates handling the SIGINT signal. Use a global variable of type volatile std::sig_atomic_t to record the signal status. Install a handler for SIGINT with signal(), then call raise(SIGINT) to trigger it. After raise() returns, print the recorded signal status value to the console.
Show answer & explanation
Answer:
#include <csignal>
#include <iostream>

namespace
{
    volatile std::sig_atomic_t gSignalStatus = 0;
}

void signalHandler(int sig)
{
    gSignalStatus = sig;
}

int main()
{
    signal(SIGINT, signalHandler);
    raise(SIGINT);
    std::cout << "Signal status: " << gSignalStatus << std::endl;
    return 0;
}
Explanation: 1. Include <csignal> for signal handling and <iostream> for printing. 2. In an anonymous namespace, declare a volatile std::sig_atomic_t variable gSignalStatus initialized to 0; volatile and sig_atomic_t ensure safe access from a signal handler. 3. Define signalHandler(int sig) that stores sig into gSignalStatus. 4. In main(), register signalHandler for SIGINT using signal(SIGINT, signalHandler). 5. Call raise(SIGINT) to deliver SIGINT to the process; the handler executes and sets gSignalStatus to the SIGINT value. 6. Print gSignalStatus, which shows the numeric value of SIGINT (typically 2 on Linux).
Q134.Medium
Write a C++ program that defines a class template named 'Box' with one template parameter 'T'. The class should store a single value of type T and provide a constructor to set it and a member function 'show()' that prints the stored value. In main(), create a Box<int> holding 25 and a Box<string> holding "Namaste", and call show() on both.
Show answer & explanation
Answer:
#include <iostream>
#include <string>
using namespace std;

template <class T>
class Box {
    T value;
public:
    Box(T v) { value = v; }
    void show() { cout << value << endl; }
};

int main() {
    Box<int> b1(25);
    Box<string> b2("Namaste");
    b1.show();
    b2.show();
    return 0;
}
Explanation: 1. 'template <class T>' before the class makes it a generic class template. 2. The member 'value' has type T, decided when an object is created. 3. The constructor Box(T v) stores the passed value. 4. show() prints the stored value. 5. In main, Box<int> makes T=int (prints 25) and Box<string> makes T=string (prints Namaste). 6. Output: 25 then Namaste on separate lines.
Q135.Medium
Write a C++ program that demonstrates a class template with a non-type template argument. Create a template class called FixedBox that takes a type parameter T and an integer non-type parameter cap (the capacity). The class should store an array of T of size cap and provide a method fill(T value) that sets every element to value, and a method total() that returns the sum of all elements. In main(), create a FixedBox<int, 4>, fill it with 7, and print the total.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

template <class T, int cap>
class FixedBox {
    T arr[cap];
public:
    void fill(T value) {
        for (int i = 0; i < cap; i++)
            arr[i] = value;
    }
    T total() {
        T sum = 0;
        for (int i = 0; i < cap; i++)
            sum += arr[i];
        return sum;
    }
};

int main() {
    FixedBox<int, 4> box;
    box.fill(7);
    cout << box.total() << endl;
    return 0;
}
Explanation: 1) The template header template <class T, int cap> declares a type parameter T and a non-type integer parameter cap. 2) Inside the class, T arr[cap]; creates a fixed-size array whose size is known at compile time from cap. 3) fill() loops from 0 to cap-1 and assigns the given value to each element. 4) total() adds all elements and returns the sum. 5) In main(), FixedBox<int, 4> makes cap = 4 and T = int; filling with 7 gives four 7s, so total() prints 28.
Q136.Medium
Write a C++ program to check whether the sequence of numbers in a given array is an "Arithmetic" sequence or a "Geometric" sequence. Return -1 if the sequence is neither "Arithmetic" nor "Geometric". For example, the array {3, 6, 12, 24} is Geometric, {5, 10, 15, 20} is Arithmetic, and {2, 4, 7, 11} is neither.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
using namespace std;

int classify(vector<int> &a) {
    int n = a.size();
    if (n < 2) return 1; // trivially both; treat as Arithmetic
    bool isArith = true, isGeo = true;
    int d = a[1] - a[0];
    for (int i = 2; i < n; i++)
        if (a[i] - a[i-1] != d) { isArith = false; break; }
    if (a[0] == 0) {
        isGeo = false;
    } else {
        // check constant ratio using cross multiplication to avoid fractions
        for (int i = 2; i < n; i++)
            if ((long long)a[i] * a[i-2] != (long long)a[i-1] * a[i-1]) { isGeo = false; break; }
    }
    if (isArith) return 1;
    if (isGeo) return 2;
    return -1;
}

int main() {
    vector<int> a1 = {3, 6, 12, 24};
    vector<int> a2 = {5, 10, 15, 20};
    vector<int> a3 = {2, 4, 7, 11};
    cout << classify(a1) << endl; // 2 -> Geometric
    cout << classify(a2) << endl; // 1 -> Arithmetic
    cout << classify(a3) << endl; // -1 -> neither
    return 0;
}
Explanation: 1) For Arithmetic, compute common difference d = a[1]-a[0] and verify every consecutive difference equals d. 2) For Geometric, verify a[i]*a[i-2] == a[i-1]*a[i-1] for all i (avoids division and fractions); handle a[0]==0 specially. 3) Return 1 if Arithmetic, 2 if Geometric, -1 if neither. 4) {3,6,12,24}: differences 3,6,12 not constant, but ratios 2,2,2 constant -> Geometric (2). 5) {5,10,15,20}: differences all 5 -> Arithmetic (1). 6) {2,4,7,11}: differences 2,3,4 and ratios 2,1.75,1.57 -> neither (-1).
Q137.Medium
Write a C++ program to find the largest sum of a contiguous subarray in a given array of integers. Use Kadane's algorithm. Your program should read an integer n (the number of elements), then n integers, and output the maximum subarray sum. For example, if the input is:
8
-2 1 -3 4 -1 2 1 -5
Then the output should be 6, because the subarray [4, -1, 2, 1] has the largest sum.
Show answer & explanation
Answer:
#include <iostream>
#include <climits>
using namespace std;

int main() {
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    int max_so_far = INT_MIN;
    int max_ending_here = 0;
    for (int i = 0; i < n; i++) {
        max_ending_here += arr[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    cout << max_so_far << endl;
    return 0;
}
Explanation: 1. Read the number of elements n. 2. Read the array elements into arr. 3. Initialize max_so_far to the smallest possible integer (INT_MIN) and max_ending_here to 0. 4. Loop through each element: a. Add the current element to max_ending_here. b. If max_so_far is less than max_ending_here, update max_so_far. c. If max_ending_here becomes negative, reset it to 0. 5. After the loop, max_so_far holds the maximum subarray sum. 6. Print max_so_far.
Q138.Medium
Write a C++ program that reads a count k and prints the sum of the first k prime numbers (for example, if k = 5 the first five primes are 2, 3, 5, 7, 11 and their sum is 28). If k is 0, print nothing.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

int main() {
    const int LIMIT = 1000000;
    const int ROOT = 1000;
    int k;
    int marked[LIMIT + 1] = {0};
    int i, j;
    marked[0] = 1;
    marked[1] = 1;
    cin >> k;
    for (i = 4; i <= LIMIT; i += 2)
        marked[i] = 1;
    for (i = 3; i <= ROOT; i += 2)
        for (j = i + i; j <= LIMIT; j += i)
            marked[j] = 1;
    if (k == 0)
        return 0;
    long long sum = 0;
    int count = 0;
    for (i = 2; count < k; i++) {
        if (marked[i] == 0) {
            count++;
            sum += i;
        }
    }
    cout << "Sum of the first " << k << " prime numbers is: " << sum;
    return 0;
}
Explanation: 1) A boolean-style array marked[] of size 1000001 is created, all zeros meaning 'assume prime'. 2) 0 and 1 are marked as non-prime (set to 1). 3) All even numbers from 4 onwards are marked non-prime. 4) For each odd number i from 3 to 1000 (square root of the limit), all multiples j = 2i, 3i, ... are marked non-prime — this is the Sieve of Eratosthenes. 5) The program reads k; if k is 0 it stops without printing. 6) It then scans from 2 upward, adding each unmarked (prime) number to sum until k primes have been collected. 7) Finally it prints the sum of those first k primes.
Q139.Medium
Write a C++ program that reads an odd integer m (the order of a matrix) and prints an m×m magic square using the Siamese (De la Loubère) method: place 1 in the middle of the last row, then place each next number one row down and one column right (wrapping around); if that cell is already filled, place the number directly above the previously placed number instead. If m is even, print "Invalid input: Order must be an odd number." and stop.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>

std::vector<std::vector<int>> buildMagicSquare(int m) {
    std::vector<std::vector<int>> grid(m, std::vector<int>(m, 0));
    int value = 1;
    int r = m - 1;      // start at last row
    int c = m / 2;      // middle column
    while (value <= m * m) {
        grid[r][c] = value++;
        int nr = (r + 1) % m;   // one row down, wrapping
        int nc = (c + 1) % m;   // one column right, wrapping
        if (grid[nr][nc] != 0) { // occupied -> go one row up from current cell
            nr = (r - 1 + m) % m;
            nc = c;
        }
        r = nr;
        c = nc;
    }
    return grid;
}

int main() {
    int m;
    std::cout << "Enter the order of the magic square (odd number): ";
    std::cin >> m;
    if (m % 2 == 0) {
        std::cout << "Invalid input: Order must be an odd number." << std::endl;
        return 1;
    }
    std::vector<std::vector<int>> grid = buildMagicSquare(m);
    std::cout << "Magic Square of order " << m << ":\n";
    for (const auto& row : grid) {
        for (int v : row) {
            std::cout << v << "\t";
        }
        std::cout << std::endl;
    }
    return 0;
}
Explanation: 1) Read m; if m is even, print the invalid-input message and exit. 2) Create an m×m grid filled with 0. 3) Start at row m-1 (last row) and column m/2 (middle column) and put 1 there. 4) For each next value, move one row down and one column right, wrapping with modulo m. 5) If that target cell is already occupied, instead move one row up from the current cell (same column). 6) Repeat until m*m values are placed; every row, column and diagonal then sums to the same magic constant. 7) Print the grid row by row separated by tabs.
Q140.Medium
Write a C++ program: Given an n×n chessboard grid, count the total number of rectangles (of any size, including squares) that can be formed using the grid lines. For example, a 2×2 board contains 9 rectangles. Read n from the user and print the total count.
Show answer & explanation
Answer:
#include <iostream>

int countRectangles(int n) {
    int total = 0;
    for (int m = 1; m <= n; ++m) {
        for (int k = 1; k <= n; ++k) {
            total += (n - m + 1) * (n - k + 1);
        }
    }
    return total;
}

int main() {
    int n;
    std::cout << "Enter the size of the board (n): ";
    std::cin >> n;
    std::cout << "Total number of rectangles on a " << n << "x" << n << " board: " << countRectangles(n) << std::endl;
    return 0;
}
Explanation: 1) A rectangle is fixed by choosing 2 of the (n+1) vertical lines and 2 of the (n+1) horizontal lines. 2) The code instead sums over all sizes m×k: a rectangle of height m and width k can be placed in (n-m+1) vertical positions and (n-k+1) horizontal positions. 3) Add (n-m+1)*(n-k+1) for every m,k from 1 to n. 4) For n=2: sizes give 4+2+2+1 = 9 rectangles, matching the example. 5) Print the total.
Q141.Medium
Write a C++ program that takes three integer arrays sorted in ascending order and returns the smallest number common to all three arrays. If there is no common number, return -1. The arrays are already sorted, so use three pointers to find the common element efficiently.
Show answer & explanation
Answer:
#include <iostream>
#include <vector>
using namespace std;

int smallestCommon(const vector<int>& a, const vector<int>& b, const vector<int>& c) {
    int i = 0, j = 0, k = 0;
    while (i < a.size() && j < b.size() && k < c.size()) {
        if (a[i] == b[j] && b[j] == c[k])
            return a[i];
        if (a[i] <= b[j] && a[i] <= c[k])
            i++;
        else if (b[j] <= a[i] && b[j] <= c[k])
            j++;
        else
            k++;
    }
    return -1;
}

int main() {
    vector<int> arr1 = {1, 3, 5, 7, 9};
    vector<int> arr2 = {2, 3, 6, 7, 10};
    vector<int> arr3 = {3, 4, 7, 8, 11};
    int result = smallestCommon(arr1, arr2, arr3);
    cout << result << endl;
    return 0;
}
Explanation: 1. Initialize three pointers i, j, k to 0 for the three arrays. 2. While all pointers are within bounds, compare the elements at the pointers. 3. If all three elements are equal, return that element (it is the smallest common because arrays are sorted). 4. Otherwise, increment the pointer that points to the smallest element (if tie, increment any). 5. If loop ends without finding a common element, return -1. 6. In the example, the common elements are 3 and 7; the smallest is 3, so output is 3.
Q142.Medium
Write a C++ program that displays the current date and time by printing the day, month, year, hour, minute and second separately, using the `<ctime>` library.
Show answer & explanation
Answer:
#include <iostream>
#include <ctime>
using namespace std;

int main() {
    time_t now = time(NULL);
    tm* tPtr = localtime(&now);

    cout << "Current Date and Time :" << endl;
    cout << "------------------------" << endl;
    cout << "seconds = " << tPtr->tm_sec << endl;
    cout << "minutes = " << tPtr->tm_min << endl;
    cout << "hours = " << tPtr->tm_hour << endl;
    cout << "day of month = " << tPtr->tm_mday << endl;
    cout << "month of year = " << (tPtr->tm_mon) + 1 << endl;
    cout << "year = " << (tPtr->tm_year) + 1900 << endl;
    cout << "weekday = " << tPtr->tm_wday << endl;
    cout << "day of year = " << tPtr->tm_yday << endl;
    cout << "daylight savings = " << tPtr->tm_isdst << endl;

    cout << "Current Date: " << tPtr->tm_mday << "/" << (tPtr->tm_mon) + 1 << "/" << (tPtr->tm_year) + 1900 << endl;
    cout << "Current Time: " << tPtr->tm_hour << ":" << tPtr->tm_min << ":" << tPtr->tm_sec << endl;
    return 0;
}
Explanation: 1. `time(NULL)` returns the current calendar time as a `time_t` value. 2. `localtime(&now)` converts it to a `tm` structure holding broken-down local time fields. 3. Each field is printed: `tm_sec`, `tm_min`, `tm_hour`, `tm_mday`, `tm_mon`, `tm_year`, `tm_wday`, `tm_yday`, `tm_isdst`. 4. `tm_mon` counts months from 0, so add 1; `tm_year` counts years since 1900, so add 1900. 5. Finally the date and time are printed in `dd/mm/yyyy` and `hh:mm:ss` format.
Q143.Medium
Write a C++ program that defines a function reverseK that takes a queue of integers and an integer k, and reverses the first k elements of the queue, leaving the rest of the queue unchanged. The function should modify the queue in place. For example, if the queue contains [10, 20, 30, 40, 50] and k = 3, after reversal the queue should be [30, 20, 10, 40, 50]. Assume k is between 1 and the size of the queue.
Show answer & explanation
Answer:
#include <iostream>
#include <queue>
#include <stack>
using namespace std;

void reverseK(queue<int>& q, int k) {
    if (k <= 1 || q.empty()) return;
    stack<int> s;
    int n = q.size();
    // Push first k elements onto stack
    for (int i = 0; i < k; i++) {
        s.push(q.front());
        q.pop();
    }
    // Pop from stack and push back to queue
    while (!s.empty()) {
        q.push(s.top());
        s.pop();
    }
    // Move the remaining elements to the back
    for (int i = 0; i < n - k; i++) {
        q.push(q.front());
        q.pop();
    }
}

int main() {
    queue<int> q;
    q.push(10);
    q.push(20);
    q.push(30);
    q.push(40);
    q.push(50);
    int k = 3;
    reverseK(q, k);
    cout << "Queue after reversing first " << k << " elements: ";
    while (!q.empty()) {
        cout << q.front() << " ";
        q.pop();
    }
    cout << endl;
    return 0;
}
Explanation: 1. The function reverseK takes a queue q and integer k. 2. If k <= 1 or queue is empty, return immediately. 3. Create an empty stack s. 4. Store the original size n = q.size(). 5. Remove the first k elements from the queue and push them onto the stack. This reverses their order. 6. Pop all elements from the stack and push them back into the queue. Now the first k elements are reversed and at the back of the queue. 7. The remaining n-k elements are still at the front of the queue. To restore their original order after the reversed block, dequeue each of the first n-k elements and enqueue them at the back. 8. The queue now has the first k elements reversed and the rest unchanged.
Q144.Medium
Write a C++ program that demonstrates the use of free() to release dynamically allocated memory. The program should allocate memory for 4 integers using malloc, read 4 integer values from the user, print them, then call free() on the pointer. After freeing, print a message 'Memory freed' and then attempt to print the values again (which will show garbage or undefined behavior). Use appropriate headers and namespace.
Show answer & explanation
Answer:
#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    int *ptr;
    ptr = (int*) malloc(4 * sizeof(int));
    if (ptr == NULL) {
        cout << "Memory allocation failed" << endl;
        return 1;
    }
    cout << "Enter 4 integers:" << endl;
    for (int i = 0; i < 4; i++) {
        cin >> ptr[i];
    }
    cout << "You entered: ";
    for (int i = 0; i < 4; i++) {
        cout << ptr[i] << " ";
    }
    cout << endl;
    free(ptr);
    cout << "Memory freed" << endl;
    cout << "Values after free (garbage): ";
    for (int i = 0; i < 4; i++) {
        cout << ptr[i] << " ";
    }
    cout << endl;
    return 0;
}
Explanation: 1. Include <iostream> for input/output and <cstdlib> for malloc and free. 2. Declare an integer pointer ptr. 3. Allocate memory for 4 integers using malloc(4 * sizeof(int)) and cast to int*. 4. Check if allocation succeeded; if not, print error and exit. 5. Prompt user to enter 4 integers and read them into the allocated memory using ptr[i]. 6. Print the entered values. 7. Call free(ptr) to release the memory. 8. Print a confirmation message. 9. Attempt to print the values again; this is undefined behavior and typically shows garbage values.
Q145.Medium
Write a C++ program that dynamically allocates an array of integers using malloc. The program should ask the user for the number of elements, allocate memory accordingly, then read that many integers into the array, print them, and finally free the memory. Use appropriate typecasting and sizeof operator.
Show answer & explanation
Answer:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
    int n;
    cout << "Enter the number of elements: ";
    cin >> n;
    int *arr = (int*) malloc(n * sizeof(int));
    if (arr == nullptr) {
        cout << "Memory allocation failed" << endl;
        return 1;
    }
    for (int i = 0; i < n; ++i) {
        cout << "Enter element " << i+1 << ": ";
        cin >> arr[i];
    }
    cout << "You entered: ";
    for (int i = 0; i < n; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
    free(arr);
    return 0;
}
Explanation: 1. Include <iostream> and <cstdlib> for input/output and malloc/free. 2. In main, declare an integer n and prompt the user to enter the number of elements. 3. Allocate memory using malloc: (int*) malloc(n * sizeof(int)). The typecast converts the void pointer returned by malloc to int*. 4. Check if allocation succeeded (arr != nullptr). If not, print an error and exit. 5. Use a loop to read n integers into the allocated array. 6. Use another loop to print the entered elements. 7. Call free(arr) to release the allocated memory.
Q146.Medium
Write a C++ program that shows what happens when the virtual keyword is NOT used: define a base class Vehicle with a non-virtual function describe() printing a value 7, and a derived class Car that defines its own describe() printing a value 12. In main(), assign a Car object's address to a Vehicle pointer and call describe() through the pointer.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Vehicle {
    int x = 7;
public:
    void describe() {
        cout << "Value of x is : " << x << endl;
    }
};

class Car : public Vehicle {
    int y = 12;
public:
    void describe() {
        cout << "Value of y is : " << y << endl;
    }
};

int main() {
    Vehicle* v;
    Car c;
    v = &c;
    v->describe();   // early binding: base version is called
    return 0;
}
Explanation: 1) Vehicle::describe() is not virtual, so the compiler binds the call statically based on the pointer type. 2) Car defines its own describe(), but this does not affect calls through a Vehicle pointer. 3) In main, v is a Vehicle pointer holding the address of a Car object. 4) v->describe() is resolved at compile time to Vehicle::describe(), so it prints 'Value of x is : 7'. 5) Adding virtual to the base function would make late binding choose Car::describe() instead.
Q147.Medium
Write a C++ program that demonstrates a pure virtual function and runtime polymorphism. Create an abstract base class 'Shape' with a pure virtual function 'area()'. Derive two classes 'Rectangle' and 'Circle' from 'Shape', each implementing 'area()'. In main, create a pointer of type Shape* and use it to call area() for objects of both derived classes. Print the area with a suitable message.
Show answer & explanation
Answer:
#include <iostream>
using namespace std;

class Shape {
public:
    virtual void area() = 0; // pure virtual function
};

class Rectangle : public Shape {
    double length, width;
public:
    Rectangle(double l, double w) : length(l), width(w) {}
    void area() override {
        cout << "Area of rectangle: " << length * width << endl;
    }
};

class Circle : public Shape {
    double radius;
public:
    Circle(double r) : radius(r) {}
    void area() override {
        cout << "Area of circle: " << 3.14159 * radius * radius << endl;
    }
};

int main() {
    Shape* ptr;
    Rectangle rect(5.0, 3.0);
    Circle circ(2.0);

    ptr = &rect;
    ptr->area();

    ptr = &circ;
    ptr->area();

    return 0;
}
Explanation: 1. The abstract base class Shape declares a pure virtual function area(), making Shape abstract. 2. Derived classes Rectangle and Circle provide their own implementations of area(). 3. In main, a Shape pointer ptr is declared. 4. ptr is assigned the address of a Rectangle object, and area() is called, invoking Rectangle's version. 5. ptr is then assigned the address of a Circle object, and area() is called, invoking Circle's version. 6. This demonstrates runtime polymorphism using a pure virtual function.
12

Get In Touch

INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India

contact@intmatedtech.com

TestMyIndia All India Rank